voronoi-go 1.0.1

Core rules and engine for Voronoi Go.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
//! The rules, exercised through the surface a headless consumer has and
//! nothing else.
//!
//! Everything here drives the board the way a bot search does — snap, play,
//! undo — so this file doubles as the proof that the surface is sufficient
//! without anything wrapped around it.

#![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]

use super::{Commit, DeltaError, Game, GameOverError, GameStatus, StonePlayError};
use crate::connectivity::{BoardEdge, Connectivity, CutError, CutKind};
use crate::geometry::LineSegment;
use crate::{Color, GameDelta, Point, PointKey, Stone, StoneId};

const BOARD: f64 = 20.0;

fn p(x: f64, y: f64) -> Point {
    Point::new(x, y)
}

/// Plays at the placeable position nearest `(x, y)`, the way a caller does:
/// snap first, then move.
fn play(game: &mut Game, x: f64, y: f64) -> GameDelta {
    let snapped = game
        .nearest_living_move(p(x, y))
        .expect("the board has room");
    game.try_move(snapped).expect("a legal move")
}

/// Everything a board change has to restore exactly when it is undone.
#[derive(Debug, PartialEq)]
struct Snapshot {
    turn: u32,
    stones: Vec<Stone>,
    captures: (u32, u32),
    status: GameStatus,
    forced_eyes: Vec<Point>,
    zone: Vec<(PointKey, Vec<(u64, bool)>)>,
}

impl Snapshot {
    fn of(game: &Game) -> Self {
        Self {
            turn: game.turn(),
            stones: game.stones().collect(),
            captures: game.captures().into_parts(),
            status: game.status(),
            forced_eyes: game.alive_zone().forced_eyes().collect(),
            zone: game.alive_zone().fingerprint(),
        }
    }
}

/// Whether `value` is `expected` to within a hair — for areas, which are sums
/// of shoelace terms and are never compared exactly.
fn close(value: f64, expected: f64) -> bool {
    (value - expected).abs() <= 1e-9 * expected.abs().max(1.0)
}

// ── Snapping ─────────────────────────────────────────────────────────────────

#[test]
fn an_empty_board_snaps_a_corner_probe_onto_the_inset_corner() {
    let game = Game::new(BOARD);

    assert_eq!(game.nearest_living_move(p(0.5, 0.5)), Some(p(1.0, 1.0)));
}

#[test]
fn a_probe_already_in_the_clear_is_its_own_answer() {
    let game = Game::new(BOARD);

    assert_eq!(game.nearest_living_move(p(7.25, 3.5)), Some(p(7.25, 3.5)));
}

#[test]
fn a_capture_leaves_a_forced_eye_to_snap_to() {
    let game = corner_capture();

    // The captured stone's own position is playable again, and a probe from
    // outside the corner now lands on it — or, as here, on the crossing a
    // rounding away from it, which is the same corner of the same region.
    let snapped = game.nearest_living_move(p(0.5, 0.5)).unwrap();
    assert!(snapped.distance(p(1.0, 1.0)) < 1e-9, "{snapped:?}");
    assert!(game.alive_zone().has_forced_eye(p(1.0, 1.0)));
    assert_eq!(game.validate(), Ok(()));
}

// ── Playing headlessly ───────────────────────────────────────────────────────

/// Black in the corner, taken by two white stones. Four committed turns, one of
/// them a pass, and Black to answer.
fn corner_capture() -> Game {
    let mut game = Game::new(BOARD);
    play(&mut game, 1.0, 1.0);
    play(&mut game, 3.0, 1.0);
    game.pass().unwrap();
    play(&mut game, 1.0, 3.0);
    game
}

#[test]
fn turns_captures_and_territory_all_follow_from_the_deltas() {
    let game = corner_capture();

    assert_eq!(game.turn(), 4);
    assert_eq!(game.pending_color(), Color::Black);
    assert_eq!(game.captures()[Color::White], 1);
    assert_eq!(game.captures()[Color::Black], 0);
    assert_eq!(game.status(), GameStatus::Playing);
    assert_eq!(game.deltas().count(), 4);
    assert_eq!(game.stone_count(), 2);

    // Two white stones and nothing of Black's, so White owns the board.
    let territory = game.territory();
    assert!(close(territory[Color::Black], 0.0));
    assert!(close(territory[Color::White], BOARD * BOARD));
    assert_eq!(game.validate(), Ok(()));
}

#[test]
fn the_revision_moves_on_every_change_including_a_transient_one() {
    let mut game = Game::new(BOARD);
    let start = game.revision();

    let stone = Stone::new(StoneId::new(0), Color::Black, p(5.0, 5.0));
    game.apply_delta(GameDelta::placement(stone), Commit::Transient)
        .unwrap();
    assert_eq!(game.revision(), start + 1);
    assert_eq!(game.turn(), 0, "a transient change commits no turn");
    assert_eq!(game.stone_count(), 1, "but it does change the board");

    game.pop_delta();
    assert_eq!(game.revision(), start + 2, "and so does taking it back");
    assert_eq!(game.stone_count(), 0);
}

