pinch-points 0.8.0

A fast, kid-friendly crab-routing game: route streams of crabs into your sandcastle before time runs out
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
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
//! The board's unit tests, spec section by spec section.

use super::*;
use crate::sim::direction::Direction::*;

fn common(board: &mut Board, x: u8, y: u8, dir: Direction, handed: Handedness) {
    board.spawn_crab(x, y, dir, handed, CrabKind::Common);
}

/// Ticks needed for a crab of `speed` to travel `tiles` tile-lengths.
fn ticks_to_cross(tiles: u32, speed: u32) -> u32 {
    (tiles * u32::from(SUBUNITS_PER_TILE)).div_ceil(speed)
}

/// A board with something on every field worth copying: creatures, a
/// castle to bank into, signposts, a spun clock, walls off the border.
fn lively(seed: u64, size: u8) -> Board {
    let mut board = Board::new(size, size, seed);
    board.set_events_enabled(true);
    board.set_tile(size - 1, 0, TileKind::Castle(0));
    board.set_wall(1, 1, Right, true);
    common(&mut board, 0, 0, Right, Handedness::Left);
    common(&mut board, 0, size - 1, Up, Handedness::Right);
    board.spawn_gull(size - 1, size - 1, Left);
    board.place_signpost(0, 1, 0, Down);
    for _ in 0..20 {
        board.tick_idle();
    }
    board
}

/// `copy_from` is `clone` with the allocations left out, and the whole
/// search rests on it being nothing else: a field it forgets to carry is a
/// copy that plays a different game from the board it was copied from.
/// Compared by `Debug`, which prints every field, rather than by
/// `state_hash`, which deliberately leaves some out.
#[test]
fn copy_from_lands_exactly_where_clone_does() {
    let source = lively(7, 6);
    // Onto a board of another size, with longer buffers to cut back and a
    // history of its own: the scratch board a search reuses is never blank.
    let mut copy = lively(99, 9);
    copy.copy_from(&source);
    assert_eq!(format!("{copy:?}"), format!("{source:?}"));
    assert_eq!(copy.state_hash(), source.state_hash());
    // And it keeps playing the same game, not merely starting from it.
    let mut clone = source.clone();
    for _ in 0..40 {
        copy.tick_idle();
        clone.tick_idle();
    }
    assert_eq!(format!("{copy:?}"), format!("{clone:?}"));
}

#[test]
fn crab_crosses_a_tile_at_spec_speed() {
    let mut board = Board::new(5, 1, 0);
    common(&mut board, 0, 0, Right, Handedness::Left);
    // 256 subunits at 12/tick: still on tile 0 after 21 ticks (252).
    for _ in 0..21 {
        board.tick_idle();
    }
    assert_eq!(board.crabs()[0].tile, 0);
    assert_eq!(board.crabs()[0].progress, 252);
    // Tick 22 crosses: snap to tile 1, carry remainder 264 - 256 = 8.
    board.tick_idle();
    assert_eq!(board.crabs()[0].tile, 1);
    assert_eq!(board.crabs()[0].progress, 8);
}

#[test]
fn prev_fields_track_last_tick() {
    let mut board = Board::new(5, 1, 0);
    common(&mut board, 0, 0, Right, Handedness::Left);
    board.tick_idle();
    let crab = board.crabs()[0];
    assert_eq!(crab.prev.progress, 0);
    assert_eq!(crab.progress, 12);
    board.tick_idle();
    assert_eq!(board.crabs()[0].prev.progress, 12);
}

#[test]
fn handedness_splits_at_a_wall() {
    // Two crabs walk up the same corridor into the top border; the
    // left-clawed one turns left, the right-clawed one turns right.
    for (handed, expected) in [(Handedness::Left, Left), (Handedness::Right, Right)] {
        let mut board = Board::new(3, 3, 0);
        common(&mut board, 1, 1, Up, handed);
        for _ in 0..ticks_to_cross(1, 12) {
            board.tick_idle();
        }
        let crab = board.crabs()[0];
        assert_eq!((crab.tile, crab.dir), (1, expected), "{handed:?}");
    }
}

#[test]
fn blocked_preferred_side_takes_other_side() {
    // Left-clawed crab arrives at the top-left corner moving up: forward
    // and left are border walls, so it takes its off-side, right.
    let mut board = Board::new(3, 3, 0);
    common(&mut board, 0, 1, Up, Handedness::Left);
    for _ in 0..ticks_to_cross(1, 12) {
        board.tick_idle();
    }
    assert_eq!(board.crabs()[0].dir, Right);
}

#[test]
fn dead_end_reverses() {
    let mut board = Board::new(1, 3, 0);
    common(&mut board, 0, 1, Down, Handedness::Left);
    for _ in 0..ticks_to_cross(1, 12) {
        board.tick_idle();
    }
    let crab = board.crabs()[0];
    assert_eq!((crab.tile, crab.dir), (u16::from(board.width()) * 2, Up));
}

#[test]
fn fully_enclosed_crab_waits_without_panicking() {
    let mut board = Board::new(1, 1, 0);
    common(&mut board, 0, 0, Right, Handedness::Left);
    for _ in 0..100 {
        board.tick_idle();
    }
    assert_eq!(board.crabs()[0].tile, 0);
    assert_eq!(board.crabs()[0].progress, 0);
}

#[test]
fn rocks_are_impassable() {
    // Corridor with a rock in the middle: the crab treats it like a wall
    // and reverses (1×3 board leaves no side exits).
    let mut board = Board::new(3, 1, 0);
    board.set_tile(1, 0, TileKind::Rock);
    common(&mut board, 0, 0, Right, Handedness::Left);
    board.tick_idle();
    // spawn_crab wall-resolved immediately: right is blocked by the rock,
    // both sides are borders, so the crab reversed to Left on spawn.
    assert_eq!(board.crabs()[0].dir, Left);
}

#[test]
fn signpost_redirects_crabs() {
    let mut board = Board::new(5, 5, 0);
    assert!(board.place_signpost(0, 2, 2, Up));
    common(&mut board, 0, 2, Right, Handedness::Left);
    for _ in 0..ticks_to_cross(2, 12) {
        board.tick_idle();
    }
    let crab = board.crabs()[0];
    assert_eq!(crab.dir, Up);
    // One more tile-crossing later it has moved up to (2, 1).
    for _ in 0..ticks_to_cross(1, 12) {
        board.tick_idle();
    }
    assert_eq!(board.crabs()[0].tile, u16::from(board.width()) + 2);
}

#[test]
fn signpost_into_wall_is_followed_then_resolved() {
    // Frozen §9#2 behaviour: the signpost turns the crab into the wall,
    // then normal wall resolution applies from the signpost's direction.
    for (handed, expected) in [(Handedness::Left, Left), (Handedness::Right, Right)] {
        let mut board = Board::new(5, 5, 0);
        assert!(board.place_signpost(0, 2, 0, Up)); // top row, points at border
        common(&mut board, 0, 0, Right, handed);
        for _ in 0..ticks_to_cross(2, 12) {
            board.tick_idle();
        }
        let crab = board.crabs()[0];
        assert_eq!((crab.tile, crab.dir), (2, expected), "{handed:?}");
    }
}

#[test]
fn banking_awards_value_and_despawns() {
    let mut board = Board::new(5, 1, 0);
    board.set_tile(4, 0, TileKind::Castle(2));
    common(&mut board, 0, 0, Right, Handedness::Left);
    board.spawn_crab(1, 0, Right, Handedness::Right, CrabKind::Giant);
    // Giant (speed 7) needs 3 tiles: ceil(768 / 7) = 110 ticks, the
    // slowest arrival. Common banks earlier.
    for _ in 0..ticks_to_cross(3, 7) {
        board.tick_idle();
    }
    assert!(board.crabs().is_empty());
    assert_eq!(board.scores()[2], 1 + 10);
    assert_eq!(board.scores()[0], 0);
}

#[test]
fn juvenile_is_faster() {
    let mut board = Board::new(5, 1, 0);
    board.spawn_crab(0, 0, Right, Handedness::Left, CrabKind::Juvenile);
    common(&mut board, 0, 0, Right, Handedness::Left);
    for _ in 0..ticks_to_cross(1, 18) {
        board.tick_idle();
    }
    assert_eq!(board.crabs()[0].tile, 1); // juvenile crossed
    assert_eq!(board.crabs()[1].tile, 0); // common has not
}

#[test]
fn signpost_cap_evicts_oldest() {
    let mut board = Board::new(6, 1, 0);
    for x in 0..4 {
        assert!(board.place_signpost(0, x, 0, Up));
    }
    assert!(board.signpost_at(0, 0).is_none(), "oldest evicted");
    for x in 1..4 {
        assert!(board.signpost_at(x, 0).is_some());
    }
}

#[test]
fn repointing_refreshes_health_and_age() {
    let mut board = Board::new(8, 1, 0);
    for x in 0..3 {
        assert!(board.place_signpost(0, x, 0, Up));
    }
    // Re-point the oldest post: it becomes the newest...
    assert!(board.place_signpost(0, 0, 0, Down));
    assert_eq!(board.signpost_count(0), 3);
    // ...so the next placement over the cap evicts (1,0), not (0,0).
    assert!(board.place_signpost(0, 4, 0, Up));
    assert!(board.signpost_at(0, 0).is_some());
    assert!(board.signpost_at(1, 0).is_none());
}

/// The post the UI marks as next to go is the one the next placement
/// actually takes, re-pointing included, and nothing is marked with room
/// to spare or under puzzle rules.
#[test]
fn the_next_to_go_is_the_one_the_cap_takes() {
    let mut board = Board::new(8, 1, 0);
    board.set_signpost_rule(3, CapPolicy::Evict);
    for x in 0..2 {
        assert!(board.place_signpost(0, x, 0, Up));
    }
    assert_eq!(board.next_to_go(0), None, "room for one more");
    assert!(board.place_signpost(0, 2, 0, Up));
    assert_eq!(board.next_to_go(0), Some((0, 0)), "at the cap: the oldest");
    assert_eq!(board.next_to_go(1), None, "a rival's count is its own");
    // Re-pointing the marked post makes it the newest: the mark moves on.
    assert!(board.place_signpost(0, 0, 0, Down));
    assert_eq!(board.next_to_go(0), Some((1, 0)));
    // And the mark is a promise: the next placement takes that post.
    let marked = board.next_to_go(0).expect("at the cap");
    assert!(board.place_signpost(0, 4, 0, Up));
    assert!(board.signpost_at(marked.0, marked.1).is_none());

    let mut puzzle = Board::new(8, 1, 0);
    puzzle.set_signpost_rule(1, CapPolicy::Reject);
    assert!(puzzle.place_signpost(0, 0, 0, Up));
    assert_eq!(puzzle.next_to_go(0), None, "a full inventory refuses");
}

/// Lives come back oldest first, the order the cap and the clock both
/// take them in.
#[test]
fn signpost_lives_are_oldest_first() {
    let mut board = Board::new(8, 1, 0);
    let mut lives = Vec::new();
    board.signpost_lives(0, &mut lives);
    assert!(lives.is_empty());
    // Planted right to left, so reading order is not age order.
    assert!(board.place_signpost(0, 5, 0, Up));
    for _ in 0..60 {
        board.tick_idle();
    }
    assert!(board.place_signpost(0, 1, 0, Up));
    board.signpost_lives(0, &mut lives);
    assert_eq!(lives.len(), 2);
    assert!(lives[0] < lives[1], "the older has less left: {lives:?}");
    assert!((lives[1] - 1.0).abs() < f32::EPSILON, "fresh: {lives:?}");
}

/// `out_of_signposts` agrees with the rule it explains, and never fires
/// where a fourth placement would simply take the oldest.
#[test]
fn out_of_signposts_names_the_inventory_refusal_only() {
    let mut board = Board::new(6, 2, 0);
    board.set_signpost_rule(2, CapPolicy::Reject);
    board.set_tile(5, 0, TileKind::Rock);
    assert!(!board.out_of_signposts(0, 0, 0), "nothing placed yet");
    assert!(board.place_signpost(0, 0, 0, Up));
    assert!(board.place_signpost(0, 1, 0, Up));
    // Spent: an empty tile now refuses, and that is the inventory talking.
    assert!(!board.can_place_signpost(0, 2, 0));
    assert!(board.out_of_signposts(0, 2, 0));
    // A rock refuses too, but aiming elsewhere is the answer there.
    assert!(!board.can_place_signpost(0, 5, 0));
    assert!(
        !board.out_of_signposts(0, 5, 0),
        "the tile, not the inventory"
    );
    // Re-pointing one you already own is never refused.
    assert!(!board.out_of_signposts(0, 0, 0));
    assert!(board.place_signpost(0, 0, 0, Down));
    // The other seat has its own inventory.
    assert!(!board.out_of_signposts(1, 2, 0));

    // Under the versus rule the fourth is taken in trade, so there is no
    // refusal to explain.
    let mut versus = Board::new(6, 2, 0);
    for x in 0..3 {
        assert!(versus.place_signpost(0, x, 0, Up));
    }
    assert!(versus.can_place_signpost(0, 4, 0));
    assert!(!versus.out_of_signposts(0, 4, 0), "evicting, not refusing");
}

#[test]
fn signpost_cap_is_per_player() {
    let mut board = Board::new(8, 1, 0);
    for x in 0..3 {
        assert!(board.place_signpost(0, x, 0, Up));
    }
    assert!(board.place_signpost(1, 3, 0, Up));
    // Player 1's placement must not evict player 0's oldest.
    for x in 0..4 {
        assert!(board.signpost_at(x, 0).is_some());
    }
}

#[test]
fn signpost_placement_rules() {
    let mut board = Board::new(5, 5, 0);
    board.set_tile(0, 0, TileKind::Rock);
    board.set_tile(1, 0, TileKind::Castle(0));
    board.set_tile(
        2,
        0,
        TileKind::Spawner(Spawner {
            dir: Down,
            period: 30,
        }),
    );
    assert!(!board.place_signpost(0, 0, 0, Up));
    assert!(!board.place_signpost(0, 1, 0, Up));
    assert!(!board.place_signpost(0, 2, 0, Up));
    assert!(board.place_signpost(0, 3, 0, Up));
    // A rival's signpost blocks the tile...
    assert!(!board.place_signpost(1, 3, 0, Down));
    // ...but your own is re-pointed in place, no Remove needed.
    assert!(board.place_signpost(0, 3, 0, Down));
    assert_eq!(board.signpost_at(3, 0).unwrap().dir, Down);
    assert_eq!(board.signpost_count(0), 1, "re-pointing is not a new post");
    // Out of bounds.
    assert!(!board.place_signpost(0, 200, 0, Up));
}

#[test]
fn only_the_owner_removes_a_signpost() {
    let mut board = Board::new(5, 5, 0);
    assert!(board.place_signpost(0, 2, 2, Up));
    assert!(!board.remove_signpost(1, 2, 2));
    assert!(board.signpost_at(2, 2).is_some());
    assert!(board.remove_signpost(0, 2, 2));
    assert!(board.signpost_at(2, 2).is_none());
}

/// Two seats reaching for one tile on one tick: whoever the tick's
/// [`Board::action_order`] reaches first takes it, and the other's placement
/// fails the occupied-tile check. On a board with no castles there is one
/// seat in play, so the order does not rotate and the lower seat leads.
#[test]
fn a_same_tile_conflict_goes_to_whoever_the_order_reaches_first() {
    let mut board = Board::new(5, 5, 0);
    let mut actions = [PlayerAction::None; MAX_PLAYERS];
    actions[1] = PlayerAction::Place {
        x: 2,
        y: 2,
        dir: Up,
    };
    actions[2] = PlayerAction::Place {
        x: 2,
        y: 2,
        dir: Down,
    };
    board.tick(&actions);
    let sp = board.signpost_at(2, 2).expect("someone placed");
    assert_eq!(sp.owner, 1);
    assert_eq!(sp.dir, Up);
}

/// And on a seated board the lead really does move, so no seat wins every
/// tie: the same conflict on tick 2 of a four-castle beach goes the other
/// way. This is the bias fix `action_order` exists for.
#[test]
fn the_lead_rotates_so_one_seat_does_not_win_every_tie() {
    let mut board = Board::new(5, 5, 0);
    for (seat, &(x, y)) in [(0u8, 0u8), (4, 4), (4, 0), (0, 4)].iter().enumerate() {
        board.set_tile(x, y, TileKind::Castle(seat as u8));
    }
    assert_eq!(board.seats_in_play(), 4);
    board.tick_idle();
    board.tick_idle();
    assert_eq!(board.ticks(), 2);

    let mut actions = [PlayerAction::None; MAX_PLAYERS];
    actions[1] = PlayerAction::Place {
        x: 2,
        y: 2,
        dir: Up,
    };
    actions[2] = PlayerAction::Place {
        x: 2,
        y: 2,
        dir: Down,
    };
    board.tick(&actions);
    let sp = board.signpost_at(2, 2).expect("someone placed");
    assert_eq!(sp.owner, 2, "seat 2 leads this tick, so it takes the tile");
    assert_eq!(sp.dir, Down);
}

#[test]
fn spawner_emits_on_schedule_with_seeded_handedness() {
    let mut board = Board::new(3, 3, 7);
    board.set_tile(
        1,
        1,
        TileKind::Spawner(Spawner {
            dir: Right,
            period: 10,
        }),
    );
    board.tick_idle(); // tick 0 spawns immediately
    assert_eq!(board.crabs().len(), 1);
    for _ in 0..20 {
        board.tick_idle(); // ticks 10 and 20 spawn
    }
    assert_eq!(board.crabs().len(), 3);

    // Same seed reproduces the same handedness sequence.
    let mut again = Board::new(3, 3, 7);
    again.set_tile(
        1,
        1,
        TileKind::Spawner(Spawner {
            dir: Right,
            period: 10,
        }),
    );
    for _ in 0..21 {
        again.tick_idle();
    }
    let handed: Vec<_> = board.crabs().iter().map(|c| c.handed).collect();
    let handed_again: Vec<_> = again.crabs().iter().map(|c| c.handed).collect();
    assert_eq!(handed, handed_again);
}

#[test]
fn walls_are_shared_between_neighbours() {
    let mut board = Board::new(3, 3, 0);
    board.set_wall(1, 1, Right, true);
    // The same edge seen from the other side.
    assert!(board.wall_at(2, 1, Left));
    board.set_wall(2, 1, Left, false);
    assert!(!board.wall_at(1, 1, Right));
}

/// A forced event arms the cooldown too.
///
/// The clock is set in `apply_tide_event` rather than in the roulette on
/// purpose: what holds the wheel is "an event is running", not "the wheel
/// was spun". The dev hook and the tests are the only other way an event
/// starts, and one fired that way must not leave the beach open to a
/// second on the same tick.
#[test]
fn an_event_fired_by_hand_holds_the_wheel_as_well() {
    let mut board = Board::new(9, 7, 2);
    board.set_events_enabled(true);
    board.force_tide_event(TideEvent::FreshSand, 0);
    let first = board.last_event().expect("the forced event landed");
    board.spin_tide_event(0);
    assert_eq!(board.last_event(), Some(first), "the wheel was still held");
}

/// A refused spin must not touch the PRNG.
///
/// The draw that picks the face comes *after* the cooldown check, and it
/// has to: the stream is the round. A draw per refused Sparkling crab
/// would have two peers disagreeing about every crab, gull and event after
/// a single held spin, and every kept replay playing back differently.
#[test]
fn a_held_spin_does_not_spend_a_draw() {
    let mut board = Board::new(9, 7, 2);
    board.set_events_enabled(true);
    board.force_tide_event(TideEvent::SpeedUp, 0);
    let untouched = board.state_hash();
    for _ in 0..25 {
        board.spin_tide_event(0);
    }
    assert_eq!(
        board.state_hash(),
        untouched,
        "a refused spin moved the board: the draw is being spent"
    );
}

/// The wheel comes back the moment the cooldown runs out, and not a tick
/// before: expiring early lets two events overlap after all, and never
/// expiring is a mute button on the whole mechanic.
#[test]
fn the_wheel_comes_back_on_the_tick_the_cooldown_ends() {
    let mut board = Board::new(9, 7, 2);
    board.set_events_enabled(true);
    board.force_tide_event(TideEvent::SlowDown, 0);
    let held = board.last_event().expect("the forced event landed");
    // One tick short: still held.
    for _ in 0..(EVENT_COOLDOWN - 1) {
        board.tick_idle();
    }
    board.spin_tide_event(0);
    assert_eq!(board.last_event(), Some(held), "it opened a tick early");
    board.tick_idle();
    board.spin_tide_event(0);
    assert_ne!(board.last_event(), Some(held), "and never opened at all");
}

/// The roulette holds off while an event is still running.
///
/// It is spun by banking a Sparkling crab, and several faces of the wheel
/// (Crab Mania, Speed Up) put more crabs on the beach - so without a valve
/// the events raise their own rate and arrive in waves. This is the valve:
/// one event, then nothing for `EVENT_COOLDOWN`, then the wheel is live
/// again. The crab still banks either way; only the spin is held.
#[test]
fn the_roulette_will_not_spin_on_top_of_a_running_event() {
    let mut board = Board::new(9, 7, 2);
    board.set_events_enabled(true);
    board.force_tide_event(TideEvent::SpeedUp, 0);
    let first = board.last_event().expect("the forced event landed");
    assert_eq!(first.0, TideEvent::SpeedUp);

    // Every spin inside the cooldown is refused, however many crabs bank.
    for _ in 0..40 {
        board.spin_tide_event(0);
        assert_eq!(
            board.last_event(),
            Some(first),
            "a second event started on top of the first"
        );
    }
    // And the wheel comes back once the first event has run its course.
    for _ in 0..EVENT_COOLDOWN {
        board.tick_idle();
    }
    board.spin_tide_event(0);
    assert_ne!(
        board.last_event(),
        Some(first),
        "the wheel never came back: it is a mute button, not a cooldown"
    );
}