#[test]
fn reading_the_diagram_twice_builds_it_once() {
    let mut game = Game::new(BOARD);
    play(&mut game, 5.0, 5.0);

    let first: *const _ = game.voronoi();
    let second: *const _ = game.voronoi();
    assert!(std::ptr::eq(first, second), "the memo is kept");
    assert_eq!(
        game.revision(),
        3,
        "reading it is not a change; the three are the move's own probe, its \
         rollback, and the move itself"
    );

    play(&mut game, 12.0, 12.0);
    assert_eq!(game.groups().count(), 2, "the change dropped the memo");
}

#[test]
fn a_pass_arms_the_next_one_and_an_undo_disarms_it_again() {
    let mut game = Game::new(BOARD);
    assert_eq!(game.status(), GameStatus::Playing);

    game.pass().unwrap();
    assert_eq!(game.status(), GameStatus::NextPassEnds);

    play(&mut game, 5.0, 5.0);
    assert_eq!(game.status(), GameStatus::Playing, "a move disarms it");

    // The status belongs to the last committed turns, so undoing the stone has
    // to find the pass behind it again.
    game.undo_move();
    assert_eq!(game.status(), GameStatus::NextPassEnds);
    assert_eq!(game.validate(), Ok(()));

    game.undo_move();
    assert_eq!(
        game.status(),
        GameStatus::Playing,
        "with no turns played, nothing is armed"
    );
}

#[test]
fn two_passes_in_a_row_end_the_game_and_it_then_takes_no_turns() {
    let mut game = Game::new(BOARD);
    play(&mut game, 5.0, 5.0);
    game.pass().unwrap();
    game.pass().unwrap();
    assert_eq!(game.status(), GameStatus::Ended);

    let before = Snapshot::of(&game);
    let revision = game.revision();

    assert_eq!(
        game.pass(),
        Err(GameOverError),
        "a third pass is not a turn"
    );
    let snapped = game.nearest_living_move(p(9.0, 9.0)).unwrap();
    assert_eq!(
        game.try_move(snapped),
        Err(StonePlayError::GameOver(GameOverError))
    );

    // Not only the two a player makes: a delta from anywhere is refused too,
    // committed or transient, so no route around the ending is left open.
    let stone = Stone::new(game.next_stone_id(), Color::Black, snapped);
    for commit in [Commit::Turn, Commit::Transient] {
        assert_eq!(
            game.apply_delta(GameDelta::placement(stone), commit),
            Err(DeltaError::GameOver(GameOverError))
        );
    }

    assert_eq!(Snapshot::of(&game), before, "and nothing moved");
    assert_eq!(game.revision(), revision);
    assert_eq!(game.validate(), Ok(()));
}

#[test]
fn an_ended_game_still_answers_everything_it_answered_before() {
    let mut game = corner_capture();
    game.pass().unwrap();
    game.pass().unwrap();
    assert_eq!(game.status(), GameStatus::Ended);

    // Every query still works — scoring an ended game is the whole reason a
    // caller ends one, and analysing it afterwards is the other.
    let territory = game.territory();
    assert!(close(territory[Color::White], BOARD * BOARD));
    assert_eq!(game.stone_count(), 2);
    assert_eq!(game.groups().count(), 1);
    assert_eq!(game.captures()[Color::White], 1);
    assert!(game.nearest_living_move(p(9.0, 9.0)).is_some());
    assert_eq!(game.dead_stones(Color::White).len(), 0);

    let stones: Vec<_> = game.stones().collect();
    assert!(
        game.pair_cuttable(stones[0].id, stones[1].id).is_ok(),
        "a cut question carves a dead zone and takes it back, which an ended \
         game still allows"
    );
    assert_eq!(game.validate(), Ok(()));
}

#[test]
fn undoing_the_second_pass_un_ends_the_game() {
    let mut game = Game::new(BOARD);
    game.pass().unwrap();
    game.pass().unwrap();

    assert!(
        game.undo_move().is_some(),
        "undo is allowed on an ended game"
    );
    assert_eq!(game.status(), GameStatus::NextPassEnds);

    // And the game takes turns again, by either route.
    play(&mut game, 5.0, 5.0);
    assert_eq!(game.status(), GameStatus::Playing);
    assert_eq!(game.turn(), 2);
    assert_eq!(game.validate(), Ok(()));
}

#[test]
fn a_replayed_log_that_carries_on_past_two_passes_is_refused() {
    let stone = Stone::new(StoneId::new(2), Color::Black, p(5.0, 5.0));
    let log = [
        GameDelta::pass(),
        GameDelta::pass(),
        GameDelta::placement(stone),
    ];

    assert_eq!(
        Game::replay(BOARD, log).err(),
        Some(DeltaError::GameOver(GameOverError)),
        "a log of turns played after the game ended is not a game"
    );

    // The two passes on their own are a whole game, and replay it.
    let game = Game::replay(BOARD, [GameDelta::pass(), GameDelta::pass()]).unwrap();
    assert_eq!(game.status(), GameStatus::Ended);
    assert_eq!(game.turn(), 2);
}

#[test]
fn the_delta_log_holds_the_committed_turns_and_nothing_else() {
    let mut game = Game::new(BOARD);
    play(&mut game, 5.0, 5.0);
    game.pass().unwrap();

    let probe = Stone::new(game.next_stone_id(), Color::White, p(9.0, 9.0));
    game.apply_delta(GameDelta::placement(probe), Commit::Transient)
        .unwrap();

    assert_eq!(
        game.deltas().count(),
        2,
        "the transient placement is not a turn"
    );
    assert_eq!(
        game.last_placed_stone(),
        None,
        "the last committed turn was a pass"
    );

    game.pop_delta();
    game.undo_move();
    assert_eq!(
        game.last_placed_stone().map(|stone| stone.position),
        Some(p(5.0, 5.0))
    );
}

#[test]
fn there_is_nothing_to_undo_on_an_empty_board() {
    let mut game = Game::new(BOARD);
    assert_eq!(game.undo_move(), None);
    assert_eq!(game.turn(), 0);
}

// ── Forced eyes ──────────────────────────────────────────────────────────────

/// A black stone in the middle of the board, taken by four white stones just
/// outside its dead zone.
fn surrounded_middle() -> Game {
    let mut game = Game::new(BOARD);
    play(&mut game, 10.0, 10.0);
    play(&mut game, 7.9, 10.0);
    game.pass().unwrap();
    play(&mut game, 12.1, 10.0);
    game.pass().unwrap();
    play(&mut game, 10.0, 7.9);
    game.pass().unwrap();
    play(&mut game, 10.0, 12.1);
    game
}

#[test]
fn a_stone_placed_near_a_forced_eye_consumes_it() {
    let mut game = surrounded_middle();
    assert_eq!(game.stone_count(), 4, "only the four white stones are left");
    assert!(game.alive_zone().has_forced_eye(p(10.0, 10.0)));

    game.pass().unwrap();
    play(&mut game, 10.5, 10.5);

    assert!(!game.alive_zone().has_forced_eye(p(10.0, 10.0)));
    assert_eq!(game.validate(), Ok(()));
}

#[test]
fn undoing_a_capture_takes_its_forced_eye_back_with_it() {
    let mut game = surrounded_middle();
    assert_eq!(game.alive_zone().forced_eyes().count(), 1);
    assert_eq!(game.captures()[Color::White], 1);

    game.undo_move();

    assert_eq!(
        game.stone_count(),
        4,
        "three white stones and the black one"
    );
    assert_eq!(game.alive_zone().forced_eyes().count(), 0);
    assert_eq!(game.captures()[Color::White], 0);
    assert_eq!(game.validate(), Ok(()));
}

#[test]
fn a_stone_played_exactly_on_one_forced_eye_leaves_the_others_alone() {
    // Two black stones close enough that one capture takes both, so the two
    // eyes they leave sit a stone diameter apart.
    let mut game = Game::new(BOARD);
    play(&mut game, 10.0, 10.0);
    game.pass().unwrap();
    play(&mut game, 12.0, 10.0);

    for (index, (x, y)) in [
        (8.0, 10.0),
        (10.0, 12.0),
        (10.0, 8.0),
        (12.0, 12.0),
        (12.0, 8.0),
        (14.0, 10.0),
    ]
    .into_iter()
    .enumerate()
    {
        // Black hands the turn straight back, so every one of these is White's.
        if index > 0 {
            game.pass().unwrap();
        }
        play(&mut game, x, y);
    }

    assert!(game.alive_zone().has_forced_eye(p(10.0, 10.0)));
    assert!(game.alive_zone().has_forced_eye(p(12.0, 10.0)));

    // An exact hit takes only the eye it lands on, even though the other is
    // inside the new stone's dead zone.
    let snapped = game.nearest_living_move(p(9.9, 10.0)).unwrap();
    assert_eq!(snapped, p(10.0, 10.0));
    game.try_move(snapped).unwrap();

    assert_eq!(
        game.alive_zone().forced_eyes().collect::<Vec<_>>(),
        [p(12.0, 10.0)]
    );
    assert_eq!(game.validate(), Ok(()));
}

// ── Capture ──────────────────────────────────────────────────────────────────

#[test]
fn a_surrounded_corner_stone_is_taken_and_leaves_an_eye() {
    let game = corner_capture();

    assert_eq!(game.stone_count(), 2);
    assert!(game.stones().all(|stone| stone.color == Color::White));
    assert!(game.alive_zone().has_forced_eye(p(1.0, 1.0)));
}