/// Under a timed lock only an event that lasts holds the wheel: one over
/// in the tick it fired leaves the next sparkling crab free to spin.
#[test]
fn a_timed_lock_holds_the_wheel_only_for_an_event_that_lasts() {
    for event in TideEvent::ALL {
        let mut board = Board::new(9, 7, 2);
        board.set_events_enabled(true);
        board.set_timed_lock(true);
        board.force_tide_event(event, 0);
        let first = board.last_event().expect("the forced event landed");
        // A tick on, so a spin landing on the same face reads as new.
        board.tick_idle();
        board.spin_tide_event(0);
        assert_eq!(
            board.last_event() == Some(first),
            event.lasts(),
            "{event:?} held the wheel wrongly"
        );
    }
}

/// An instant event called on top of a timed one leaves the timed one's
/// lock where it was.
#[test]
fn a_timed_lock_outlasts_an_instant_event_called_on_top() {
    let mut board = Board::new(9, 7, 2);
    board.set_events_enabled(true);
    board.set_timed_lock(true);
    board.force_tide_event(TideEvent::CrabMania, 0);
    board.tick_idle();
    board.force_tide_event(TideEvent::FreshSand, 0);
    let fresh = board.last_event();
    board.tick_idle();
    board.spin_tide_event(0);
    assert_eq!(board.last_event(), fresh, "the mania's lock was lifted");
}

/// Without the rule every event holds the wheel, the instant ones too: the
/// lock a file that does not say `timed_lock: on` keeps.
#[test]
fn without_a_timed_lock_an_instant_event_holds_the_wheel() {
    for event in TideEvent::ALL.into_iter().filter(|e| !e.lasts()) {
        let mut board = Board::new(9, 7, 2);
        board.set_events_enabled(true);
        board.force_tide_event(event, 0);
        let first = board.last_event();
        board.tick_idle();
        board.spin_tide_event(0);
        assert_eq!(board.last_event(), first, "{event:?} left the wheel free");
    }
}

/// `can_place_signpost` must agree with `place_signpost` on every tile, in
/// both cap policies, including the at-cap and rival-post cases.
#[test]
fn can_place_mirrors_place() {
    for policy in [CapPolicy::Reject, CapPolicy::Evict] {
        let mut board = Board::new(6, 5, 3);
        board.set_signpost_rule(2, policy);
        board.set_tile(4, 0, TileKind::Rock);
        assert!(board.place_signpost(1, 5, 0, Down)); // rival post
        assert!(board.place_signpost(0, 0, 0, Right));
        assert!(board.place_signpost(0, 1, 0, Right)); // player 0 at cap
        for y in 0..board.height() {
            for x in 0..board.width() {
                let predicted = board.can_place_signpost(0, x, y);
                let mut probe = board.clone();
                assert_eq!(
                    probe.place_signpost(0, x, y, Up),
                    predicted,
                    "({x},{y}) under {policy:?}"
                );
            }
        }
    }
}

#[test]
fn signpost_fade_is_full_under_puzzle_rules_and_decays_under_evict() {
    let mut board = Board::new(5, 5, 0);
    // Puzzle rules (Reject): permanent, always full, however old. Set
    // before the post goes down, since a fresh post reads full under
    // either rule.
    board.set_signpost_rule(3, CapPolicy::Reject);
    assert!(board.place_signpost(0, 2, 2, Right));
    let sp = board.signpost_at(2, 2).unwrap();
    for _ in 0..SIGNPOST_LIFETIME {
        board.tick_idle();
    }
    assert_eq!(board.signpost_fade(&sp), 1.0, "a puzzle post never fades");
    assert!(board.signpost_at(2, 2).is_some(), "nor washes away");

    // Versus rules (Evict): full when fresh, half at half-life, gone at end.
    let mut board = Board::new(5, 5, 0);
    board.set_signpost_rule(3, CapPolicy::Evict);
    assert!(board.place_signpost(0, 2, 2, Right));
    let sp = board.signpost_at(2, 2).unwrap();
    assert_eq!(board.signpost_fade(&sp), 1.0);
    for _ in 0..SIGNPOST_LIFETIME / 2 {
        board.tick_idle();
    }
    let sp = board.signpost_at(2, 2).unwrap();
    let half = board.signpost_fade(&sp);
    assert!((half - 0.5).abs() < 0.01, "half-life fade was {half}");
    for _ in 0..SIGNPOST_LIFETIME / 2 + 1 {
        board.tick_idle();
    }
    assert!(
        board.signpost_at(2, 2).is_none(),
        "post washed away at end of life"
    );
}

#[test]
fn first_signpost_of_scans_in_reading_order() {
    let mut board = Board::new(6, 6, 0);
    assert_eq!(board.first_signpost_of(0), None);
    assert!(board.place_signpost(0, 4, 3, Left));
    assert!(board.place_signpost(0, 1, 3, Up));
    assert!(board.place_signpost(0, 3, 1, Down));
    // Row-major: (3,1) beats both y=3 posts; other players see nothing.
    assert_eq!(board.first_signpost_of(0), Some((3, 1)));
    assert_eq!(board.first_signpost_of(1), None);
}

/// The eat check is a hard boundary at [`EAT_RANGE`] subunits (spec §4.3):
/// exactly in range is eaten, one subunit past is not.
#[test]
fn gulls_eat_exactly_at_the_range_boundary() {
    for (crab_progress, expect_eaten) in [(EAT_RANGE - 8, true), (EAT_RANGE - 7, false)] {
        let mut board = Board::new(5, 5, 0);
        common(&mut board, 2, 2, Down, Handedness::Left);
        board.spawn_gull(2, 2, Right);
        board.crabs[0].progress = crab_progress;
        board.gulls[0].progress = 8;
        // Offsets: gull (8, 0), crab (0, p) -> Manhattan distance 8 + p.
        board.gulls_eat();
        assert_eq!(
            board.crabs.is_empty(),
            expect_eaten,
            "distance {}",
            8 + crab_progress
        );
    }
}

/// Two creatures meeting head-on through the seam of a wrapping arena are
/// a tile apart on the sand and a whole board apart in raw coordinates.
/// The eat check has to measure the sand, or a gull and a crab walk
/// through each other there; the same board without the seam keeps them
/// apart, since there is a wall between them.
#[test]
fn gulls_eat_across_the_seam_of_a_wrapping_board() {
    for wrap in [false, true] {
        let mut board = Board::new(5, 3, 0);
        board.set_wrap(wrap);
        common(&mut board, 4, 1, Right, Handedness::Left);
        board.spawn_gull(0, 1, Left);
        // Gull at x = -120, crab at x = 4 * 256 + 120: sixteen subunits
        // apart through the seam, twelve hundred and more the other way.
        board.crabs[0].progress = 120;
        board.gulls[0].progress = 120;
        board.gulls_eat();
        assert_eq!(board.crabs.is_empty(), wrap, "wrap {wrap}");
    }
}

/// Where a gull may be put down, asked of the board rather than kept by
/// each placer: sand and pool yes, rock and kelp no, off the board no.
#[test]
fn a_gull_may_stand_on_sand_and_in_a_pool_but_not_on_rock_or_kelp() {
    let mut board = Board::new(5, 5, 0);
    board.set_tile(1, 1, TileKind::Rock);
    board.set_tile(2, 2, TileKind::Kelp);
    board.set_tile(3, 3, TileKind::Pool);
    assert!(board.gull_may_stand(0, 0), "sand");
    assert!(board.gull_may_stand(3, 3), "a pool");
    assert!(!board.gull_may_stand(1, 1), "rock");
    assert!(!board.gull_may_stand(2, 2), "kelp");
    assert!(!board.gull_may_stand(5, 0), "off the board");
}

/// Evict with a cap of zero is refused by every parser, but a board built
/// by hand can still be told it. The first placement then has nothing to
/// evict and is refused, rather than expecting an oldest post to exist.
#[test]
fn evicting_with_nothing_to_evict_refuses_rather_than_panics() {
    let mut board = Board::new(5, 5, 0);
    board.set_signpost_rule(0, CapPolicy::Evict);
    assert!(
        board.can_place_signpost(0, 2, 2),
        "the rule says evict, so yes"
    );
    assert!(
        !board.place_signpost(0, 2, 2, Right),
        "but there is nothing to trade"
    );
    assert!(board.signpost_at(2, 2).is_none());
}

/// The editor's removers take coordinates like every other public
/// mutator, and check them like every other: off the board is a bug in
/// the caller, said loudly rather than removing from a wrong tile.
#[test]
#[should_panic(expected = "crab off the board")]
fn removing_crabs_off_the_board_is_refused_loudly() {
    Board::new(5, 5, 0).remove_crabs_at(5, 0);
}

#[test]
#[should_panic(expected = "gull off the board")]
fn removing_gulls_off_the_board_is_refused_loudly() {
    Board::new(5, 5, 0).remove_gulls_at(0, 5);
}

/// The lure's short way is per axis too.
#[test]
fn a_lure_pulls_through_the_top_and_bottom_seam_as_well() {
    for (wrap, expect) in [(false, Down), (true, Up)] {
        let mut board = Board::new(3, 5, 0);
        board.set_wrap(wrap);
        board.set_tile(1, 4, TileKind::Castle(0));
        board.force_lure(0);
        let target = board.lure_target();
        assert_eq!(
            board.lure_step(board.index_of(1, 0), target),
            Some(expect),
            "wrap {wrap}"
        );
    }
}

/// The fold is per axis: the top and bottom edges are a seam too.
#[test]
fn gulls_eat_across_the_top_and_bottom_seam_as_well() {
    for wrap in [false, true] {
        let mut board = Board::new(3, 5, 0);
        board.set_wrap(wrap);
        common(&mut board, 1, 4, Down, Handedness::Left);
        board.spawn_gull(1, 0, Up);
        board.crabs[0].progress = 120;
        board.gulls[0].progress = 120;
        board.gulls_eat();
        assert_eq!(board.crabs.is_empty(), wrap, "wrap {wrap}");
    }
}

/// A lured crab takes the short way to the castle, which on a wrapping
/// board can be through the seam.
#[test]
fn a_lure_pulls_through_the_seam_when_that_is_the_short_way() {
    for (wrap, expect) in [(false, Right), (true, Left)] {
        let mut board = Board::new(5, 3, 0);
        board.set_wrap(wrap);
        board.set_tile(4, 1, TileKind::Castle(0));
        board.force_lure(0);
        let target = board.lure_target();
        assert_eq!(
            board.lure_step(board.index_of(0, 1), target),
            Some(expect),
            "wrap {wrap}"
        );
    }
}

#[test]
fn turnstile_alternates_deflections() {
    let mut board = Board::new(5, 5, 0);
    board.set_tile(2, 2, TileKind::Turnstile { next_right: true });
    // Two crabs cross the log one after the other, both heading Right.
    common(&mut board, 0, 2, Right, Handedness::Left);
    for _ in 0..ticks_to_cross(2, 12) {
        board.tick_idle();
    }
    // First crossing deflects right (screen Down for a Right-walker).
    assert_eq!(board.crabs()[0].dir, Down);
    common(&mut board, 0, 2, Right, Handedness::Left);
    for _ in 0..ticks_to_cross(2, 12) {
        board.tick_idle();
    }
    // Second crossing deflects left (screen Up).
    assert_eq!(board.crabs()[1].dir, Up);
}

#[test]
fn kelp_blocks_walking_gulls_but_not_crabs() {
    // A 3x1 corridor with kelp in the middle: the crab passes through; the
    // gull treats it like a wall (separate boards so nobody gets eaten).
    let mut crabs = Board::new(3, 1, 0);
    crabs.set_tile(1, 0, TileKind::Kelp);
    common(&mut crabs, 0, 0, Right, Handedness::Left);
    for _ in 0..ticks_to_cross(2, 12) + 1 {
        crabs.tick_idle();
    }
    assert_eq!(crabs.crabs()[0].tile, 2, "crab crossed the kelp corridor");

    let mut gulls = Board::new(3, 1, 0);
    gulls.set_tile(1, 0, TileKind::Kelp);
    gulls.spawn_gull(2, 0, Left);
    gulls.tick_idle();
    let gull = gulls.gulls()[0];
    assert_eq!(gull.dir, Right, "gull reversed off the kelp");
    assert_eq!(gull.tile, 2, "and stays put in the dead end");
}

#[test]
fn pools_halve_wading_speed() {
    let mut dry = Board::new(5, 1, 0);
    let mut wet = Board::new(5, 1, 0);
    wet.set_tile(0, 0, TileKind::Pool);
    common(&mut dry, 0, 0, Right, Handedness::Left);
    common(&mut wet, 0, 0, Right, Handedness::Left);
    dry.tick_idle();
    wet.tick_idle();
    assert_eq!(dry.crabs()[0].progress, 12);
    assert_eq!(wet.crabs()[0].progress, 6, "wading is half speed");
}

/// Turnstiles deflect walking gulls exactly like crabs, flipping per
/// crossing - a defensive tool against steered raids.
#[test]
fn turnstile_deflects_walking_gulls_too() {
    let mut board = Board::new(5, 5, 0);
    board.set_tile(2, 2, TileKind::Turnstile { next_right: true });
    board.spawn_gull(0, 2, Right);
    for _ in 0..ticks_to_cross(2, u32::from(GULL_WALK_SPEED)) {
        board.tick_idle();
    }
    assert_eq!(board.gulls()[0].dir, Down, "first crossing deflects right");
    assert_eq!(
        board.tile_at(2, 2),
        TileKind::Turnstile { next_right: false },
        "the log flipped"
    );
}

#[test]
fn gulls_wade_pools_at_half_speed() {
    let mut board = Board::new(5, 1, 0);
    board.set_tile(0, 0, TileKind::Pool);
    board.spawn_gull(0, 0, Right);
    board.tick_idle();
    assert_eq!(board.gulls()[0].progress, GULL_WALK_SPEED / 2);
}

/// A flying gull cannot land in kelp: it glides one more tile, exactly as
/// over a rock.
#[test]
fn flying_gulls_glide_past_kelp() {
    let mut board = Board::new(5, 1, 0);
    board.set_tile(2, 0, TileKind::Kelp);
    board.spawn_gull(1, 0, Right);
    // The walking spawn wall-resolved away from the kelp; flight ignores
    // terrain, so point it back before takeoff.
    board.gulls[0].dir = Right;
    board.gulls[0].state = GullState::Flying { remaining: 1 };
    // One flight hop per arrival: tick until it lands.
    while matches!(board.gulls()[0].state, GullState::Flying { .. }) {
        board.tick_idle();
    }
    assert_eq!(board.gulls()[0].tile, 3, "landed past the kelp, not in it");
}

// --- M4: gulls, castles, molting, tide -------------------------------

#[test]
fn gull_obeys_and_degrades_signposts() {
    let mut board = Board::new(7, 3, 0);
    assert!(board.place_signpost(0, 3, 1, Up));
    board.spawn_gull(0, 1, Right);
    // Gull walks at 8 subunits/tick: 3 tiles in 96 ticks, under the
    // 150-tick takeoff minimum.
    for _ in 0..ticks_to_cross(3, 8) {
        board.tick_idle();
    }
    assert_eq!(board.gulls()[0].dir, Up, "gull follows the signpost");
    assert_eq!(
        board.signpost_at(3, 1).unwrap().health,
        SignpostHealth::Worn
    );
    // A second gull crossing destroys it.
    board.spawn_gull(2, 1, Right);
    for _ in 0..ticks_to_cross(1, 8) {
        board.tick_idle();
    }
    assert!(board.signpost_at(3, 1).is_none());
}

#[test]
fn walking_gull_eats_crab_on_shared_tile() {
    let mut board = Board::new(5, 3, 0);
    common(&mut board, 2, 1, Right, Handedness::Left);
    board.spawn_gull(2, 1, Right);
    board.tick_idle();
    assert!(board.crabs().is_empty(), "crab within eat range is gone");
    assert_eq!(board.gulls().len(), 1);
}

#[test]
fn distant_crab_survives_the_gull() {
    let mut board = Board::new(9, 1, 0);
    common(&mut board, 8, 0, Left, Handedness::Left);
    board.spawn_gull(0, 0, Right);
    board.tick_idle();
    assert_eq!(board.crabs().len(), 1);
}

#[test]
fn gull_raid_halves_the_castle() {
    let mut board = Board::new(7, 5, 0);
    board.set_tile(4, 2, TileKind::Castle(1));
    board.scores[1] = 30;
    board.spawn_gull(0, 2, Right);
    for _ in 0..ticks_to_cross(4, 8) {
        board.tick_idle();
    }
    assert_eq!(board.scores()[1], 15, "half the banked crabs carried off");
    assert_eq!(
        board.crabs().len(),
        SPILL_CAP as usize,
        "the spill cap of live crabs lands on the sand"
    );
    assert!(
        board.gulls().is_empty(),
        "the raider departs the beach with its loot"
    );
}

/// With raids off a gull still walks into the castle and still leaves the
/// beach - it just takes nothing with it.
///
/// The puzzle rule. A raid spills banked crabs back onto the sand, each
/// counting as newly spawned, so the "Saved a/b" denominator climbed every
/// time a gull touched the castle: nine shipped campaign levels did it
/// while playing the authored solution.
///
/// The departure has to survive: a castle is the one tile that takes a gull
/// off the sand, and sealing it instead left Two Giants unsolvable.
#[test]
fn a_raid_with_raids_off_takes_nothing_and_still_ends_the_visit() {
    let mut board = Board::new(7, 5, 0);
    board.set_tile(4, 2, TileKind::Castle(1));
    board.set_castle_raids(false);
    board.scores[1] = 30;
    board.spawn_gull(0, 2, Right);
    let spawned_before = board.crabs_spawned();
    for _ in 0..ticks_to_cross(4, 8) {
        board.tick_idle();
    }
    assert_eq!(board.scores()[1], 30, "the bank is not robbed");
    assert_eq!(
        board.crabs_spawned(),
        spawned_before,
        "nothing spills, so the level's target stays where it was"
    );
    assert!(
        board.gulls().is_empty(),
        "the visitor still leaves the beach, which is what the levels rely on"
    );

    // A crab walks the same lane straight in and banks, as ever.
    let mut board = Board::new(7, 5, 0);
    board.set_tile(4, 2, TileKind::Castle(1));
    board.set_castle_raids(false);
    board.spawn_crab(0, 2, Right, Handedness::Left, CrabKind::Common);
    for _ in 0..ticks_to_cross(4, 12) {
        board.tick_idle();
    }
    assert_eq!(board.crabs_banked(), 1, "the castle is still the goal");
}

#[test]
fn empty_castle_hit_is_harmless() {
    let mut board = Board::new(7, 5, 0);
    board.set_tile(4, 2, TileKind::Castle(1));
    board.spawn_gull(0, 2, Right);
    for _ in 0..ticks_to_cross(4, 8) {
        board.tick_idle();
    }
    assert_eq!(board.scores()[1], 0);
    assert!(board.crabs().is_empty());
}

#[test]
fn flight_crosses_walls_and_lands_on_sand() {
    let mut board = Board::new(9, 1, 7);
    board.set_wall(0, 0, Right, true); // walking would bounce off this
    board.spawn_gull(0, 0, Right);
    board.gulls[0].takeoff_in = 0; // force takeoff next tick
    board.gulls[0].dir = Right; // spawn wall-resolve reversed it; fly right
    for _ in 0..80 {
        board.tick_idle();
        if board.gulls[0].state == GullState::Walking && board.gulls[0].tile > 0 {
            break;
        }
    }
    let gull = board.gulls()[0];
    assert_eq!(gull.state, GullState::Walking, "flight ended");
    assert!(
        (2..=4).contains(&gull.tile),
        "landed 2-4 tiles out, past the wall (tile {})",
        gull.tile
    );
}

#[test]
fn molting_bank_lures_loose_crabs_then_expires() {
    let mut board = Board::new(7, 5, 0);
    board.set_tile(6, 2, TileKind::Castle(2));
    board.spawn_crab(5, 2, Right, Handedness::Left, CrabKind::Molting);
    common(&mut board, 0, 2, Up, Handedness::Left);
    let bank_tick = ticks_to_cross(1, 12);
    for _ in 0..bank_tick {
        board.tick_idle();
    }
    let (owner, _) = board.lure().expect("molting bank starts the lure");
    assert_eq!(owner, 2);
    // The loose crab was walking Up; its arrival under the lure turns it
    // toward the castle at (6,2): dx dominates, so Right.
    assert_eq!(board.crabs()[0].dir, Right);
    for _ in 0..LURE_TICKS {
        board.tick_idle();
    }
    assert!(board.lure().is_none(), "lure expires after 10 s");
}