#[test]
fn a_surrounded_edge_stone_is_taken_too() {
    let mut game = Game::new(BOARD);
    game.pass().unwrap();
    play(&mut game, 1.0, 5.0);
    play(&mut game, 1.0, 7.0);
    game.pass().unwrap();
    play(&mut game, 1.0, 3.0);
    game.pass().unwrap();
    play(&mut game, 3.0, 5.0);

    assert_eq!(game.stone_count(), 3);
    assert!(game.stones().all(|stone| stone.color == Color::Black));
    assert!(game.alive_zone().has_forced_eye(p(1.0, 5.0)));
    assert_eq!(game.captures()[Color::Black], 1);
    assert_eq!(game.captures()[Color::White], 0);
}

#[test]
fn a_self_capture_is_refused_and_changes_nothing() {
    let mut game = corner_capture();
    let before = Snapshot::of(&game);
    let revision = game.revision();

    // Black plays straight back into the eye its captured stone left.
    let eye = game.nearest_living_move(p(1.0, 1.0)).unwrap();
    let refused = game.try_move(eye);

    assert_eq!(
        refused,
        Err(StonePlayError::SelfCapture {
            position: p(1.0, 1.0),
            color: Color::Black,
        })
    );
    // The board is bit-identical, down to the alive zone's segments: resolving
    // the move placed the stone and took it back off.
    assert_eq!(Snapshot::of(&game), before);
    assert_eq!(
        game.revision(),
        revision + 2,
        "the board did change twice, and a caller watching the revision has to see it"
    );
    assert_eq!(game.validate(), Ok(()));
}

#[test]
fn a_position_no_centre_can_reach_is_refused_without_being_played() {
    let mut game = Game::new(BOARD);
    play(&mut game, 10.0, 10.0);
    let before = Snapshot::of(&game);

    // Inside the stone's own dead zone.
    assert_eq!(
        game.try_move(p(10.5, 10.0)),
        Err(StonePlayError::NotPlaceable {
            position: p(10.5, 10.0)
        })
    );
    // Off the board, which is inset by a stone radius: a centre cannot reach
    // the literal edge.
    assert_eq!(
        game.try_move(p(0.5, 5.0)),
        Err(StonePlayError::NotPlaceable {
            position: p(0.5, 5.0)
        })
    );

    assert_eq!(Snapshot::of(&game), before);
    assert_eq!(
        game.revision(),
        3,
        "a refusal is not a board change, and the move before it was three"
    );
}

#[test]
fn every_position_the_zone_names_is_one_a_move_can_be_played_at() {
    // A snapped position lies *on* the outline, and about half of them round to
    // the covered side of it. `is_placeable` is what keeps them playable;
    // against the exact predicate this loop stops at the first crossing of two
    // shapes it snaps to, which on a board with any stones on it is most of
    // them.
    let board = 12.0;
    let mut game = Game::new(board);
    let mut played = 0;
    let mut on_a_crossing = 0;

    for step in 0..40_u32 {
        let probe = p(
            f64::from(step % 7) * board / 6.0,
            f64::from(step / 7 % 7) * board / 6.0,
        );
        let Some(snapped) = game.nearest_living_move(probe) else {
            break;
        };
        if !game.alive_zone().contains(snapped) {
            on_a_crossing += 1;
        }
        match game.try_move(snapped) {
            Ok(_) => played += 1,
            // Legal to refuse: a board this full has positions that take only
            // the mover's own stones. The turn goes to the other colour
            // instead, and two refusals in a row end the game — at which point
            // there is nothing left here to prove.
            Err(StonePlayError::SelfCapture { .. }) => {
                game.pass().expect("the game is still taking turns");
                if game.status().has_ended() {
                    break;
                }
            }
            Err(error) => panic!("snapped position {snapped:?} rejected: {error}"),
        }
    }

    assert!(played > 15, "only {played} positions were playable");
    assert!(
        on_a_crossing > 0,
        "no snapped position landed on the covered side of the outline, so this \
         proved nothing"
    );
    assert_eq!(game.validate(), Ok(()));
}

// ── A board with no room left ────────────────────────────────────────────────

/// Fills the board with black stones, snapping each to the nearest position
/// left, until there is no playable position anywhere.
///
/// The colours are set rather than alternated, because what is being built is a
/// position rather than a game.
fn pack_with_black(board: f64) -> Game {
    let mut game = Game::new(board);
    let mut probe = 0_u32;

    for _ in 0..500 {
        let candidate = p(
            f64::from(probe % 13) * board / 12.0,
            f64::from(probe / 13 % 13) * board / 12.0,
        );
        probe += 7;
        let Some(snapped) = game.nearest_living_move(candidate) else {
            return game;
        };
        let stone = Stone::new(game.next_stone_id(), Color::Black, snapped);
        game.apply_delta(GameDelta::placement(stone), Commit::Turn)
            .unwrap();
    }

    panic!("the board never filled up");
}