/// The lure does not stack and does not restart on its own heels: a molt
/// banked while one is running, or during the quiet spell after, banks for
/// its points and nothing more. Without this the lure feeds itself, because
/// the crabs it delivers include the next molting crab.
#[test]
fn a_lure_neither_stacks_nor_restarts_at_once() {
    let mut board = Board::new(7, 5, 0);
    board.set_tile(6, 2, TileKind::Castle(0));
    board.set_tile(6, 4, TileKind::Castle(1));
    // Two molts, one for each castle, arriving a few ticks apart.
    board.spawn_crab(5, 2, Right, Handedness::Left, CrabKind::Molting);
    board.spawn_crab(4, 4, Right, Handedness::Left, CrabKind::Molting);
    while board.lure().is_none() {
        board.tick_idle();
    }
    let (owner, started_with) = board.lure().expect("the first molt lures");
    assert_eq!(owner, 0);
    // The second molt banks during the lure: it must not take it over, and
    // must not top the clock back up.
    let mut lowest = started_with;
    for _ in 0..LURE_TICKS - 1 {
        board.tick_idle();
        if let Some((who, left)) = board.lure() {
            assert_eq!(who, 0, "a molt banked mid-lure must not steal it");
            assert!(left <= lowest, "the clock only ever runs down");
            lowest = left;
        }
    }
    board.tick_idle();
    assert!(board.lure().is_none(), "and it ends on time");

    // In the quiet spell a fresh molt banks for points only.
    board.spawn_crab(5, 2, Right, Handedness::Left, CrabKind::Molting);
    let before = board.scores()[0];
    for _ in 0..LURE_COOLDOWN / 2 {
        board.tick_idle();
    }
    assert!(board.scores()[0] > before, "it still banked");
    assert!(board.lure().is_none(), "but started nothing");

    // Once the spell is over, the next molt lures again.
    for _ in 0..LURE_COOLDOWN {
        board.tick_idle();
    }
    board.spawn_crab(5, 2, Right, Handedness::Left, CrabKind::Molting);
    for _ in 0..ticks_to_cross(1, 12) + 2 {
        board.tick_idle();
    }
    assert!(board.lure().is_some(), "the cooldown has passed");
}

/// The ambient spawners fill the beach to a cap and then wait. Crab Mania
/// floods past it, but only to twice the cap.
#[test]
fn the_beach_fills_to_a_cap_and_mania_to_twice_it() {
    let mut board = Board::new(9, 9, 5); // 81 tiles: cap 27, mania 54
    for (x, y, dir) in [(0u8, 4u8, Right), (8, 4, Left)] {
        board.set_tile(x, y, TileKind::Spawner(Spawner { dir, period: 2 }));
    }
    // A castle in the middle of the lane, so the population cycles and the
    // cap is a standing level rather than a one-way fill.
    board.set_tile(4, 4, TileKind::Castle(0));
    // The roulette stays off for the fill: what this measures is the cap
    // and the mania, and a sparkling crab banking into that castle would
    // spin a wheel whose faces move the population around. It was left on,
    // and the flood was measured from wherever the last event had put the
    // beach: adding a ninth face moved the draws and the peak landed one
    // crab under the bound. `apply_tide_event` fires regardless, which is
    // what the mania below is started with.
    board.set_events_enabled(false);
    for _ in 0..1200 {
        board.tick_idle();
    }
    let cap = 81 / 3;
    assert!(
        board.crabs().len() <= cap + 2,
        "ambient spawning stops at the cap, saw {}",
        board.crabs().len()
    );
    assert!(
        board.crabs_spawned() > 100,
        "and it kept spawning as the banked ones made room, saw {}",
        board.crabs_spawned()
    );

    board.apply_tide_event(TideEvent::CrabMania, 0);
    // Watched across the whole flood rather than read at the end of it: the
    // mania lasts `EVENT_TICKS` and the beach drains back to the cap once
    // it lifts, so a count taken 600 ticks later measures the drain.
    let mut peak = board.crabs().len();
    for _ in 0..600 {
        board.tick_idle();
        peak = peak.max(board.crabs().len());
    }
    assert!(peak > cap + 2, "the mania floods past the cap, saw {peak}");
    assert!(peak <= cap * 2 + 4, "but not without bound, saw {peak}");
}

/// The surge already doubles the flock, so the roulette swaps its two gull
/// events for something the players can still route.
#[test]
fn the_roulette_keeps_gulls_out_of_the_surge() {
    let mut board = party_board();
    board.set_round_length(Some(1000));
    assert!(!board.in_surge());
    board.apply_tide_event(TideEvent::GullMania, 0);
    assert_eq!(
        board.last_event().map(|(e, _)| e),
        Some(TideEvent::GullMania),
        "outside the surge it stands"
    );

    // Into the last 30 seconds, where a spin lands on the gull events.
    let mut surging = party_board();
    surging.set_round_length(Some(200));
    surging.set_score(0, 1); // a sparkling bank needs a castle owner
    for _ in 0..100 {
        surging.tick_idle();
    }
    assert!(surging.in_surge());
    // The spin's filter, asked outright: the wheel itself draws from the
    // PRNG, and which face it lands on is not the point.
    assert_eq!(
        surging.surge_safe(TideEvent::GullMania),
        TideEvent::CrabMania
    );
    assert_eq!(
        surging.surge_safe(TideEvent::GullAttack),
        TideEvent::SpeedUp
    );
    for kept in [
        TideEvent::CrabMania,
        TideEvent::Monopoly,
        TideEvent::SpeedUp,
        TideEvent::SlowDown,
        TideEvent::FreshSand,
        TideEvent::CastleSwap,
    ] {
        assert_eq!(surging.surge_safe(kept), kept, "{kept:?} stands");
    }
    assert_eq!(
        board.surge_safe(TideEvent::GullMania),
        TideEvent::GullMania,
        "outside the surge"
    );
    // Applying one directly is still honoured; only the spin is filtered.
    surging.apply_tide_event(TideEvent::GullMania, 0);
    assert_eq!(
        surging.last_event().map(|(e, _)| e),
        Some(TideEvent::GullMania)
    );
}

#[test]
fn tide_freezes_the_sim_and_surges_gulls() {
    let mut board = Board::new(7, 5, 3);
    board.set_gull_period(500);
    board.set_round_length(Some(2000));
    common(&mut board, 0, 0, Right, Handedness::Left);
    for _ in 0..1099 {
        board.tick_idle();
    }
    assert!(!board.in_surge(), "901 ticks left: not yet the scramble");
    board.tick_idle();
    assert!(board.in_surge(), "900 ticks left: final scramble");
    for _ in 0..900 {
        board.tick_idle();
    }
    assert!(board.round_over());
    let frozen = board.state_hash();
    for _ in 0..10 {
        board.tick_idle();
    }
    assert_eq!(board.state_hash(), frozen, "scores locked at the wave");
}

#[test]
fn versus_signposts_fade_away() {
    let mut board = Board::new(5, 3, 0); // default Evict rules
    assert!(board.place_signpost(0, 2, 1, Up));
    for _ in 0..SIGNPOST_LIFETIME {
        board.tick_idle();
    }
    assert!(
        board.signpost_at(2, 1).is_some(),
        "alive through its lifetime"
    );
    board.tick_idle();
    assert!(board.signpost_at(2, 1).is_none(), "faded one tick after");
}

#[test]
fn puzzle_signposts_are_permanent() {
    let mut board = Board::new(5, 3, 0);
    board.set_signpost_rule(3, CapPolicy::Reject);
    assert!(board.place_signpost(0, 2, 1, Up));
    for _ in 0..SIGNPOST_LIFETIME * 2 {
        board.tick_idle();
    }
    assert!(board.signpost_at(2, 1).is_some());
}

#[test]
fn wrapped_edges_carry_crabs_across() {
    let mut board = Board::new(3, 3, 0);
    board.set_wrap(true);
    common(&mut board, 2, 1, Right, Handedness::Left);
    for _ in 0..ticks_to_cross(1, 12) {
        board.tick_idle();
    }
    let crab = board.crabs()[0];
    assert_eq!(crab.tile, 3, "walked off the east edge onto (0,1)");
    assert_eq!(crab.dir, Right);
}

/// The public step the bot plans with agrees with the beach the crabs walk:
/// off the edge is nowhere on a plain board, and the far side on a wrapping
/// one. The bot used to stop at the seam while the crabs crossed it.
#[test]
fn a_step_crosses_the_seam_exactly_when_the_beach_wraps() {
    let mut board = Board::new(6, 5, 0);
    let corner = 0u16; // (0,0)
    assert_eq!(board.step(corner, Left), None);
    assert_eq!(board.step(corner, Up), None);
    assert_eq!(board.step(corner, Right), Some(1));
    assert_eq!(board.step(corner, Down), Some(6));
    board.set_wrap(true);
    assert_eq!(board.step(corner, Left), Some(5), "west seam to (5,0)");
    assert_eq!(board.step(corner, Up), Some(24), "north seam to (0,4)");
}

#[test]
fn sparkling_bank_spins_events_only_when_enabled() {
    let mut quiet = Board::new(5, 3, 9);
    quiet.set_tile(4, 1, TileKind::Castle(0));
    quiet.spawn_crab(3, 1, Right, Handedness::Left, CrabKind::Sparkling);
    for _ in 0..ticks_to_cross(1, 12) {
        quiet.tick_idle();
    }
    assert!(quiet.last_event().is_none(), "events off by default");

    let mut party = Board::new(5, 3, 9);
    party.set_events_enabled(true);
    party.set_tile(4, 1, TileKind::Castle(0));
    party.spawn_crab(3, 1, Right, Handedness::Left, CrabKind::Sparkling);
    for _ in 0..ticks_to_cross(1, 12) {
        party.tick_idle();
    }
    let (event, at) = party.last_event().expect("roulette spun");
    assert!(at < party.ticks());
    // The event actually did something observable for the effects that
    // leave immediate state (others set timers).
    match event {
        TideEvent::SpeedUp | TideEvent::SlowDown => {
            assert_ne!(party.state_hash(), quiet.state_hash());
        }
        TideEvent::CrabMania
        | TideEvent::GullMania
        | TideEvent::Monopoly
        | TideEvent::GullAttack
        | TideEvent::FreshSand
        | TideEvent::CastleSwap
        | TideEvent::RightClaws => {}
    }
}

// --- tide events, one by one -------------------------------------

fn party_board() -> Board {
    let mut board = Board::new(7, 5, 11);
    board.set_events_enabled(true);
    board.set_tile(1, 1, TileKind::Castle(0));
    board.set_tile(5, 3, TileKind::Castle(1));
    board
}

/// A called event fires from the action stream, the same way a placement
/// does, so every peer runs it on the frame it arrived with.
#[test]
fn a_called_event_fires_from_a_seats_input() {
    let mut board = party_board();
    board.spawn_crab(3, 2, Right, Handedness::Right, CrabKind::Common);
    board.place_signpost(0, 3, 1, Right);
    assert_eq!(board.signpost_count(0), 1, "an arrow to wash away");

    let mut actions = [PlayerAction::None; MAX_PLAYERS];
    actions[0] = PlayerAction::CallEvent(TideEvent::FreshSand);
    board.tick(&actions);

    assert_eq!(board.signpost_count(0), 0, "fresh sand took it");
    let (event, _) = board.last_event().expect("the call fired");
    assert_eq!(event, TideEvent::FreshSand);
}

/// A called event goes through the surge guard, the same as a spun one.
///
/// The guard is not the wheel's bookkeeping but a rule about the beach,
/// and a measured one: Gull Mania on top of the surge leaves fifteen gulls
/// and almost no crabs with half a minute to play. A crowd calling it down
/// is that case at its worst, not an exception to it.
#[test]
fn a_called_event_is_held_to_the_surge_guard_too() {
    let mut board = party_board();
    board.set_round_length(Some(SURGE_TICKS));
    assert!(board.in_surge(), "inside the last stretch");

    let mut actions = [PlayerAction::None; MAX_PLAYERS];
    actions[0] = PlayerAction::CallEvent(TideEvent::GullMania);
    board.tick(&actions);

    let (event, _) = board.last_event().expect("something fired");
    assert_eq!(
        event,
        TideEvent::CrabMania,
        "swapped, exactly as the wheel's own draw would be"
    );

    // And outside the surge the call stands as made.
    let mut calm = party_board();
    let mut actions = [PlayerAction::None; MAX_PLAYERS];
    actions[0] = PlayerAction::CallEvent(TideEvent::GullMania);
    calm.tick(&actions);
    assert_eq!(calm.last_event().expect("fired").0, TideEvent::GullMania);
}

/// Right Claws: while it runs, the claw a crab leads with decides whether
/// banking it is worth doing at all.
#[test]
fn event_right_claws_pays_one_hand_and_charges_the_other() {
    let mut board = party_board();
    // Walk a crab of each hand into seat 0's castle at (1,1), from the
    // tile to its right.
    // Ticked until the beach is empty rather than for a fixed count: a
    // giant walks at a tenth of a common crab's pace, and a budget that
    // suited one left the other still on the sand.
    let bank = |board: &mut Board, handed: Handedness, kind: CrabKind| {
        board.spawn_crab(2, 1, Left, handed, kind);
        for _ in 0..ticks_to_cross(1, 12) * 16 {
            board.tick_idle();
            if board.crabs().is_empty() {
                return;
            }
        }
        panic!("the crab never reached the castle");
    };

    // Off, a crab is worth what it says, whichever claw it leads with.
    bank(&mut board, Handedness::Right, CrabKind::Common);
    bank(&mut board, Handedness::Left, CrabKind::Common);
    assert_eq!(board.scores()[0], 2, "two common crabs, two points");

    board.apply_tide_event(TideEvent::RightClaws, 0);
    bank(&mut board, Handedness::Right, CrabKind::Common);
    assert_eq!(board.scores()[0], 4, "the right claw pays twice over");
    bank(&mut board, Handedness::Left, CrabKind::Common);
    assert_eq!(board.scores()[0], 3, "and the left one costs the same");

    // Down to nothing and no further: a child staring at a minus sign has
    // stopped playing.
    bank(&mut board, Handedness::Left, CrabKind::Giant);
    assert_eq!(board.scores()[0], 0, "a giant costs 10 into a score of 3");

    // What a bot reads before it goes fetching, which has to be the same
    // answer the bank will give: a jackpot on the wrong claw is not a
    // jackpot. Read off crabs standing still, well away from the castle.
    board.spawn_crab(5, 0, Up, Handedness::Right, CrabKind::Golden);
    board.spawn_crab(5, 4, Down, Handedness::Left, CrabKind::Golden);
    let worths: Vec<Option<u32>> = board.crabs().iter().map(|c| board.bank_worth(c)).collect();
    assert_eq!(
        worths,
        vec![Some(100), None],
        "the right claw doubles, the left one is worth leaving alone"
    );

    // And it lifts, leaving the ordinary rule behind it.
    for _ in 0..EVENT_TICKS {
        board.tick_idle();
    }
    let worths: Vec<Option<u32>> = board.crabs().iter().map(|c| board.bank_worth(c)).collect();
    assert!(
        worths.iter().all(|&w| w == Some(50)),
        "worth what they say again: {worths:?}"
    );
}

#[test]
fn event_crab_mania_clears_gulls_and_floods() {
    let mut board = party_board();
    board.set_tile(
        0,
        2,
        TileKind::Spawner(Spawner {
            dir: Right,
            period: 100,
        }),
    );
    board.spawn_gull(3, 2, Right);
    board.apply_tide_event(TideEvent::CrabMania, 0);
    assert!(board.gulls().is_empty(), "gulls washed away");
    let before = board.crabs().len();
    for _ in 0..64 {
        board.tick_idle();
    }
    assert!(
        board.crabs().len() >= before + 8,
        "flood cadence: 8 spawns in 64 ticks"
    );
}

#[test]
fn event_gull_mania_spawns_gulls_from_holes() {
    let mut board = party_board();
    board.set_tile(
        0,
        2,
        TileKind::Spawner(Spawner {
            dir: Right,
            period: 100,
        }),
    );
    board.apply_tide_event(TideEvent::GullMania, 0);
    for _ in 0..64 {
        board.tick_idle();
    }
    assert!(
        board.gulls().len() >= 8,
        "holes emit gulls during the mania"
    );
}

#[test]
fn event_monopoly_banks_half_the_loose_crabs() {
    let mut board = party_board();
    for x in 0..6 {
        common(&mut board, x, 4, Right, Handedness::Left);
    }
    board.apply_tide_event(TideEvent::Monopoly, 1);
    assert_eq!(board.crabs().len(), 3);
    assert_eq!(board.scores()[1], 3);
    assert_eq!(board.crabs_banked(), 3);
}

/// Carried home, the swept crabs leave the beach at once, bank nothing
/// until they land, and land one after another, each written down against
/// the seat that got it on the tick it banks.
#[test]
fn a_flying_sweep_banks_each_crab_as_it_lands() {
    let mut board = party_board();
    board.set_sweep_flight(true);
    for x in 0..6 {
        common(&mut board, x, 4, Right, Handedness::Left);
    }
    board.apply_tide_event(TideEvent::Monopoly, 1);
    assert_eq!(board.crabs().len(), 3, "off the beach at once");
    assert_eq!(board.scores()[1], 0, "and nothing banked yet");
    let lands: Vec<u64> = board.sweeping().iter().map(|f| f.lands).collect();
    let first = SWEEP_HOLD + SWEEP_FLIGHT;
    assert_eq!(
        lands,
        [first, first + SWEEP_STAGGER, first + 2 * SWEEP_STAGGER]
    );
    let mut flying: Vec<(u32, u64)> = board
        .sweeping()
        .iter()
        .map(|f| (f.crab.id, f.lands))
        .collect();
    while !board.sweeping().is_empty() {
        let tick = board.ticks();
        board.tick_idle();
        flying.retain(|&(crab, lands)| {
            let landed = board.sweeping().iter().all(|f| f.crab.id != crab);
            if landed {
                assert_eq!(lands, tick, "crab {crab} landed on its tick");
                assert_eq!(board.swept_home(crab), Some(1), "for seat 1");
            }
            !landed
        });
    }
    assert!(board.scores()[1] >= 3, "all three banked");
}

/// The wave freezes the board, so whatever is still in the air lands on
/// the round's last tick rather than never.
#[test]
fn a_flying_sweep_lands_everything_at_the_wave() {
    let mut board = party_board();
    board.set_sweep_flight(true);
    board.set_round_length(Some(10));
    for x in 0..6 {
        common(&mut board, x, 4, Right, Handedness::Left);
    }
    board.apply_tide_event(TideEvent::Monopoly, 1);
    while !board.round_over() {
        board.tick_idle();
    }
    assert!(board.sweeping().is_empty(), "nothing left in the air");
    assert_eq!(board.scores()[1], 3, "and every crab paid");
}

/// A round saved mid-sweep picks up with the same crabs in the air,
/// landing on the same ticks.
#[test]
fn a_sweep_survives_a_snapshot_mid_flight() {
    let mut board = party_board();
    board.set_sweep_flight(true);
    for x in 0..6 {
        common(&mut board, x, 4, Right, Handedness::Left);
    }
    board.apply_tide_event(TideEvent::Monopoly, 1);
    for _ in 0..80 {
        board.tick_idle();
    }
    assert!(!board.sweeping().is_empty(), "caught in the air");
    let mut resumed = Board::parse_snapshot(&board.to_snapshot()).expect("snapshot");
    assert_eq!(resumed.state_hash(), board.state_hash());
    for _ in 0..200 {
        board.tick_idle();
        resumed.tick_idle();
    }
    assert_eq!(resumed.state_hash(), board.state_hash());
    assert_eq!(resumed.scores(), board.scores());
}

/// A crab the tide banks goes from a tile that is not a castle, which
/// from outside the sim is exactly what being eaten looks like. So the sim
/// writes down what it did, because nothing else can work it out
/// afterwards.
#[test]
fn a_swept_crab_is_written_down_against_the_seat_that_got_it() {
    let mut board = party_board();
    for x in 0..6 {
        common(&mut board, x, 4, Right, Handedness::Left);
    }
    let taken: Vec<u32> = board.crabs()[..3].iter().map(|crab| crab.id).collect();
    let left: Vec<u32> = board.crabs()[3..].iter().map(|crab| crab.id).collect();
    board.apply_tide_event(TideEvent::Monopoly, 1);
    for crab in taken {
        assert_eq!(
            board.swept_home(crab),
            Some(1),
            "crab {crab} went to seat 1"
        );
    }
    for crab in left {
        assert_eq!(board.swept_home(crab), None, "crab {crab} is still walking");
    }
    // And a crab nobody has ever heard of is nobody's.
    assert_eq!(board.swept_home(9999), None);
}

/// The record is news about one tick and is read between frames, which can
/// cover several ticks, so it outlives its own tick and then goes.
#[test]
fn a_swept_crab_is_remembered_a_few_ticks_and_then_forgotten() {
    let mut board = party_board();
    for x in 0..6 {
        common(&mut board, x, 4, Right, Handedness::Left);
    }
    let crab = board.crabs()[0].id;
    board.apply_tide_event(TideEvent::Monopoly, 1);
    assert_eq!(board.swept_home(crab), Some(1), "the tick it happened on");
    board.tick_idle();
    assert_eq!(board.swept_home(crab), Some(1), "and the frame after it");
    for _ in 0..SWEEP_MEMORY {
        board.tick_idle();
    }
    assert_eq!(board.swept_home(crab), None, "but not for the round");
}