#[test]
fn a_packed_board_captures_every_group_on_it() {
    let mut game = pack_with_black(12.0);
    assert!(
        game.nearest_living_move(p(6.0, 6.0)).is_none(),
        "the packing left room"
    );

    // Take the last stone back, so exactly the room it took is free again.
    let last = game.undo_move().unwrap().new_stone.unwrap();
    let survivors = game.stone_count();
    assert!(survivors > 10, "only {survivors} stones fitted");

    // White plays into it. With that position filled the alive zone is empty,
    // and an empty zone is infinitely far from everything rather than zero away
    // — which is what makes every group on the board dead at once.
    if game.pending_color() != Color::White {
        game.pass().unwrap();
    }
    let white = Stone::new(game.next_stone_id(), Color::White, last.position);
    game.apply_delta(GameDelta::placement(white), Commit::Transient)
        .unwrap();

    assert!(
        game.alive_zone()
            .closest_distance(LineSegment::new(p(1.0, 1.0), p(11.0, 11.0)))
            .is_infinite()
    );
    assert_eq!(game.dead_stones(Color::Black).len(), survivors);
    assert!(
        !game.dead_stones(Color::White).is_empty(),
        "the stone that filled the board is dead too, which is what makes this \
         both a capture and a self-capture"
    );
    game.pop_delta();

    // Played for real the enemy is asked first, so the move is legal and takes
    // the lot.
    let delta = game.try_move(last.position).expect("a legal move");
    assert_eq!(delta.captured_stone_ids.len(), survivors);
    assert_eq!(game.captures()[Color::White], survivors as u32);
    assert_eq!(game.stone_count(), 1);
    assert_eq!(game.dead_stones(Color::Black).len(), 0);
    assert_eq!(game.validate(), Ok(()));
}

// ── Undo is bit-exact ────────────────────────────────────────────────────────

#[test]
fn undoing_a_capture_restores_the_board_bit_for_bit() {
    let mut game = Game::new(BOARD);
    play(&mut game, 1.0, 1.0);
    play(&mut game, 3.0, 1.0);
    game.pass().unwrap();

    let before = Snapshot::of(&game);

    // The capture carves a dead zone, adds a forced eye, and gives another
    // stone's dead zone back; undoing it has to reverse all three.
    let delta = play(&mut game, 1.0, 3.0);
    assert_eq!(delta.captured_stone_ids, [StoneId::new(0)]);
    assert_ne!(Snapshot::of(&game), before);

    game.undo_move();

    assert_eq!(
        Snapshot::of(&game),
        before,
        "the alive zone's own segments have to come back identical, not merely equivalent"
    );
    assert_eq!(game.validate(), Ok(()));
}

#[test]
fn undoing_a_plain_move_restores_the_board_bit_for_bit() {
    let mut game = Game::new(BOARD);
    for (x, y) in [(6.0, 6.0), (8.5, 7.0), (7.0, 9.0), (4.0, 8.0)] {
        play(&mut game, x, y);
    }
    let before = Snapshot::of(&game);

    play(&mut game, 8.0, 10.5);
    game.undo_move();

    assert_eq!(Snapshot::of(&game), before);
}

#[test]
fn a_transient_placement_leaves_nothing_behind() {
    let mut game = Game::new(BOARD);
    play(&mut game, 6.0, 6.0);
    play(&mut game, 8.5, 7.0);
    let before = Snapshot::of(&game);

    let probe = Stone::new(game.next_stone_id(), game.pending_color(), p(7.5, 9.0));
    game.apply_delta(GameDelta::placement(probe), Commit::Transient)
        .unwrap();
    game.pop_delta();

    assert_eq!(Snapshot::of(&game), before);
    assert_eq!(game.turn(), 2, "no turn was ever committed");
}

// ── Deltas the board cannot account for ──────────────────────────────────────

#[test]
fn a_delta_that_captures_a_stone_that_is_not_there_is_refused() {
    let mut game = Game::new(BOARD);
    play(&mut game, 5.0, 5.0);
    let before = Snapshot::of(&game);

    let stone = Stone::new(game.next_stone_id(), Color::White, p(9.0, 9.0));
    let ghost = StoneId::new(41);
    assert_eq!(
        game.apply_delta(GameDelta::capture(stone, vec![ghost]), Commit::Turn),
        Err(DeltaError::NoSuchStone { stone: ghost })
    );

    assert_eq!(
        Snapshot::of(&game),
        before,
        "a refused delta changes nothing"
    );
    assert_eq!(game.revision(), 3);
}

#[test]
fn a_delta_that_reuses_a_stone_id_is_refused() {
    let mut game = Game::new(BOARD);
    play(&mut game, 5.0, 5.0);

    let clash = Stone::new(StoneId::new(0), Color::White, p(9.0, 9.0));
    assert_eq!(
        game.apply_delta(GameDelta::placement(clash), Commit::Turn),
        Err(DeltaError::StoneExists {
            stone: StoneId::new(0)
        })
    );
}

#[test]
fn a_delta_that_captures_the_same_stone_twice_is_refused() {
    let mut game = Game::new(BOARD);
    play(&mut game, 5.0, 5.0);

    let stone = Stone::new(game.next_stone_id(), Color::White, p(9.0, 9.0));
    let victim = StoneId::new(0);
    assert_eq!(
        game.apply_delta(
            GameDelta::capture(stone, vec![victim, victim]),
            Commit::Turn
        ),
        Err(DeltaError::CapturedTwice { stone: victim })
    );
}

#[test]
fn a_pass_that_captures_is_refused() {
    let mut game = Game::new(BOARD);
    play(&mut game, 5.0, 5.0);

    let delta = GameDelta {
        new_stone: None,
        captured_stone_ids: vec![StoneId::new(0)],
    };
    assert_eq!(
        game.apply_delta(delta, Commit::Turn),
        Err(DeltaError::PassCaptures)
    );
}

#[test]
fn a_delta_placing_a_stone_off_the_board_is_refused() {
    let mut game = Game::new(BOARD);
    play(&mut game, 5.0, 5.0);
    let before = Snapshot::of(&game);

    // A delta is not re-judged for placeability — it carries its own record of a
    // legal turn — so these are refused for being nowhere, not for being taken.
    for position in [
        p(BOARD + 1.0, 5.0),
        p(-1.0, 5.0),
        p(1e300, 1e300),
        p(f64::NAN, 5.0),
        p(5.0, f64::INFINITY),
    ] {
        let stone = Stone::new(game.next_stone_id(), Color::White, position);
        assert_eq!(
            game.apply_delta(GameDelta::placement(stone), Commit::Turn),
            Err(DeltaError::OffBoard {
                stone: game.next_stone_id(),
                position,
            }),
            "{position:?}"
        );
    }

    assert_eq!(
        Snapshot::of(&game),
        before,
        "a refused delta changes nothing"
    );
    assert_eq!(game.revision(), 3);
}

#[test]
fn the_board_rectangle_is_the_whole_domain_a_delta_may_use() {
    // The corners are on the board and nowhere near placeable — the alive zone
    // is inset by a stone radius — which is exactly the difference between the
    // two questions. A replayed delta is judged by the weaker one.
    let mut game = Game::new(BOARD);
    let corner = Stone::new(StoneId::new(0), Color::Black, p(0.0, 0.0));

    assert!(!game.alive_zone().is_placeable(p(0.0, 0.0)));
    assert_eq!(
        game.apply_delta(GameDelta::placement(corner), Commit::Turn),
        Ok(())
    );
    assert_eq!(game.validate(), Ok(()));
}

// ── A position is a point on the board ───────────────────────────────────────

#[test]
fn a_coordinate_that_is_not_a_number_is_not_placeable() {
    // Every depth is a subtraction, so a `NaN` makes all of them `NaN`, and
    // `f64::max` discards a `NaN` operand: without the domain check the fold
    // answers `NEG_INFINITY` and the position reads as the clearest on the
    // board. See `docs/design.md` § "A position is a point on the board".
    let mut game = Game::new(BOARD);
    play(&mut game, 10.0, 10.0);
    let before = Snapshot::of(&game);

    for position in [
        p(f64::NAN, 5.0),
        p(5.0, f64::NAN),
        p(f64::NAN, f64::NAN),
        p(f64::INFINITY, 5.0),
        p(5.0, f64::NEG_INFINITY),
        p(1e300, 1e300),
    ] {
        assert!(!game.alive_zone().contains(position), "{position:?}");
        assert!(!game.alive_zone().is_placeable(position), "{position:?}");
        assert_eq!(
            game.try_move(position),
            Err(StonePlayError::NotPlaceable { position }),
            "{position:?}"
        );
    }

    assert_eq!(Snapshot::of(&game), before);
    assert_eq!(game.validate(), Ok(()));
}

#[test]
fn a_probe_that_is_not_a_number_snaps_to_nothing() {
    let mut game = Game::new(BOARD);
    play(&mut game, 10.0, 10.0);

    assert_eq!(game.nearest_living_move(p(f64::NAN, 5.0)), None);
    assert_eq!(game.nearest_living_move(p(5.0, f64::NAN)), None);
    assert_eq!(game.nearest_living_move(p(f64::INFINITY, 5.0)), None);

    // A finite probe off the board still snaps inwards: it is a direction to
    // look from, not a position, and that is the whole point of the method.
    let snapped = game.nearest_living_move(p(-50.0, -50.0));
    assert_eq!(snapped, Some(p(1.0, 1.0)));
}

#[test]
fn a_board_that_is_not_a_number_holds_no_positions() {
    let mut game = Game::new(f64::NAN);

    assert!(!game.alive_zone().is_placeable(p(1.0, 1.0)));
    assert_eq!(game.nearest_living_move(p(1.0, 1.0)), None);
    assert_eq!(
        game.try_move(p(1.0, 1.0)),
        Err(StonePlayError::NotPlaceable {
            position: p(1.0, 1.0)
        })
    );
}