/// The record is written for the render layer and never read back by the
/// sim, so it has no business in the fingerprint: a field that moved one
/// peer's hash would be a desync neither could see.
///
/// Put in by hand rather than by playing a round into it: the question is
/// whether the fingerprint can feel it at all.
#[test]
fn a_sweep_leaves_the_fingerprint_alone() {
    let mut board = party_board();
    for x in 0..6 {
        common(&mut board, x, 4, Right, Handedness::Left);
    }
    let before = board.state_hash();
    board.swept_home.push(Swept {
        crab: 7,
        owner: 1,
        at: 0,
    });
    assert_eq!(board.swept_home(7), Some(1), "the record is really there");
    assert_eq!(
        board.state_hash(),
        before,
        "and the fingerprint cannot feel it"
    );
}

#[test]
fn event_gull_attack_targets_rival_castles_only() {
    let mut board = party_board();
    board.apply_tide_event(TideEvent::GullAttack, 0);
    assert_eq!(board.gulls().len(), 1, "one gull, at the rival's castle");
    let (gx, gy) = (board.gulls()[0].tile % 7, board.gulls()[0].tile / 7);
    let dist = (i32::from(gx) - 5).abs() + (i32::from(gy) - 3).abs();
    assert_eq!(dist, 1, "landed adjacent to the rival castle");
}

#[test]
fn event_tempo_doubles_and_halves_movement() {
    let mut fast = party_board();
    common(&mut fast, 0, 4, Right, Handedness::Left);
    fast.apply_tide_event(TideEvent::SpeedUp, 0);
    for _ in 0..11 {
        fast.tick_idle();
    }
    assert_eq!(fast.crabs()[0].tile, 4 * 7 + 1, "24/tick crosses in 11");

    let mut slow = party_board();
    common(&mut slow, 0, 4, Right, Handedness::Left);
    slow.apply_tide_event(TideEvent::SlowDown, 0);
    for _ in 0..42 {
        slow.tick_idle();
    }
    assert_eq!(slow.crabs()[0].tile, 4 * 7, "6/tick still mid-tile at 42");
    slow.tick_idle();
    assert_eq!(slow.crabs()[0].tile, 4 * 7 + 1);
}

#[test]
fn event_fresh_sand_washes_all_signposts() {
    let mut board = party_board();
    assert!(board.place_signpost(0, 3, 2, Up));
    assert!(board.place_signpost(1, 4, 2, Down));
    board.apply_tide_event(TideEvent::FreshSand, 0);
    assert_eq!(board.signpost_count(0) + board.signpost_count(1), 0);
}

#[test]
fn event_castle_swap_rotates_owners() {
    let mut board = party_board();
    board.apply_tide_event(TideEvent::CastleSwap, 0);
    assert_eq!(board.tile_at(1, 1), TileKind::Castle(1));
    assert_eq!(board.tile_at(5, 3), TileKind::Castle(0));
}

#[test]
fn event_timers_expire() {
    let mut board = party_board();
    board.apply_tide_event(TideEvent::SpeedUp, 0);
    common(&mut board, 0, 4, Right, Handedness::Left);
    for _ in 0..EVENT_TICKS + 1 {
        board.tick_idle();
    }
    // Back to normal speed: a fresh crab crosses in 22 ticks again.
    common(&mut board, 0, 2, Right, Handedness::Left);
    let start = board.crabs().last().unwrap().tile;
    for _ in 0..21 {
        board.tick_idle();
    }
    assert_eq!(board.crabs().last().unwrap().tile, start, "12/tick again");
}

#[test]
fn repointing_restarts_the_fade_clock() {
    let mut board = Board::new(5, 3, 0);
    assert!(board.place_signpost(0, 2, 1, Up));
    for _ in 0..200 {
        board.tick_idle();
    }
    assert!(board.place_signpost(0, 2, 1, Down), "re-point in place");
    for _ in 0..200 {
        board.tick_idle();
    }
    assert!(
        board.signpost_at(2, 1).is_some(),
        "clock restarted at re-point"
    );
    for _ in 0..SIGNPOST_LIFETIME {
        board.tick_idle();
    }
    assert!(board.signpost_at(2, 1).is_none());
}

#[test]
fn wrapped_flight_crosses_the_edge() {
    let mut board = Board::new(5, 1, 3);
    board.set_wrap(true);
    board.spawn_gull(4, 0, Right);
    board.gulls[0].takeoff_in = 0;
    board.gulls[0].dir = Right;
    for _ in 0..80 {
        board.tick_idle();
        if board.gulls[0].state == GullState::Walking {
            break;
        }
    }
    assert!(
        board.gulls[0].tile < 4,
        "flew across the open edge (tile {})",
        board.gulls[0].tile
    );
}

#[test]
fn castle_tier_boundaries() {
    for (score, tier) in [
        (0, 0),
        (9, 0),
        (10, 1),
        (24, 1),
        (25, 2),
        (49, 2),
        (50, 3),
        (5000, 3),
    ] {
        assert_eq!(castle_tier(score), tier, "score {score}");
    }
}

#[test]
fn surge_doubles_gull_spawn_rate() {
    // Surged board: surge covers remaining <= 900, i.e. from tick 100 on,
    // halving the period to 50 (spawns at 0, 100, 150, 200, 250 -> capped).
    let mut board = Board::new(7, 5, 3);
    board.set_gull_period(100);
    board.set_round_length(Some(1000));
    // Control at the normal rate.
    let mut calm = Board::new(7, 5, 3);
    calm.set_gull_period(100);
    for _ in 0..320 {
        board.tick_idle();
        calm.tick_idle();
    }
    assert_eq!(
        board.gulls().len(),
        GULL_CAP,
        "surged spawns hit the ambient flock cap"
    );
    assert_eq!(calm.gulls().len(), 4, "un-surged control spawns at period");
    // The cap holds from here on: no ambient spawn can exceed it.
    for _ in 0..300 {
        board.tick_idle();
    }
    assert!(board.gulls().len() <= GULL_CAP);
}

/// A board that raised its cap fills to the new one, and no further.
#[test]
fn a_raised_gull_cap_is_the_one_the_spawner_stops_at() {
    let mut board = Board::new(7, 5, 3);
    board.set_gull_period(10);
    board.set_gull_cap(9);
    for _ in 0..400 {
        board.tick_idle();
    }
    assert_eq!(board.gulls().len(), 9);
}

/// A full flock that turns over sends off its oldest gull clear of the
/// castles and lets a fresh one in; the bird beside a castle is somebody's
/// attack and stays. Without turnover the flock is left as it is.
#[test]
fn a_full_flock_turns_over_from_its_oldest_gull_clear_of_the_castles() {
    for turnover in [true, false] {
        let mut board = Board::new(9, 7, 3);
        board.set_tile(4, 3, TileKind::Castle(0));
        board.set_gull_period(10);
        board.set_gull_cap(3);
        board.set_gull_turnover(turnover);
        board.spawn_gull(4, 2, Left); // the oldest, beside the castle
        board.spawn_gull(8, 6, Up); // the oldest clear of it
        board.spawn_gull(0, 6, Up);
        board.run_gull_spawner();
        let ids: Vec<u32> = board.gulls().iter().map(|g| g.id).collect();
        if turnover {
            assert_eq!(ids.len(), 3, "one off, one on: {ids:?}");
            assert!(ids.contains(&0), "the attack stays: {ids:?}");
            assert!(!ids.contains(&1), "the oldest clear one left: {ids:?}");
            assert!(ids.contains(&2), "{ids:?}");
        } else {
            assert_eq!(ids, [0, 1, 2]);
        }
    }
}

/// The final rush raises a turning-over flock's cap by half, so its
/// doubled rate adds birds rather than only swapping them.
#[test]
fn the_final_rush_raises_a_turning_over_flocks_cap() {
    for turnover in [true, false] {
        let mut board = Board::new(9, 7, 3);
        board.set_tile(4, 3, TileKind::Castle(0));
        board.set_gull_period(10);
        board.set_gull_cap(2);
        board.set_gull_turnover(turnover);
        board.set_round_length(Some(600));
        assert!(board.in_surge());
        board.spawn_gull(8, 6, Up);
        board.spawn_gull(0, 6, Up);
        board.run_gull_spawner();
        let expected = if turnover { 3 } else { 2 };
        assert_eq!(board.gulls().len(), expected, "turnover {turnover}");
    }
}

/// A beach of two spawner holes that calls its golden crabs every
/// `every` ticks, and never runs out of time unless asked to.
fn calling_board(every: u32) -> Board {
    let mut board = Board::new(9, 7, 11);
    board.set_tile(1, 1, TileKind::Castle(0));
    for (x, y, dir) in [(0, 3, Right), (8, 3, Left)] {
        board.set_tile(x, y, TileKind::Spawner(Spawner { dir, period: 9 }));
    }
    board.set_golden_every(every);
    board
}

/// A calling board sends out one golden crab a stretch, from the hole it
/// called on the tick it called, worth the called value; it is told to
/// nobody until the notice, and the spawn mix never rolls one of its own.
#[test]
fn a_called_golden_crab_comes_out_where_and_when_it_was_called() {
    let every = 600u32;
    let mut board = calling_board(every);
    let mut goldens = Vec::new();
    let mut calls = Vec::new();
    let mut seen = std::collections::HashSet::new();
    while board.ticks() < 3 * u64::from(every) {
        if let Some(call) = board.golden_call() {
            assert!(
                call.0 - board.ticks() <= u64::from(GOLDEN_NOTICE),
                "told {} ticks early",
                call.0 - board.ticks()
            );
            if calls.last() != Some(&call) {
                calls.push(call);
            }
        }
        board.tick_idle();
        for crab in board.crabs() {
            if crab.kind == CrabKind::Golden && seen.insert(crab.id) {
                let (x, y) = board.coords_u8(crab.tile);
                goldens.push((board.ticks() - 1, x, y));
            }
        }
    }
    assert_eq!(goldens.len(), 3, "one a stretch: {goldens:?}");
    assert_eq!(goldens, calls, "out where and when it was called");
    for (k, (at, ..)) in goldens.iter().enumerate() {
        let into = at - k as u64 * u64::from(every);
        assert!(
            (200..400).contains(&into),
            "a third to two thirds in: {into}"
        );
    }
    assert_eq!(board.crab_value(CrabKind::Golden), GOLDEN_CALLED_VALUE);
    assert_eq!(calling_board(0).crab_value(CrabKind::Golden), 50);
}

/// No call is made for a tick the round will not reach.
#[test]
fn a_golden_crab_is_not_called_past_the_end_of_the_round() {
    let mut board = calling_board(600);
    board.set_round_length(Some(150));
    while !board.round_over() {
        board.tick_idle();
        assert_eq!(board.golden_call(), None);
    }
    assert!(board.crabs().iter().all(|c| c.kind != CrabKind::Golden));
}