// ── The transient placement must unwind ──────────────────────────────────────

#[test]
fn a_panic_while_a_transient_stone_is_down_leaves_the_board_as_it_was() {
    // The property `Game::try_move` depends on and cannot state for itself: the
    // stone goes down before anything can be asked about it, so every way out of
    // the asking has to take it back. Without the guard the placement survives
    // the unwind — history keeps an uncommitted delta, the alive zone keeps a
    // dead zone for a stone nobody played, and the next move collides with its
    // id. See `docs/design.md` § "The transient placement must unwind".
    let mut game = Game::new(BOARD);
    play(&mut game, 5.0, 5.0);
    play(&mut game, 9.0, 9.0);

    let before = Snapshot::of(&game);
    let revision = game.revision();
    let stone = Stone::new(game.next_stone_id(), game.pending_color(), p(13.0, 13.0));

    let escaped = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        game.with_transient_stone(stone, |_| panic!("the question blew up"))
    }));
    assert!(escaped.is_err(), "the panic reached the caller");

    assert_eq!(
        Snapshot::of(&game),
        before,
        "the transient placement was taken back, down to the zone's segments"
    );
    assert_eq!(game.validate(), Ok(()));
    assert_eq!(
        game.revision(),
        revision + 2,
        "the revision only ever increases: one for the placement, one for the \
         rollback"
    );

    // And the board is still fit to play on, which is the point of all of it.
    assert!(game.try_move(p(13.0, 13.0)).is_ok());
    assert_eq!(game.validate(), Ok(()));
}

#[test]
fn a_transient_question_is_answered_with_the_stone_on_the_board() {
    let mut game = Game::new(BOARD);
    let stone = Stone::new(game.next_stone_id(), Color::Black, p(5.0, 5.0));
    let before = Snapshot::of(&game);

    let seen = game
        .with_transient_stone(stone, |game| (game.stone_count(), game.turn()))
        .unwrap();

    assert_eq!(seen, (1, 0), "on the board, but no turn committed");
    assert_eq!(Snapshot::of(&game), before, "and taken straight back off");
}

// ── Connectivity ─────────────────────────────────────────────────────────────

#[test]
fn a_board_answers_whether_its_own_stones_can_be_cut() {
    let mut game = Game::new(BOARD);
    // Black, white, black: the two blacks end up a tight pair and the white is
    // out of the way.
    game.try_move(p(10.0, 10.0)).expect("a legal move");
    game.try_move(p(16.0, 16.0)).expect("a legal move");
    game.try_move(p(10.0, 12.5)).expect("a legal move");

    let (black, other_black, white) = (StoneId::new(0), StoneId::new(2), StoneId::new(1));
    let missing = StoneId::new(9);

    assert_eq!(
        game.pair_cuttable(black, other_black),
        Ok(CutKind::Connected),
        "a tight pair"
    );
    assert_eq!(
        game.pair_cuttable(black, white),
        Err(CutError::DifferentColors { a: black, b: white })
    );
    assert_eq!(
        game.pair_cuttable(black, black),
        Err(CutError::SameStone { stone: black })
    );
    assert_eq!(
        game.pair_cuttable(black, missing),
        Err(CutError::NoSuchStone { stone: missing })
    );
    assert_eq!(
        game.boundary_cuttable(black, BoardEdge::Left),
        Ok(CutKind::TooFar),
        "ten units from the wall is nothing the rules will judge"
    );
    assert_eq!(
        game.boundary_cuttable(missing, BoardEdge::Left),
        Err(CutError::NoSuchStone { stone: missing })
    );
}

#[test]
fn asking_whether_a_pair_can_be_cut_does_not_change_the_board() {
    // It carves temporary circles into the alive zone to answer, and every one
    // of them has to come back — to the bit.
    let mut game = corner_capture();
    let before = Snapshot::of(&game);
    let revision = game.revision();

    for edge in BoardEdge::ALL {
        let _ = game.boundary_cuttable(StoneId::new(0), edge);
    }
    let _ = game.pair_cuttable(StoneId::new(0), StoneId::new(1));

    assert_eq!(Snapshot::of(&game), before);
    assert_eq!(game.revision(), revision, "asking is not a change");
    assert_eq!(game.validate(), Ok(()));
}

/// Every cut answer a board has, in a fixed order: each pair of stones by
/// ascending id, then each stone against each edge.
///
/// A malformed question — two colours, a stone with itself — has no answer and
/// is left out rather than recorded as one.
fn answers(game: &mut Game) -> Vec<CutKind> {
    let ids: Vec<StoneId> = game.stones().map(|stone| stone.id).collect();
    let mut all = Vec::new();
    for (index, a) in ids.iter().enumerate() {
        for b in ids.iter().skip(index + 1) {
            all.extend(game.pair_cuttable(*a, *b));
        }
    }
    for id in &ids {
        for edge in BoardEdge::ALL {
            all.extend(game.boundary_cuttable(*id, edge));
        }
    }
    all
}