/// A round saved mid-call, before the call is public, sends its golden
/// crab out exactly as the round it was saved from does.
#[test]
fn a_golden_call_survives_a_snapshot_before_it_is_public() {
    let mut board = calling_board(600);
    for _ in 0..50 {
        board.tick_idle();
    }
    assert_eq!(board.golden_call(), None, "not yet public");
    let mut back = Board::parse_snapshot(&board.to_snapshot()).expect("its own output");
    for _ in 0..600 {
        board.tick_idle();
        back.tick_idle();
        assert_eq!(back.state_hash(), board.state_hash());
    }
    assert!(board.crabs().iter().any(|c| c.kind == CrabKind::Golden) || board.golden_banked() > 0);
}

/// Tide events bypass the ambient flock cap on purpose: GullMania floods the
/// beach through the crab spawners.
#[test]
fn gull_mania_ignores_the_flock_cap() {
    let mut board = Board::new(9, 7, 5);
    board.set_tile(
        0,
        3,
        TileKind::Spawner(Spawner {
            dir: Right,
            period: 40,
        }),
    );
    board.set_events_enabled(true);
    board.apply_tide_event(TideEvent::GullMania, 0);
    for _ in 0..200 {
        board.tick_idle();
    }
    assert!(
        board.gulls().len() > GULL_CAP,
        "mania floods past the cap, got {}",
        board.gulls().len()
    );
}

/// Spec §3.4 says a raid halves the score "rounding the loss up": the
/// castle keeps `score / 2` and the odd crab goes with the gull. A score of
/// 7 keeps 3 and loses 4, all four spilling back onto the sand (under the
/// spill cap); 3 keeps 1 and spills 2. Pinned so a later "round to nearest"
/// cannot change how devastating a raid on a small castle is.
#[test]
fn a_raid_on_an_odd_score_rounds_the_loss_up_and_spills_it() {
    for (score, kept, spilled) in [(7, 3, 4), (3, 1, 2)] {
        let mut board = Board::new(7, 5, 0);
        board.set_tile(3, 2, TileKind::Castle(0));
        let castle = board.index_of(3, 2);
        board.scores[0] = score;
        board.damage_castle(0, castle);
        assert_eq!(board.scores()[0], kept, "{score} halves to {kept}");
        assert_eq!(
            board.crabs().len(),
            spilled,
            "{score}: the lost crabs spill"
        );
    }
}

/// A castle in a corner with a rock on its diagonal has only two open ring
/// tiles, fewer than the crabs a raid wants to spill. The spill takes what
/// sand there is and the flock carries the rest off: nothing spawns off the
/// board or on the rock, and the score still drops by the full half.
#[test]
fn a_spill_into_a_cramped_corner_lands_only_on_the_open_sand() {
    let mut board = Board::new(3, 3, 0);
    board.set_tile(0, 0, TileKind::Castle(0));
    board.set_tile(1, 1, TileKind::Rock);
    let castle = board.index_of(0, 0);
    board.scores[0] = 7;
    board.damage_castle(0, castle);
    assert_eq!(board.scores()[0], 3, "the loss is the full half regardless");
    let landed: Vec<(u8, u8)> = board
        .crabs()
        .iter()
        .map(|c| board.coords_u8(c.tile))
        .collect();
    assert_eq!(
        landed.len(),
        2,
        "only two ring tiles are open sand: {landed:?}"
    );
    for &(x, y) in &landed {
        assert!(x < 3 && y < 3, "spilled crab off the board at ({x},{y})");
        assert!(
            matches!((x, y), (1, 0) | (0, 1)),
            "spilled crab on the castle or the rock at ({x},{y})"
        );
    }
}

/// Where the ambient flock comes from: every spawn is on the edge of the
/// board and walks inward, and over enough rolls every edge tile gets its
/// turn. The perimeter arithmetic has four branches, and an off-by-one in
/// any of them skips tiles or indexes past the board.
#[test]
fn the_gull_spawner_covers_the_whole_perimeter_and_faces_inward() {
    let mut board = Board::new(4, 3, 7);
    board.set_gull_period(1);
    let mut hit = std::collections::BTreeSet::new();
    for _ in 0..400 {
        board.run_gull_spawner();
        let gull = board.gulls()[0];
        let (x, y) = board.coords(gull.tile);
        assert!(
            x == 0 || y == 0 || x == 3 || y == 2,
            "spawned inside the board at ({x},{y})"
        );
        let (dx, dy) = gull.dir.offset();
        assert!(
            board.in_bounds(x + dx, y + dy),
            "spawned at ({x},{y}) facing {:?}, off the board",
            gull.dir
        );
        hit.insert((x, y));
        board.gulls.clear();
    }
    assert_eq!(
        hit.len(),
        10,
        "every perimeter tile of a 4x3 board: {hit:?}"
    );
}

/// A one-wide or one-tall board is all perimeter, and the spawner's
/// `w * h` branch has to say so: every tile gets a gull eventually, and
/// none of the four edge branches names a tile the strip does not have.
/// There is no "inward" on a strip; the spawn's wall resolution turns the
/// gull along it, and that is asserted as "facing a tile that exists".
#[test]
fn the_gull_spawner_walks_the_length_of_a_strip() {
    for (w, h) in [(1u8, 5u8), (5, 1)] {
        let mut board = Board::new(w, h, 3);
        board.set_gull_period(1);
        let mut hit = std::collections::BTreeSet::new();
        for _ in 0..200 {
            board.run_gull_spawner();
            let gull = board.gulls()[0];
            let (x, y) = board.coords(gull.tile);
            let (dx, dy) = gull.dir.offset();
            assert!(
                board.in_bounds(x + dx, y + dy),
                "{w}x{h}: spawned at ({x},{y}) facing {:?}, off the board",
                gull.dir
            );
            hit.insert((x, y));
            board.gulls.clear();
        }
        assert_eq!(hit.len(), 5, "{w}x{h}: every tile of the strip: {hit:?}");
    }
}

/// A gull in flight, with its `remaining` hops given.
fn flying(board: &Board, x: u8, y: u8, dir: Direction, remaining: u8) -> Gull {
    let tile = board.index_of(x, y);
    Gull {
        id: 99,
        tile,
        dir,
        progress: 0,
        prev: Pose {
            tile,
            dir,
            progress: 0,
        },
        handed: Handedness::Left,
        state: GullState::Flying { remaining },
        takeoff_in: 0,
    }
}

/// Spec §3.5: a flying gull bounces off the board edge and lands only on a
/// tile a creature can stand on. On a 4x1 strip with rocks on the far two
/// tiles, a gull flying right with two hops left runs out over the rocks,
/// glides one more tile, hits the edge, turns back and puts down on the
/// first sand it finds. It has to end walking, on sand, in a bounded
/// number of ticks.
#[test]
fn a_flying_gull_bounces_off_the_edge_and_lands_on_sand() {
    let mut board = Board::new(4, 1, 0);
    board.set_tile(2, 0, TileKind::Rock);
    board.set_tile(3, 0, TileKind::Rock);
    let gull = flying(&board, 0, 0, Right, 2);
    board.gulls.push(gull);
    // Five hops (1, 2, 3, back to 2, back to 1) at one tile per 16 ticks.
    let hops = 5 * ticks_to_cross(1, u32::from(GULL_FLY_SPEED));
    for _ in 0..hops {
        board.tick_idle();
        if board.gulls()[0].state == GullState::Walking {
            break;
        }
    }
    let gull = board.gulls()[0];
    assert_eq!(
        gull.state,
        GullState::Walking,
        "still airborne after {hops} ticks"
    );
    let (x, y) = board.coords_u8(gull.tile);
    assert_eq!(board.tile_at(x, y), TileKind::Empty, "landed on a rock");
    assert_eq!((x, y), (1, 0), "the first sand on the way back");
    assert!(gull.takeoff_in > 0, "a fresh takeoff timer on landing");
}

/// The one-tile board: a gull that takes off has nowhere to fly, forward
/// or back, and has to land where it stands rather than hop off the edge
/// into a tile that does not exist.
#[test]
fn a_gull_on_a_one_tile_board_has_nowhere_to_fly_and_lands_where_it_is() {
    let mut board = Board::new(1, 1, 0);
    let gull = flying(&board, 0, 0, Right, 3);
    board.gulls.push(gull);
    for _ in 0..ticks_to_cross(1, u32::from(GULL_FLY_SPEED)) {
        board.tick_idle();
    }
    let gull = board.gulls()[0];
    assert_eq!(gull.state, GullState::Walking, "landed on the only tile");
    assert_eq!(gull.tile, 0);
    assert!(gull.takeoff_in > 0, "a fresh takeoff timer on landing");
}

/// The bot's cursor anchor: a player's newest post is the one with the
/// highest sequence number, and re-pointing a post in place takes a fresh
/// number. Evicting the oldest at the cap and a rival's posts must both
/// leave the answer alone, or a bot pays for a walk it never made.
#[test]
fn the_newest_signpost_is_by_sequence_and_ignores_rivals_and_evictions() {
    let mut board = Board::new(6, 6, 0);
    assert_eq!(board.newest_signpost_of(0), None, "nothing placed yet");
    assert!(board.place_signpost(0, 1, 1, Right));
    board.tick_idle();
    assert!(board.place_signpost(0, 2, 2, Right));
    assert_eq!(board.newest_signpost_of(0), Some((2, 2, 1)));
    // Re-pointing the first post makes it the newest again, stamped now.
    board.tick_idle();
    assert!(board.place_signpost(0, 1, 1, Down));
    assert_eq!(board.newest_signpost_of(0), Some((1, 1, 2)));
    // A rival's post, however fresh, is not this player's.
    board.tick_idle();
    assert!(board.place_signpost(1, 4, 4, Left));
    assert_eq!(board.newest_signpost_of(0), Some((1, 1, 2)));
    assert_eq!(board.newest_signpost_of(1), Some((4, 4, 3)));
    // A third fills the cap; a fourth evicts the oldest, which is (2, 2)
    // now that (1, 1) was re-pointed, and the fourth is the newest.
    assert!(board.place_signpost(0, 3, 3, Up));
    assert!(board.place_signpost(0, 5, 5, Up));
    assert!(board.signpost_at(2, 2).is_none(), "the oldest was evicted");
    assert!(
        board.signpost_at(1, 1).is_some(),
        "the re-pointed post survived"
    );
    assert_eq!(board.newest_signpost_of(0), Some((5, 5, 3)));
    // Losing a rival's post changes nothing for this player.
    assert!(board.remove_signpost(1, 4, 4));
    assert_eq!(board.newest_signpost_of(0), Some((5, 5, 3)));
    assert_eq!(board.newest_signpost_of(1), None);
}