/// The same answers according to a cache that holds nothing — which is what the
/// board's own, cached, answers have to agree with after every change.
fn uncached_answers(game: &Game) -> Vec<CutKind> {
    let stones: Vec<Stone> = game.stones().collect();
    let mut zone = game.alive_zone().clone();
    let mut connectivity = Connectivity::new(game.board_size());
    let mut all = Vec::new();
    for (index, a) in stones.iter().enumerate() {
        for b in stones.iter().skip(index + 1) {
            all.extend(connectivity.pair_cuttable(&mut zone, &stones, *a, *b));
        }
    }
    for stone in &stones {
        for edge in BoardEdge::ALL {
            all.push(connectivity.boundary_cuttable(&mut zone, &stones, *stone, edge));
        }
    }
    all
}

/// How many of a board's answers are proven connections.
fn connections(game: &mut Game) -> usize {
    answers(game)
        .iter()
        .filter(|kind| **kind == CutKind::Connected)
        .count()
}

#[test]
fn no_cut_status_outlives_the_position_it_was_computed_for() {
    // This is what the invalidation hook is for, stated as the property rather
    // than as a hand-built flip: a cached answer must never differ from the one
    // a cache holding nothing would give. Checked after every move on the way up
    // and after every undo on the way back down, because the hook has to fire
    // from `pop_delta` as well as `apply_delta`.
    //
    // The positions are chosen so that a third stone really does change a pair's
    // status — white passes throughout, so these are all one colour and the
    // cluster genuinely tightens. The first two are three apart, which is
    // cuttable in the open; the third, off to one side, takes the cutting room
    // away and the pair becomes a connection. Undoing walks that back, and it
    // cannot come out right from a status computed before it.
    let positions = [
        (10.0, 10.0),
        (13.0, 10.0),
        (11.5, 8.0),
        (11.5, 12.0),
        (11.5, 14.5),
        (11.5, 5.5),
    ];

    let mut game = Game::new(BOARD);
    let mut counts = Vec::new();
    for (x, y) in positions {
        play(&mut game, x, y);
        game.pass().unwrap();
        assert_eq!(
            answers(&mut game),
            uncached_answers(&game),
            "after playing near ({x}, {y})"
        );
        counts.push(connections(&mut game));
    }

    let mut down = Vec::new();
    while game.undo_move().is_some() {
        let turn = game.turn();
        assert_eq!(
            answers(&mut game),
            uncached_answers(&game),
            "after undoing back to turn {turn}"
        );
        down.push(connections(&mut game));
    }

    // The sequence has to have moved for any of the above to mean anything, and
    // the way back down has to retrace the way up rather than merely end where
    // it started.
    assert_eq!(counts, vec![0, 0, 3, 5, 6, 7]);
    // Two entries per step: the pass, then the stone.
    assert_eq!(down, vec![7, 6, 6, 5, 5, 3, 3, 0, 0, 0, 0, 0]);
}

#[test]
fn a_transient_change_invalidates_around_itself_too() {
    // Not gated on `Commit`: a preview applies and pops a delta every frame, so
    // it has to invalidate on the way in as well as on the way out, and a status
    // computed while that stone was on the board must not outlive it.
    //
    // The same three stones as above, whose fourth tightens the cluster further
    // — except that this time the fourth is transient.
    let mut game = Game::new(BOARD);
    for (x, y) in [(10.0, 10.0), (13.0, 10.0), (11.5, 8.0)] {
        play(&mut game, x, y);
        game.pass().unwrap();
    }
    // Cached with the first pair already held together by the third stone.
    let settled = answers(&mut game);
    assert_eq!(connections(&mut game), 3);

    let preview = Stone::new(game.next_stone_id(), game.pending_color(), p(11.5, 12.0));
    game.apply_delta(GameDelta::placement(preview), Commit::Transient)
        .expect("a transient placement");
    assert_eq!(answers(&mut game), uncached_answers(&game));
    assert_eq!(
        connections(&mut game),
        5,
        "the transient stone made two more connections"
    );

    game.pop_delta().expect("something to pop");
    assert_eq!(
        answers(&mut game),
        settled,
        "the pop dropped every status the transient stone produced"
    );
}

// ── Replay ───────────────────────────────────────────────────────────────────

#[test]
fn a_game_rebuilt_from_its_deltas_is_the_same_game() {
    let mut played = corner_capture();
    play(&mut played, 15.0, 15.0);

    let replayed = Game::replay(BOARD, played.deltas().cloned()).expect("the log replays");

    assert_eq!(Snapshot::of(&replayed), Snapshot::of(&played));
    assert_eq!(replayed.revision(), 5, "one change per delta, and no more");
    assert_eq!(replayed.validate(), Ok(()));
}