pinch-points 0.9.0

A fast, kid-friendly crab-routing game: route streams of crabs into your sandcastle before time runs out
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
//! The single sim observer: diffs the headless simulation once per frame
//! and broadcasts everything that happened as [`SimEvent`] messages. Audio,
//! effects, and any future consumer read the same stream instead of each
//! re-deriving events from board state.

use crate::app::{Sim, layout};
use crate::sim::{
    Crab, CrabKind, Direction, GullState, Handedness, IncomingGull, MAX_PLAYERS, PlayerId,
    TideEvent, TileKind, castle_tier,
};
use bevy::platform::collections::HashMap;
use bevy::prelude::*;

/// Something observable happened in the sim since the last frame.
#[derive(Message, Clone, Debug)]
pub enum SimEvent {
    /// A crab walked into a castle. `points` is what that did to its
    /// owner's score: the kind's worth, or under a Right Claws call twice
    /// that for a right claw and that much taken away for a left one.
    ///
    /// `pos` is where the crab was last drawn and `keep` the middle of the
    /// wall it stepped through. Both, because the render layer walks it
    /// from one to the other, and the keep cannot be worked out later:
    /// these events are read a frame after they are observed (see the
    /// `Frame` sets), and a `CastleSwap` landing in that gap would send
    /// the crab to whichever castle its owner holds *now* - typically on
    /// the far side of the beach, into a keep it never touched.
    ///
    /// `id` is the crab's, so it can be drawn in the shell it walked in
    /// with rather than its kind's flat colour.
    CrabBanked {
        id: u32,
        owner: PlayerId,
        pos: Vec2,
        keep: Vec2,
        points: i32,
        kind: CrabKind,
        /// Which side its big claw is on, so the crab that hops into the
        /// keep is the crab that walked there.
        handed: Handedness,
    },
    /// The gulls got one.
    CrabEaten { pos: Vec2 },
    /// A crab appeared from a spawner hole.
    CrabSpawned { pos: Vec2 },
    /// A gull raided `owner`'s castle for `lost` banked crabs. `by` is
    /// the seat whose arrow last turned it (`owner` itself when a player
    /// walked a gull home), `None` for a wild gull no arrow turned.
    CastleRaided {
        owner: PlayerId,
        pos: Vec2,
        lost: u32,
        by: Option<PlayerId>,
    },
    /// The edge spawner sent for a gull: it lands on `tile`, facing `dir`,
    /// on tick `at` (see [`IncomingGull`]). Its own event,
    /// ahead of [`SimEvent::GullArrived`], because the whole point of the
    /// lead is that the beach hears of the bird before it is on the sand.
    GullIncoming {
        tile: (u8, u8),
        dir: Direction,
        at: u64,
    },
    /// A new gull walked onto the beach.
    GullArrived,
    /// A walking gull took to the air.
    GullTookOff,
    /// A flying gull touched down here.
    GullLanded { pos: Vec2 },
    /// A gull reached a castle on a beach without raids and was sent
    /// packing: it leaves the beach, as a raider does, and takes nothing.
    ///
    /// A puzzle's castles cannot be robbed, but reaching one still takes
    /// the gull off the sand (see `Rules::castle_raids` for why that is
    /// load-bearing). Drawn as nothing, the bird walked into the keep and
    /// vanished, which is exactly what a raid looks like in versus, and
    /// players read their puzzle as lost. `pos` is where it was last
    /// drawn, `castle` the middle of the tile that turned it away.
    GullShooed { pos: Vec2, castle: Vec2 },
    /// A gull left a full flock to make room for a fresh one, from `pos`,
    /// where it was last drawn (see `Rules::gull_turnover`). Drawn taking
    /// off, or it blinked out of existence mid-step.
    GullFlewOff { pos: Vec2 },
    /// A signpost went up here, and whose it is.
    ///
    /// One per tile, never a headcount: a board-wide count nets one seat's
    /// placement against another's removal and falls silent for both.
    ///
    /// It carries the owner so a listener can ask whether the post was one
    /// of *its* player's: on a six-seat beach the bots place far more often
    /// than the people do, and a knock for each is a click track running
    /// under the whole match.
    SignpostPlaced { owner: PlayerId, pos: Vec2 },
    /// A signpost left this tile and took its owner's count down with it:
    /// they pulled it, or it wore out. [`SimEvent::SignpostEvicted`] is the
    /// one departure that does not.
    ///
    /// Carries the owner for the same reason [`SimEvent::SignpostPlaced`]
    /// does: in versus every post wears out on its own, so silencing the
    /// placement alone leaves the click track running at nearly its old
    /// rate.
    SignpostRemoved { owner: PlayerId, pos: Vec2 },
    /// A signpost was pushed off the board to make room for a newer one:
    /// `owner` was at the cap under [`crate::sim::CapPolicy::Evict`] and
    /// placed anyway, so their oldest went. `pos` is where it stood.
    ///
    /// The versus rule, never the campaign's, which refuses
    /// the placement instead. The one way a player loses a signpost by
    /// their own hand without asking to.
    SignpostEvicted {
        owner: PlayerId,
        pos: Vec2,
        dir: Direction,
    },
    /// `owner`'s castle rose a tier.
    TierUp { owner: PlayerId },
    /// The tide roulette fired this event. `by` is the seat whose
    /// sparkling crab spun it, `None` for one the spectators called.
    TideEventFired {
        event: TideEvent,
        by: Option<PlayerId>,
    },
    /// `owner` banked a sparkling crab and the event wheel did not spin: a
    /// timed event was still running (`Rules::timed_lock`), or on an older
    /// board any event at all was. Its own event because nothing on the
    /// beach shows it, and a spin that silently did not happen reads as a
    /// bug.
    WheelLocked { owner: PlayerId },
    /// `owner` banked a molting crab and a lure began: every loose crab
    /// runs for their castle. Not every molt banked starts one (never
    /// during a lure or the quiet spell after), so it is its own event
    /// rather than read off `CrabBanked`, which named a lure for each.
    LureStarted { owner: PlayerId },
    /// `owner` banked a molting crab and no lure began
    /// (`Board::lure_ready` was false): `running` when a lure was still on,
    /// otherwise the quiet spell after one. Its own event for the same
    /// reason as [`SimEvent::WheelLocked`]: the molt banks for its points
    /// and nothing on the beach says why the crabs did not come running.
    LureRefused { owner: PlayerId, running: bool },
    /// The final-scramble surge began.
    SurgeStarted,
    /// A golden crab was called: it comes out of the spawner hole at `pos`
    /// in a few seconds (`Board::golden_call`).
    GoldenCalled { pos: Vec2 },
    /// A golden crab came out of the spawner hole at `pos`: the called
    /// one's arrival, or one the spawn mix rolled on a board that does
    /// not call them.
    GoldenOut { pos: Vec2 },
    /// The round timer expired.
    RoundEnded,
}

/// What a board looks like before its clock has run: the terrain and the
/// creatures it started with. Two boards both at tick 0 are told apart by
/// this rather than by the clock, which reads the same on both.
///
/// Signposts and scores are deliberately left out. A puzzle's Setup phase
/// never ticks, and placing a signpost there must still read as a change
/// to *this* board (it plays the placement sound), not as a swap.
#[derive(PartialEq, Debug)]
struct Origin {
    width: u8,
    height: u8,
    seed: u64,
    tiles: Vec<TileKind>,
    crabs: Vec<(u32, u16, Direction, CrabKind)>,
    gulls: Vec<(u32, u16)>,
}

impl Origin {
    /// Only boards at tick 0 need an identity; a ticked board's clock
    /// already tells it apart from whatever comes next.
    fn of(board: &crate::sim::Board) -> Option<Origin> {
        (board.ticks() == 0).then(|| Origin {
            width: board.width(),
            height: board.height(),
            seed: board.seed(),
            tiles: board.tiles().map(|(_, _, kind)| kind).collect(),
            crabs: board
                .crabs()
                .iter()
                .map(|c| (c.id, c.tile, c.dir, c.kind))
                .collect(),
            gulls: board.gulls().iter().map(|g| (g.id, g.tile)).collect(),
        })
    }
}

/// Which board is on the table, as far as telling one board from the next
/// goes: its clock, its beach, and before the clock has run its origin.
///
/// The one rule for "is this a different board", asked by the sim
/// observer and, through [`BoardGeneration`], by every drawing that keeps
/// a memory of the last frame's board.
#[derive(Default)]
pub struct BoardIdentity {
    ticks: u64,
    /// The beach itself, by size and seed: what tells a round picked back
    /// up from a pasted code, which arrives mid-clock, from the board this
    /// was last read from. The clock alone cannot, when the pasted round
    /// is further along than the board before it was.
    beach: (u8, u8, u64),
    origin: Option<Origin>,
}

impl BoardIdentity {
    fn of(board: &crate::sim::Board) -> BoardIdentity {
        BoardIdentity {
            ticks: board.ticks(),
            beach: (board.width(), board.height(), board.seed()),
            origin: Origin::of(board),
        }
    }

    /// Whether `next` was read off a different board from this one.
    ///
    /// A board swap usually rolls the tick clock back. A round picked up
    /// from a pasted code can be further along than the last board, and is
    /// told apart by its beach. Between two boards that have never ticked
    /// (a puzzle's Setup phase, skipping levels from there, an editor
    /// resize) the clock reads 0 on both sides, so those are told apart by
    /// their origin instead: same clock, different board.
    fn is_new(&self, next: &BoardIdentity) -> bool {
        let Self {
            ticks,
            beach,
            origin,
        } = self;
        next.ticks < *ticks || next.beach != *beach || (next.ticks == 0 && next.origin != *origin)
    }
}

/// A count of the boards the table has held, one up every time the board
/// on it is a different one (by [`BoardIdentity`]).
///
/// What a drawing with a memory of the last frame keys its reset on: the
/// castle swap detector, the gull arrivals, the gulls' flights. Each kept
/// its own guess before (the clock running backwards), which missed a
/// round pasted in mid-clock, and flew castles across the beach, puffed
/// sand under every gull on it, and handed recycled gull ids the last
/// board's descents.
///
/// Published by [`track_board`] at the top of the render pass, so every
/// drawing in the frame reads the same answer for the board it draws.
#[derive(Resource, Default)]
pub struct BoardGeneration {
    identity: BoardIdentity,
    generation: u64,
}

impl BoardGeneration {
    /// The current board's number. Only ever compared for equality with a
    /// number read earlier: different means a different board.
    pub fn get(&self) -> u64 {
        self.generation
    }

    /// Read `board`, counting it as a new board if it is one.
    fn observe(&mut self, board: &crate::sim::Board) {
        let next = BoardIdentity::of(board);
        if self.identity.is_new(&next) {
            self.generation += 1;
        }
        self.identity = next;
    }

    /// Count `board` as a new board whatever it reads like: it has just
    /// been laid out on a fresh stage, every sprite rebuilt.
    ///
    /// The identity rule alone cannot see one case of that. A watcher who
    /// lost the thread of a round is handed the round as it stands
    /// (`take_catch_up_part`) and the arena is built again from it: the
    /// same beach, its clock further along, which reads as the old board
    /// ticking on. Taken for that, every crab that walked in the gap was
    /// a bank or a death on the first frame, and the drawings carried
    /// their memories of the frozen frame onto the new one.
    pub fn laid_out(&mut self, board: &crate::sim::Board) {
        self.generation += 1;
        self.identity = BoardIdentity::of(board);
    }
}

/// The board on the table, and which board it is: what a drawing that
/// remembers last frame's board reads, so it can tell a new board from
/// the old one ticking on.
#[derive(bevy::ecs::system::SystemParam)]
pub struct CurrentBoard<'w> {
    pub sim: Res<'w, Sim>,
    pub generation: Res<'w, BoardGeneration>,
}

impl CurrentBoard<'_> {
    /// The board's [`BoardGeneration`] number.
    pub fn generation(&self) -> u64 {
        self.generation.get()
    }
}

/// Which board (by [`BoardGeneration`]) a drawing last read, so it can
/// tell a new board from the old one ticking on. Empty until the first
/// read, which is always of a new board.
#[derive(Default)]
pub struct BoardStamp(Option<u64>);

impl BoardStamp {
    /// Whether the board on the table is another than the one last read,
    /// stamping it as read either way.
    pub fn is_new(&mut self, current: &CurrentBoard) -> bool {
        let generation = Some(current.generation());
        let new = self.0 != generation;
        self.0 = generation;
        new
    }
}

/// A memory kept per creature id, and the board it was filled on.
///
/// Crab and gull ids start again at zero on every board, so a memory
/// pruned by id alone hands a new board's crab the last board's entry: a
/// crab that was on dry sand there and starts in a pool here splashes on
/// its first frame, and one that starts across the beach from where its
/// namesake stood presses a footprint halfway between.
pub struct BoardMemory<K, V> {
    filled_on: BoardStamp,
    by_id: HashMap<K, V>,
}

impl<K, V> Default for BoardMemory<K, V> {
    fn default() -> Self {
        BoardMemory {
            filled_on: BoardStamp::default(),
            by_id: Default::default(),
        }
    }
}

impl<K, V> BoardMemory<K, V> {
    /// The memory for the board on the table: emptied first if it was
    /// filled on another one.
    pub fn of(&mut self, current: &CurrentBoard) -> &mut HashMap<K, V> {
        let Self { filled_on, by_id } = self;
        if filled_on.is_new(current) {
            by_id.clear();
        }
        by_id
    }
}

/// Keep [`BoardGeneration`] up with the board on the table.
pub fn track_board(sim: Res<Sim>, mut generation: ResMut<BoardGeneration>) {
    // An untouched sim is the board last read, and reading one at tick 0
    // copies its terrain.
    if !sim.is_changed() {
        return;
    }
    generation.observe(&sim.0);
}

/// Last-seen sim facts for the diff.
#[derive(Default)]
pub struct Watch {
    identity: BoardIdentity,
    scores: [u32; MAX_PLAYERS],
    tiers: [u8; MAX_PLAYERS],
    /// Per seat, never a board-wide sum: an eviction leaves its owner's
    /// count where it was, and a sum cannot even see whose post moved.
    posts_by: [usize; MAX_PLAYERS],
    /// Which seat holds the signpost on each occupied tile, and which way
    /// it points. Only the seat decides whether a tile lost its post, since
    /// re-pointing one in place keeps the seat and changes the direction;
    /// the direction is kept to draw the ghost of a post already gone.
    posts_at: HashMap<(u8, u8), (PlayerId, Direction)>,
    /// What each seat's steered gulls have taken from each castle, as
    /// `stolen[steerer][victim]` ([`crate::sim::Board::stolen`]): the
    /// growth of a victim's column names who steered the raid on it.
    stolen: [[u32; MAX_PLAYERS]; MAX_PLAYERS],
    /// The most recent tide event and the tick it fired on.
    tide_event: Option<(TideEvent, u64)>,
    spun_by: Option<PlayerId>,
    lure: Option<PlayerId>,
    /// Whether a Right Claws call was on, which decides what a crab banked
    /// before the next look was worth.
    claw: bool,
    surging: bool,
    /// The golden crab called and announced, as its tick and hole.
    golden_call: Option<(u64, u8, u8)>,
    over: bool,
    /// Every crab in play, the ones Crab Monopoly is carrying home too.
    crabs: HashMap<u32, Crab>,
    /// Which of `crabs` were in the air, flown home by the drawing: one
    /// that is gone next has landed in its keep, and is told as banking
    /// there rather than where it was picked up.
    in_flight: std::collections::HashSet<u32>,
    /// Every gull on the beach, by id: by its keys which gulls were
    /// already here, for the one that is new.
    gulls: HashMap<u32, SeenGull>,
    /// The gulls on their way in, for the one newly sent for.
    incoming: Vec<IncomingGull>,
}

/// One gull as the last look saw it.
#[derive(Clone, Copy)]
struct SeenGull {
    /// Where it was drawn, for the one that is gone next frame.
    at: Vec2,
    /// Whether it was in the air: one that was and now is not has just
    /// landed.
    aloft: bool,
}

impl Watch {
    /// The tide event fired since `prev`, if one did.
    fn fired_since(&self, prev: &Watch) -> Option<TideEvent> {
        let (event, at) = self.tide_event?;
        (prev.tide_event.map(|(_, then)| then) != Some(at)).then_some(event)
    }

    /// How many gulls were in the air.
    fn flying(&self) -> usize {
        self.gulls.values().filter(|gull| gull.aloft).count()
    }
}

impl Watch {
    /// Read every fact the differ compares, in one place. Built whole and
    /// assigned whole, so a new field cannot be compared-but-never-stored.
    fn of(board: &crate::sim::Board) -> Watch {
        let mut tiers = [0u8; MAX_PLAYERS];
        for (tier, &score) in tiers.iter_mut().zip(board.scores().iter()) {
            *tier = castle_tier(score);
        }
        Watch {
            identity: BoardIdentity::of(board),
            scores: *board.scores(),
            tiers,
            posts_by: std::array::from_fn(|p| board.signpost_count(p as PlayerId)),
            posts_at: board
                .tiles()
                .filter_map(|(x, y, _)| {
                    let sp = board.signpost_at(x, y)?;
                    Some(((x, y), (sp.owner, sp.dir)))
                })
                .collect(),
            stolen: std::array::from_fn(|by| {
                std::array::from_fn(|victim| board.stolen(by as PlayerId, victim as PlayerId))
            }),
            tide_event: board.last_event(),
            spun_by: board.event_spun_by(),
            lure: board.lure().map(|(owner, _)| owner),
            claw: board.in_claw_call(),
            surging: board.in_surge(),
            golden_call: board.golden_call(),
            over: board.round_over(),
            crabs: board
                .crabs()
                .iter()
                .chain(board.sweeping().iter().map(|flight| &flight.crab))
                .map(|c| (c.id, *c))
                .collect(),
            in_flight: board.sweeping().iter().map(|f| f.crab.id).collect(),
            gulls: board
                .gulls()
                .iter()
                .map(|g| {
                    let seen = SeenGull {
                        at: layout::creature_pos(board, g.tile, g.dir, g.progress),
                        aloft: matches!(g.state, GullState::Flying { .. }),
                    };
                    (g.id, seen)
                })
                .collect(),
            incoming: board.incoming_gulls().to_vec(),
        }
    }
}

/// What each seat's banks in this look did to its score, with every
/// cost cut to what the score had to give: the sim keeps a score at zero
/// rather than below (`Board::credit_bank`), so a left claw banked on three
/// points takes three, and its float and feed line say so rather than the
/// crab's full price. Gains are counted first, the order within a look
/// being unknown and a cost never the larger for it.
fn settle_banks(before: &[u32; MAX_PLAYERS], events: &mut [SimEvent]) -> [i64; MAX_PLAYERS] {
    let mut banked = [0i64; MAX_PLAYERS];
    for event in events.iter() {
        if let SimEvent::CrabBanked { owner, points, .. } = event
            && *points > 0
        {
            banked[usize::from(*owner)] += i64::from(*points);
        }
    }
    for event in events.iter_mut() {
        if let SimEvent::CrabBanked { owner, points, .. } = event
            && *points < 0
        {
            let seat = usize::from(*owner);
            let left = i64::from(before[seat]) + banked[seat];
            let taken = i64::from(*points).max(-left);
            *points = taken as i32;
            banked[seat] += taken;
        }
    }
    banked
}

/// A crab left the board: it either reached a castle or a gull got it.
///
/// The sim does not say which, since a crab simply stops existing, so this
/// reads the tile it was on and the one it was walking into. Either being a
/// castle means it banked there; anything else means it was eaten. Getting
/// this wrong plays the wrong sound and the wrong particle burst on the
/// most-noticed moment in the game, so it has tests of its own.
///
/// The exception is the one departure the tiles cannot explain. `Monopoly`
/// banks half the loose crabs where they stand, from open sand with no
/// castle at either end of the step, so the tiles alone call every one of
/// them a death. The sim writes those down as it makes them
/// ([`Board::swept_home`](crate::sim::Board::swept_home)), and they are
/// asked after first.
///
/// Both tile reads are bounds-checked rather than trusting the crab's
/// coordinates: `prev` was recorded on last frame's board, and should that
/// board have been larger than this one (a swap the differ failed to
/// notice) an asserting `tile_at` would take the game down at level start.
fn crab_departure(board: &crate::sim::Board, prev: &Crab, claw: bool) -> SimEvent {
    let pos = layout::creature_pos(board, prev.tile, prev.dir, prev.progress);
    let priced = || prev.bank_points(board.crab_value(prev.kind), claw);
    // The tide's own doing, which no tile records. Its keep is where the
    // crab is flown to, and a banker with no castle to fly it to is not a
    // thing the sim makes, so it reads as eaten if it ever happens.
    let swept = board
        .swept_home(prev.id)
        .and_then(|owner| Some((owner, board.castle_of(owner)?)));
    let (owner, keep, points) = match swept {
        // What the sim paid, not a second pricing off the clock: a crab in
        // flight banks under the call it was swept under.
        Some((owner, (kx, ky))) => (
            owner,
            layout::tile_center(board, kx, ky),
            board.swept_paid(prev.id).unwrap_or_else(priced),
        ),
        // What the sim banked and paid, never a guess off the map: a gull taking a
        // crab one tile short of a castle leaves it facing the castle, and
        // read off the tiles that was a bank, sound, points and all. The
        // castle's tile is also *where* the bank is, which nothing else
        // records once the crab is gone.
        None => match board.walked_home(prev.id) {
            Some((owner, tile, paid)) => {
                let (kx, ky) = board.coords_u8(tile);
                (owner, layout::tile_center(board, kx, ky), paid)
            }
            None => return SimEvent::CrabEaten { pos },
        },
    };
    SimEvent::CrabBanked {
        id: prev.id,
        owner,
        pos,
        keep,
        points,
        kind: prev.kind,
        handed: prev.handed,
    }
}

/// Crabs that left the board since the last frame, and crabs that arrived
/// out of a spawner hole.
fn crab_events(board: &crate::sim::Board, watch: &Watch, events: &mut Vec<SimEvent>) {
    for (id, prev) in watch.crabs.iter() {
        let in_play = board.crabs().iter().any(|crab| crab.id == *id)
            || board.sweeping().iter().any(|flight| flight.crab.id == *id);
        if in_play {
            continue;
        }
        let mut departure = crab_departure(board, prev, watch.claw);
        // Flown home already: it banks at the gate, not where it was
        // picked up, or the bank would fly it across the beach again.
        if watch.in_flight.contains(id)
            && let SimEvent::CrabBanked { pos, keep, .. } = &mut departure
        {
            *pos = *keep;
        }
        events.push(departure);
    }
    for crab in board.crabs() {
        if watch.crabs.contains_key(&crab.id) {
            continue;
        }
        let (x, y) = board.coords_u8(crab.tile);
        if matches!(board.tile_at(x, y), TileKind::Spawner(_)) {
            let pos = layout::creature_pos(board, crab.tile, crab.dir, crab.progress);
            events.push(SimEvent::CrabSpawned { pos });
            if crab.kind == CrabKind::Golden {
                events.push(SimEvent::GoldenOut { pos });
            }
        }
    }
}

/// Gulls that left the beach since the last frame, other than all at once
/// when Crab Mania clears the sky.
///
/// A gull leaves through a castle, which on a raid-free beach turns it
/// away, or, on a versus beach whose flock turns over, by flying off. The
/// sim records neither, so they are told apart by where the bird was last
/// drawn. It walks at most a tile a frame, and a flight that ends on a
/// castle ends on that tile, so one that went through a castle was last
/// drawn beside it; the sim only sends off a gull more than two tiles from
/// every castle. A raid is not news here: [`SimEvent::CastleRaided`] is.
fn gull_departures(
    board: &crate::sim::Board,
    prev: &Watch,
    next: &Watch,
    events: &mut Vec<SimEvent>,
) {
    if next.fired_since(prev) == Some(TideEvent::CrabMania) {
        return;
    }
    let castles: Vec<Vec2> = board
        .tiles()
        .filter(|(_, _, kind)| matches!(kind, TileKind::Castle(_)))
        .map(|(x, y, _)| layout::tile_center(board, x, y))
        .collect();
    for (id, gull) in &prev.gulls {
        if next.gulls.contains_key(id) {
            continue;
        }
        let pos = gull.at;
        let nearest = castles
            .iter()
            .copied()
            .min_by(|a, b| a.distance_squared(pos).total_cmp(&b.distance_squared(pos)));
        let Some(castle) = nearest else {
            continue;
        };
        if castle.distance(pos) > layout::TILE * 1.5 {
            events.push(SimEvent::GullFlewOff { pos });
        } else if !board.rules().castle_raids {
            events.push(SimEvent::GullShooed { pos, castle });
        }
    }
}

/// Diff the sim against the last frame and emit one message per happening.
/// A board swap (a fresh level or round, or one pasted in mid-clock, as
/// [`BoardIdentity::is_new`] tells them) resyncs silently so loading never
/// fires a burst of stale events.
pub fn observe_sim(
    sim: Res<Sim>,
    generation: Res<BoardGeneration>,
    mut watch: Local<Watch>,
    mut read_on: Local<Option<u64>>,
    mut events: MessageWriter<SimEvent>,
) {
    // A board counted new by [`BoardGeneration`] is read afresh, nothing
    // on it news. Its own identity rule would agree about most of them,
    // but not a board laid out again further along the same round (see
    // [`BoardGeneration::laid_out`]).
    if *read_on != Some(generation.get()) {
        *read_on = Some(generation.get());
        *watch = Watch::of(&sim.0);
        return;
    }
    // An untouched sim is the board the watch was read from, so the diff
    // would find nothing. Reading one costs every tile, both creature
    // maps, and on an unticked board a copy of the terrain; a puzzle in
    // Setup and the editor never tick at all.
    if !sim.is_changed() {
        return;
    }
    for event in diff(&sim.0, &mut watch) {
        events.write(event);
    }
}

/// The pure diff-and-resync core of [`observe_sim`], separated so the
/// bank-vs-eaten classification and the reset silence are testable
/// without a Bevy runtime. Mutates `watch` to the board's current facts
/// and returns everything that happened since the last call.
pub fn diff(board: &crate::sim::Board, watch: &mut Watch) -> Vec<SimEvent> {
    let next = Watch::of(board);
    // Everything the old board was doing is not news about a new one.
    let swapped = watch.identity.is_new(&next.identity);
    let events = if swapped {
        Vec::new()
    } else {
        changes(board, watch, &next)
    };
    *watch = next;
    events
}

/// Who steered the raid on `victim` between two looks: the seat whose
/// steered gulls' take from that castle grew the most, or nobody when it
/// did not grow (a wild gull). Two raids on one castle inside one look
/// are one line, and it names the bigger thief.
fn raider(prev: &Watch, next: &Watch, victim: usize) -> Option<PlayerId> {
    (0..MAX_PLAYERS)
        .map(|by| {
            (
                by,
                next.stolen[by][victim].saturating_sub(prev.stolen[by][victim]),
            )
        })
        .filter(|&(_, took)| took > 0)
        .max_by_key(|&(by, took)| (took, std::cmp::Reverse(by)))
        .map(|(by, _)| by as PlayerId)
}

/// What changed between two readings of the same board.
fn changes(board: &crate::sim::Board, prev: &Watch, next: &Watch) -> Vec<SimEvent> {
    let mut events = Vec::new();
    crab_events(board, prev, &mut events);
    let banked = settle_banks(&prev.scores, &mut events);

    // Raids: a score below what this look's banks leave it at, located at
    // that player's castle. Not any drop: a left claw banked under a Right
    // Claws call takes points too, and read as a raid it played the raid's
    // sound, rumble and feed line, and counted toward both raid trophies.
    for (seat, (&now, &before)) in next.scores.iter().zip(prev.scores.iter()).enumerate() {
        let expected = (i64::from(before) + banked[seat]).max(0);
        if i64::from(now) >= expected {
            continue;
        }
        if let Some((x, y)) = board.castle_of(seat as PlayerId) {
            events.push(SimEvent::CastleRaided {
                owner: seat as PlayerId,
                pos: layout::tile_center(board, x, y),
                lost: (expected - i64::from(now)) as u32,
                by: raider(prev, next, seat),
            });
        }
    }

    // Arrivals by id, never by headcount: a full flock turning over sends
    // one gull off and brings one on in the same tick, and a raider can
    // leave on the tick another lands, so the count holds and the new
    // bird came in without a screech or a feed line.
    for gull in &next.incoming {
        if !prev.incoming.contains(gull) {
            events.push(SimEvent::GullIncoming {
                tile: board.coords_u8(gull.tile),
                dir: gull.dir,
                at: gull.at,
            });
        }
    }
    if next.gulls.keys().any(|id| !prev.gulls.contains_key(id)) {
        events.push(SimEvent::GullArrived);
    }
    if next.flying() > prev.flying() {
        events.push(SimEvent::GullTookOff);
    }
    for gull in board.gulls() {
        let now_flying = matches!(gull.state, GullState::Flying { .. });
        if prev.gulls.get(&gull.id).is_some_and(|seen| seen.aloft) && !now_flying {
            events.push(SimEvent::GullLanded {
                pos: layout::creature_pos(board, gull.tile, gull.dir, gull.progress),
            });
        }
    }

    gull_departures(board, prev, next, &mut events);

    // Signposts tile by tile, in both directions. A tile whose seat is the
    // same on both sides has not changed hands: re-pointing a post keeps
    // the seat and swings the direction, which is neither.
    for (&(x, y), &(owner, _)) in &next.posts_at {
        if prev.posts_at.get(&(x, y)).is_some_and(|&(o, _)| o == owner) {
            continue;
        }
        events.push(SimEvent::SignpostPlaced {
            owner,
            pos: layout::tile_center(board, x, y),
        });
    }
    // An eviction is a signpost leaving a tile while its owner's count
    // holds: they were at the cap and placed a fourth, so the board took
    // their oldest in trade. Every other way one goes (expiry, the player
    // pulling it, a gull finishing it off) takes the count down with it.
    // Placing on a frame where one of yours also expired reads as an
    // eviction, and "one of yours just went, here" is true either way.
    for (&(x, y), &(owner, dir)) in &prev.posts_at {
        if next.posts_at.get(&(x, y)).is_some_and(|&(o, _)| o == owner) {
            continue;
        }
        let pos = layout::tile_center(board, x, y);
        events.push(
            if next.posts_by[owner as usize] < prev.posts_by[owner as usize] {
                SimEvent::SignpostRemoved { owner, pos }
            } else {
                SimEvent::SignpostEvicted { owner, pos, dir }
            },
        );
    }
    for (seat, (&now, &before)) in next.tiers.iter().zip(prev.tiers.iter()).enumerate() {
        if now > before {
            events.push(SimEvent::TierUp {
                owner: seat as PlayerId,
            });
        }
    }
    if let Some(event) = next.fired_since(prev) {
        events.push(SimEvent::TideEventFired {
            event,
            by: next.spun_by,
        });
    }
    // Read off the banks rather than the wheel, which keeps no record of a
    // spin it refused. A look that also fired an event is taken to have
    // spun for its sparkling crab: two banked in the same few ticks, one
    // of them refused, is not worth a line of its own.
    //
    // A crab the tide swept home is not asked about at all: the sim never
    // spins the wheel for one, on any rule. Flown home, it lands two
    // seconds or more after the Monopoly that took it, in a look with no
    // event, and read as a refusal it told the banker the wheel was on
    // cooldown when nothing had tried to spin it.
    let spun = events
        .iter()
        .any(|event| matches!(event, SimEvent::TideEventFired { .. }));
    if board.events_enabled() && !spun {
        let refused: Vec<PlayerId> = events
            .iter()
            .filter_map(|event| {
                let SimEvent::CrabBanked {
                    id,
                    owner,
                    kind: CrabKind::Sparkling,
                    ..
                } = event
                else {
                    return None;
                };
                board.swept_home(*id).is_none().then_some(*owner)
            })
            .collect();
        for owner in refused {
            events.push(SimEvent::WheelLocked { owner });
        }
    }
    if let Some(owner) = next.lure
        && prev.lure.is_none()
    {
        events.push(SimEvent::LureStarted { owner });
    }
    // Read off the board's record, written on the bank tick: a look can
    // span several ticks, and a lure that ended inside it leaves the end
    // state saying "quiet spell" for a molt banked while it still ran. A
    // molt that started a lure, or that the tide swept home, has no record.
    let refused: Vec<(PlayerId, bool)> = events
        .iter()
        .filter_map(|event| {
            let SimEvent::CrabBanked {
                id,
                owner,
                kind: CrabKind::Molting,
                ..
            } = event
            else {
                return None;
            };
            board.lure_refused(*id).map(|running| (*owner, running))
        })
        .collect();
    for (owner, running) in refused {
        events.push(SimEvent::LureRefused { owner, running });
    }
    if next.surging && !prev.surging {
        events.push(SimEvent::SurgeStarted);
    }
    if let Some((_, x, y)) = next.golden_call
        && next.golden_call != prev.golden_call
    {
        events.push(SimEvent::GoldenCalled {
            pos: layout::tile_center(board, x, y),
        });
    }
    if next.over && !prev.over {
        events.push(SimEvent::RoundEnded);
    }
    events
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sim::{Board, CrabKind, Direction, Handedness};

    fn synced(board: &Board) -> Watch {
        let mut watch = Watch::default();
        diff(board, &mut watch);
        watch
    }

    /// The raid's event names whose arrow steered the gull, read at any
    /// frame rate: a replay at speed folds many ticks into one look, and
    /// the credit is the board's own tally rather than a sighting of the
    /// gull on the arrow. A wild gull names nobody.
    #[test]
    fn a_raid_names_the_seat_that_steered_it() {
        for (arrow, every) in [(Some(0), 1), (Some(0), 40), (Some(1), 1), (None, 7)] {
            let mut board = Board::new(7, 5, 0);
            board.set_tile(4, 2, TileKind::Castle(1));
            board.set_tile(6, 4, TileKind::Castle(0));
            board.set_score(1, 30);
            if let Some(seat) = arrow {
                assert!(board.place_signpost(seat, 1, 2, Direction::Right));
            }
            board.spawn_gull(0, 2, Direction::Right);
            let mut watch = synced(&board);
            let mut raids = Vec::new();
            for tick in 1..=200 {
                board.tick_idle();
                if tick % every == 0 {
                    raids.extend(diff(&board, &mut watch).into_iter().filter_map(|e| {
                        let SimEvent::CastleRaided { owner, by, .. } = e else {
                            return None;
                        };
                        Some((owner, by))
                    }));
                }
            }
            assert_eq!(raids, [(1, arrow)], "{arrow:?} every {every}");
        }
    }

    /// A sweep's landing records outlast the most ticks one drawn frame can
    /// cover, or a bank read on the frame after a hitch, in a replay at its
    /// fastest, is drawn as a crab eaten. The worst frame: the fixed clock's
    /// most steps after a stall, each feeding the most ticks a step can.
    #[test]
    fn a_swept_crab_is_remembered_past_the_longest_frame() {
        use bevy::time::{Time, Virtual};
        let max_delta = Time::<Virtual>::default().max_delta().as_secs_f64();
        // One more for the overstep the clock carries into the frame.
        let steps = (max_delta * f64::from(crate::sim::TICKS_PER_SECOND)).ceil() as u64 + 1;
        let fastest = crate::app::replays::PlaybackSpeed::STEPS
            .iter()
            .copied()
            .max()
            .map_or(1, u64::from);
        let per_step = fastest.max(crate::app::net::CATCH_UP_FRAMES as u64);
        // With the margin `SWEEP_MEMORY` promises: half as many again.
        assert!(
            steps * per_step * 3 / 2 <= crate::sim::SWEEP_MEMORY,
            "{steps} steps of {per_step} ticks, and half again, outrun the landing records"
        );
    }

    /// What a bank is worth is what it did to the score: under a Right
    /// Claws call a left claw costs, and the castle's float and the feed
    /// read this rather than the crab's face value.
    #[test]
    fn a_bank_under_a_claw_call_carries_what_it_did() {
        // What the bank did, from a score of `start`, and whether anything
        // also read it as a raid.
        let bank_on = |start: u32| {
            let mut board = Board::new(6, 4, 7);
            board.set_tile(3, 1, TileKind::Castle(2));
            board.spawn_crab(2, 1, Direction::Right, Handedness::Left, CrabKind::Giant);
            board.force_tide_event(TideEvent::RightClaws, 0);
            board.set_score(2, start);
            let mut watch = synced(&board);
            for _ in 0..600 {
                board.tick_idle();
                let events = diff(&board, &mut watch);
                let raided = events
                    .iter()
                    .any(|e| matches!(e, SimEvent::CastleRaided { .. }));
                if let Some(SimEvent::CrabBanked { points, .. }) = events
                    .iter()
                    .find(|e| matches!(e, SimEvent::CrabBanked { .. }))
                {
                    return (*points, raided, board.scores()[2]);
                }
            }
            panic!("the crab never banked");
        };
        assert_eq!(bank_on(30), (-10, false, 20), "a left claw costs its worth");
        // The score stops at zero, and the bank says what it took.
        assert_eq!(bank_on(3), (-3, false, 0), "no more than there was");
    }

    /// A sparkling crab banked while the wheel is locked says so, naming
    /// whose it was; one that spins it says what it spun, and a board with
    /// no random events says nothing about the wheel at all.
    #[test]
    fn a_sparkling_crab_the_wheel_ignored_is_told() {
        // The wheel's events on the look the crab banked in.
        let bank_on = |events_on: bool, locked: bool| {
            let mut board = Board::new(6, 4, 7);
            board.set_events_enabled(events_on);
            board.rules_mut().timed_lock = true;
            board.set_tile(3, 1, TileKind::Castle(2));
            board.spawn_crab(
                2,
                1,
                Direction::Right,
                Handedness::Left,
                CrabKind::Sparkling,
            );
            if locked {
                board.force_tide_event(TideEvent::SlowDown, 0);
            }
            let mut watch = synced(&board);
            for _ in 0..600 {
                board.tick_idle();
                let events = diff(&board, &mut watch);
                if events
                    .iter()
                    .any(|e| matches!(e, SimEvent::CrabBanked { .. }))
                {
                    return events
                        .into_iter()
                        .filter(|e| {
                            matches!(
                                e,
                                SimEvent::WheelLocked { .. } | SimEvent::TideEventFired { .. }
                            )
                        })
                        .collect::<Vec<_>>();
                }
            }
            panic!("the crab never banked");
        };
        assert!(matches!(
            bank_on(true, true)[..],
            [SimEvent::WheelLocked { owner: 2 }]
        ));
        assert!(matches!(
            bank_on(true, false)[..],
            [SimEvent::TideEventFired { by: Some(2), .. }]
        ));
        assert!(bank_on(false, false).is_empty());
    }

    /// A molt banked with its lure not ready says so, naming whose it was
    /// and whether a lure was still on or resting; one that starts a lure
    /// says only that.
    #[test]
    fn a_molt_that_starts_no_lure_is_told() {
        // `before` ticks after a lure for seat 0 starts, a molt walks into
        // seat 2's castle; what the look it banked in says of lures.
        let bank_after = |before: Option<u32>| {
            let mut board = Board::new(6, 4, 7);
            board.set_tile(3, 1, TileKind::Castle(2));
            if let Some(before) = before {
                board.force_lure(0);
                for _ in 0..before {
                    board.tick_idle();
                }
            }
            board.spawn_crab(2, 1, Direction::Right, Handedness::Left, CrabKind::Molting);
            let mut watch = synced(&board);
            for _ in 0..600 {
                board.tick_idle();
                let events = diff(&board, &mut watch);
                if events
                    .iter()
                    .any(|e| matches!(e, SimEvent::CrabBanked { .. }))
                {
                    return events
                        .into_iter()
                        .filter(|e| {
                            matches!(
                                e,
                                SimEvent::LureRefused { .. } | SimEvent::LureStarted { .. }
                            )
                        })
                        .collect::<Vec<_>>();
                }
            }
            panic!("the crab never banked");
        };
        assert!(matches!(
            bank_after(None)[..],
            [SimEvent::LureStarted { owner: 2 }]
        ));
        assert!(matches!(
            bank_after(Some(0))[..],
            [SimEvent::LureRefused {
                owner: 2,
                running: true
            }]
        ));
        assert!(matches!(
            bank_after(Some(crate::sim::LURE_TICKS))[..],
            [SimEvent::LureRefused {
                owner: 2,
                running: false
            }]
        ));
    }

    /// Whether a lure was on is read at the tick the molt banked, not at
    /// the end of the look: one look spanning a molt banked mid-lure and
    /// the lure's end still says the lure was running.
    #[test]
    fn a_molt_refused_mid_lure_says_running_across_a_long_look() {
        let mut board = Board::new(6, 4, 7);
        board.set_tile(3, 1, TileKind::Castle(2));
        // How long the molt takes to bank, so it can be sent in near the
        // lure's end and the look stays as short as a slow frame's.
        let mut probe = board.clone();
        probe.spawn_crab(2, 1, Direction::Right, Handedness::Left, CrabKind::Molting);
        let mut walk = 0;
        while probe.crabs_banked() == 0 {
            probe.tick_idle();
            walk += 1;
        }
        board.force_lure(0);
        while board.lure().is_some_and(|(_, left)| left > walk + 4) {
            board.tick_idle();
        }
        board.spawn_crab(2, 1, Direction::Right, Handedness::Left, CrabKind::Molting);
        let mut watch = synced(&board);
        while board.crabs_banked() == 0 {
            board.tick_idle();
        }
        assert!(board.lure().is_some(), "banked while the lure ran");
        while board.lure().is_some() {
            board.tick_idle();
        }
        let refused: Vec<_> = diff(&board, &mut watch)
            .into_iter()
            .filter(|e| matches!(e, SimEvent::LureRefused { .. }))
            .collect();
        assert!(
            matches!(
                refused[..],
                [SimEvent::LureRefused {
                    owner: 2,
                    running: true
                }]
            ),
            "{refused:?}"
        );
    }

    /// A lure is news once, when it begins, and says whose it is; a tide
    /// event called rather than spun names nobody as its spinner.
    #[test]
    fn a_lure_is_told_once_and_a_called_event_names_no_spinner() {
        let mut board = Board::new(6, 4, 7);
        let mut watch = synced(&board);
        board.force_lure(1);
        board.force_tide_event(TideEvent::SpeedUp, 0);
        let events = diff(&board, &mut watch);
        assert!(
            events
                .iter()
                .any(|e| matches!(e, SimEvent::LureStarted { owner: 1 })),
            "{events:?}"
        );
        assert!(events.iter().any(|e| matches!(
            e,
            SimEvent::TideEventFired {
                event: TideEvent::SpeedUp,
                by: None,
            }
        )));
        board.tick_idle();
        let again = diff(&board, &mut watch);
        assert!(
            !again
                .iter()
                .any(|e| matches!(e, SimEvent::LureStarted { .. })),
            "a running lure is not a new one"
        );
    }

    /// A crab that disappears while entering a castle banked; one that
    /// disappears anywhere else was eaten.
    #[test]
    fn bank_and_eaten_classification() {
        let mut board = Board::new(6, 4, 7);
        board.set_tile(3, 1, TileKind::Castle(2));
        board.spawn_crab(2, 1, Direction::Right, Handedness::Left, CrabKind::Giant);
        let mut watch = synced(&board);
        let mut banked = None;
        for _ in 0..600 {
            board.tick_idle();
            let events = diff(&board, &mut watch);
            if let Some(SimEvent::CrabBanked { owner, points, .. }) = events
                .iter()
                .find(|e| matches!(e, SimEvent::CrabBanked { .. }))
            {
                banked = Some((*owner, *points));
                break;
            }
            assert!(
                !events
                    .iter()
                    .any(|e| matches!(e, SimEvent::CrabEaten { .. })),
                "a banking crab must never read as eaten"
            );
        }
        assert_eq!(
            banked,
            Some((2, 10)),
            "giant banks for its owner at value 10"
        );

        // Eaten: a gull dropped on the crab's tile removes it mid-sand.
        let mut board = Board::new(6, 4, 7);
        board.spawn_crab(1, 2, Direction::Right, Handedness::Left, CrabKind::Common);
        let mut watch = synced(&board);
        board.spawn_gull(1, 2, Direction::Right);
        let mut eaten = false;
        for _ in 0..60 {
            board.tick_idle();
            let events = diff(&board, &mut watch);
            assert!(
                !events
                    .iter()
                    .any(|e| matches!(e, SimEvent::CrabBanked { .. })),
                "an eaten crab must never read as banked"
            );
            if events
                .iter()
                .any(|e| matches!(e, SimEvent::CrabEaten { .. }))
            {
                eaten = true;
                break;
            }
        }
        assert!(eaten, "the gull never registered its meal");
    }

    /// A gull taking a crab one tile short of a castle, the crab facing
    /// it, is a gull's dinner: nobody banked it. Read off the map, it was
    /// a bank for the castle's owner, with the sound, the points, and for
    /// a sparkling crab a wheel that never turned.
    #[test]
    fn a_crab_eaten_in_front_of_a_castle_is_eaten() {
        let mut board = Board::new(6, 4, 7);
        board.rules_mut().castle_raids = false;
        board.set_tile(3, 1, TileKind::Castle(2));
        board.spawn_crab(
            2,
            1,
            Direction::Right,
            Handedness::Left,
            CrabKind::Sparkling,
        );
        let mut watch = synced(&board);
        board.spawn_gull(2, 1, Direction::Right);
        board.tick_idle();
        assert!(board.crabs().is_empty(), "the gull took it");
        assert_eq!(board.scores()[2], 0, "and nobody banked it");
        let events = diff(&board, &mut watch);
        assert!(
            events
                .iter()
                .any(|e| matches!(e, SimEvent::CrabEaten { .. })),
            "{events:?}"
        );
        assert!(
            !events
                .iter()
                .any(|e| matches!(e, SimEvent::CrabBanked { .. })),
            "{events:?}"
        );
    }

    /// A frame that spans several ticks still sees a crab that walked in
    /// early in it as banked, at its castle, for what the sim paid.
    #[test]
    fn a_bank_inside_a_long_frame_is_a_bank() {
        let mut board = Board::new(6, 4, 7);
        board.set_tile(3, 1, TileKind::Castle(2));
        board.spawn_crab(2, 1, Direction::Right, Handedness::Left, CrabKind::Giant);
        let mut watch = synced(&board);
        while !board.crabs().is_empty() {
            board.tick_idle();
        }
        for _ in 0..10 {
            board.tick_idle();
        }
        let events = diff(&board, &mut watch);
        let banked: Vec<_> = events
            .iter()
            .filter_map(|e| {
                if let SimEvent::CrabBanked {
                    owner,
                    keep,
                    points,
                    ..
                } = e
                {
                    Some((*owner, *keep, *points))
                } else {
                    None
                }
            })
            .collect();
        assert_eq!(
            banked,
            vec![(2, layout::tile_center(&board, 3, 1), 10)],
            "{events:?}"
        );
        assert_eq!(board.scores()[2], 10);
    }

    /// A gull a puzzle's castle turns away is seen leaving, from where it
    /// was, beside the castle that sent it. With raids on the same walk is
    /// a raid, whose own event is the news, and nothing is shooed.
    #[test]
    fn a_raid_free_castle_is_seen_turning_its_gull_away() {
        for raids in [false, true] {
            let mut board = Board::new(6, 4, 7);
            board.set_tile(3, 1, TileKind::Castle(0));
            board.rules_mut().castle_raids = raids;
            board.spawn_gull(2, 1, Direction::Right);
            let mut watch = synced(&board);
            let mut shooed = Vec::new();
            for _ in 0..120 {
                board.tick_idle();
                let events = diff(&board, &mut watch);
                assert!(
                    !events
                        .iter()
                        .any(|e| matches!(e, SimEvent::GullFlewOff { .. })),
                    "raids {raids}: through a castle is not flying off: {events:?}"
                );
                shooed.extend(
                    events
                        .into_iter()
                        .filter(|e| matches!(e, SimEvent::GullShooed { .. })),
                );
                if board.gulls().is_empty() {
                    break;
                }
            }
            assert!(
                board.gulls().is_empty(),
                "raids {raids}: the gull never left"
            );
            if raids {
                assert!(shooed.is_empty(), "a raid is not a shooing: {shooed:?}");
                continue;
            }
            let castle = layout::tile_center(&board, 3, 1);
            match shooed.as_slice() {
                [SimEvent::GullShooed { pos, castle: at }] => {
                    assert_eq!(*at, castle, "the castle it walked into");
                    assert!(
                        pos.distance(castle) <= layout::TILE,
                        "last drawn beside it: {pos}"
                    );
                }
                other => panic!("one departure, told once: {other:?}"),
            }
        }
    }

    /// A gull a full flock sends off is seen flying off from where it stood,
    /// and nobody's castle is told it was raided.
    #[test]
    fn a_gull_sent_off_by_its_flock_is_seen_flying_off() {
        let mut board = Board::new(12, 9, 7);
        board.set_tile(1, 1, TileKind::Castle(0));
        board.spawn_gull(10, 7, Direction::Up);
        for _ in 0..3 {
            board.tick_idle();
        }
        let mut watch = synced(&board);
        board.rules_mut().gull_period = 1;
        board.rules_mut().gull_cap = 1;
        board.rules_mut().gull_turnover = true;
        board.tick_idle();
        let events = diff(&board, &mut watch);
        let flew: Vec<&SimEvent> = events
            .iter()
            .filter(|e| matches!(e, SimEvent::GullFlewOff { .. }))
            .collect();
        match flew.as_slice() {
            [SimEvent::GullFlewOff { pos }] => {
                let stood = layout::tile_center(&board, 10, 7);
                assert!(pos.distance(stood) <= layout::TILE, "from {pos}");
            }
            other => panic!("one gull flew off, told once: {other:?}"),
        }
        assert!(
            !events.iter().any(|e| matches!(
                e,
                SimEvent::CastleRaided { .. } | SimEvent::GullShooed { .. }
            )),
            "{events:?}"
        );
    }

    /// A full flock turning over sends one gull off as it sends for the
    /// next, and the newcomer is news twice: when it is sent for, with the
    /// tile and tick it lands on, and when it lands there, on that tick.
    #[test]
    fn a_gull_that_takes_a_turned_over_place_is_heard_coming_and_arriving() {
        let mut board = Board::new(12, 9, 7);
        board.set_tile(1, 1, TileKind::Castle(0));
        board.spawn_gull(10, 7, Direction::Up);
        while board.ticks() < 50 {
            board.tick_idle();
        }
        let mut watch = synced(&board);
        board.rules_mut().gull_period = 50;
        board.rules_mut().gull_cap = 1;
        board.rules_mut().gull_turnover = true;
        board.tick_idle();
        let events = diff(&board, &mut watch);
        assert!(board.gulls().is_empty(), "the old one is off");
        assert!(
            events
                .iter()
                .any(|e| matches!(e, SimEvent::GullFlewOff { .. })),
            "{events:?}"
        );
        let due = 50 + u64::from(crate::sim::GULL_LEAD);
        let [incoming] = board.incoming_gulls() else {
            panic!("one sent for: {:?}", board.incoming_gulls());
        };
        let tile = board.coords_u8(incoming.tile);
        assert!(
            events.iter().any(|e| matches!(
                e,
                SimEvent::GullIncoming { tile: at_tile, at, .. } if *at == due && *at_tile == tile
            )),
            "the new gull was not heard coming: {events:?}"
        );
        // Nothing more until it lands, and then it lands on its tick.
        while board.ticks() <= due {
            assert!(
                board.gulls().is_empty(),
                "landed early, at {}",
                board.ticks()
            );
            let events = diff(&board, &mut watch);
            assert!(
                !events
                    .iter()
                    .any(|e| matches!(e, SimEvent::GullArrived | SimEvent::GullIncoming { .. })),
                "{events:?}"
            );
            board.tick_idle();
        }
        let events = diff(&board, &mut watch);
        assert_eq!(board.gulls().len(), 1, "landed on the tick it was due");
        assert_eq!(board.coords_u8(board.gulls()[0].tile), tile);
        assert!(
            events.iter().any(|e| matches!(e, SimEvent::GullArrived)),
            "the new gull came in unannounced: {events:?}"
        );
    }

    /// A golden crab's call is news once, when it goes public, from the
    /// hole it was called to.
    #[test]
    fn a_golden_crab_is_announced_once_and_seen_coming_out() {
        let mut board = Board::new(9, 7, 11);
        board.set_tile(1, 1, TileKind::Castle(0));
        board.set_tile(
            0,
            3,
            TileKind::Spawner(crate::sim::Spawner {
                dir: Direction::Right,
                period: 9,
            }),
        );
        board.rules_mut().golden_every = 600;
        board.tick_idle();
        let mut watch = synced(&board);
        let mut called = Vec::new();
        for _ in 0..600 {
            board.tick_idle();
            called.extend(diff(&board, &mut watch).into_iter().filter(|e| {
                matches!(
                    e,
                    SimEvent::GoldenCalled { .. } | SimEvent::GoldenOut { .. }
                )
            }));
        }
        // Called, then out of the same hole, each told once.
        let hole = layout::tile_center(&board, 0, 3);
        match called.as_slice() {
            [
                SimEvent::GoldenCalled { pos },
                SimEvent::GoldenOut { pos: out },
            ] => {
                assert_eq!(*pos, hole);
                assert!(
                    out.distance(hole) < layout::TILE / 2.0,
                    "out at {out}, hole at {hole}"
                );
            }
            other => panic!("one call and one arrival, told once each: {other:?}"),
        }
    }

    /// Crab Mania clears the sky in one go, and none of those birds went
    /// near a castle. The board has ticked first: on an unticked one the
    /// gulls going would read as a board swap, which is silent anyway, and
    /// the test would pass without the rule it is here for.
    #[test]
    fn the_gulls_crab_mania_clears_were_not_shooed() {
        let mut board = Board::new(8, 4, 7);
        board.set_tile(7, 3, TileKind::Castle(0));
        board.rules_mut().castle_raids = false;
        board.spawn_gull(0, 0, Direction::Up);
        board.spawn_gull(1, 0, Direction::Up);
        for _ in 0..3 {
            board.tick_idle();
        }
        let mut watch = synced(&board);
        board.force_tide_event(TideEvent::CrabMania, 0);
        board.tick_idle();
        assert!(board.gulls().is_empty(), "the tide took them");
        let events = diff(&board, &mut watch);
        assert!(
            !events
                .iter()
                .any(|e| matches!(e, SimEvent::GullShooed { .. })),
            "washed away, not turned away: {events:?}"
        );
    }

    /// A board swap (tick clock rolling back) resyncs without emitting a
    /// burst of stale events.
    #[test]
    fn board_swap_is_silent() {
        let mut board = Board::new(6, 4, 7);
        board.spawn_crab(1, 1, Direction::Right, Handedness::Left, CrabKind::Common);
        let mut watch = synced(&board);
        for _ in 0..40 {
            board.tick_idle();
            diff(&board, &mut watch);
        }
        // A fresh, different board: everything changed, nothing fires.
        let fresh = Board::new(8, 6, 99);
        assert!(
            diff(&fresh, &mut watch).is_empty(),
            "a board swap must not fire stale events"
        );
    }

    /// A round picked back up from a pasted code arrives mid-clock, and can
    /// be further along than the board watched before it. The clock then
    /// says nothing rolled back, and the diff runs across two unrelated
    /// boards. The beach's size and seed are what tell them apart.
    #[test]
    fn a_pasted_round_further_along_is_still_a_swap() {
        let mut board = Board::new(6, 4, 7);
        board.spawn_crab(1, 1, Direction::Right, Handedness::Left, CrabKind::Common);
        let mut watch = synced(&board);
        for _ in 0..40 {
            board.tick_idle();
            diff(&board, &mut watch);
        }
        let mut pasted = Board::new(8, 6, 99);
        pasted.set_tile(1, 1, TileKind::Castle(0));
        for _ in 0..300 {
            pasted.tick_idle();
        }
        assert!(
            pasted.ticks() > watch.identity.ticks,
            "the pasted round is further along"
        );
        assert!(
            diff(&pasted, &mut watch).is_empty(),
            "a different beach is a swap whatever its clock says"
        );
    }

    /// The board count the drawings reset on moves for a new board and for
    /// nothing else: not for the same board ticking on, and not for a
    /// post going in during a puzzle's Setup. A round pasted in further
    /// along than the last one is new by its beach, which the clock alone
    /// missed.
    #[test]
    fn the_board_count_moves_for_a_new_board_and_only_then() {
        let mut generation = BoardGeneration::default();
        let mut board = Board::new(6, 4, 7);
        generation.observe(&board);
        let first = generation.get();
        for _ in 0..40 {
            board.tick_idle();
            generation.observe(&board);
        }
        assert_eq!(generation.get(), first, "the same board ticking on");
        let mut pasted = Board::new(8, 6, 99);
        for _ in 0..300 {
            pasted.tick_idle();
        }
        generation.observe(&pasted);
        let after_paste = generation.get();
        assert_ne!(after_paste, first, "a pasted round mid-clock is new");
        let rematch = Board::new(8, 6, 99);
        generation.observe(&rematch);
        let rematch_count = generation.get();
        assert_ne!(rematch_count, after_paste, "a clock rolled back is new");
        let mut setup = Board::new(8, 6, 99);
        assert!(
            setup.place_signpost(0, 2, 2, Direction::Up),
            "a post goes in"
        );
        generation.observe(&setup);
        assert_eq!(generation.get(), rematch_count, "a post in Setup is not");
        let mut other = Board::new(8, 6, 99);
        other.set_tile(3, 3, TileKind::Rock);
        generation.observe(&other);
        assert_ne!(generation.get(), rematch_count, "another unticked board is");
    }

    /// Losing your oldest signpost to the cap fires; every other way one
    /// leaves the board does not.
    ///
    /// The versus rule takes a post in trade for the fourth you place, and
    /// the count on the header does not move, since one went for one.
    /// Pulling a post yourself, or letting one expire, is a count going
    /// *down*, and neither is news.
    #[test]
    fn a_signpost_traded_away_at_the_cap_says_so() {
        let mut board = Board::new(6, 4, 5);
        board.set_signpost_rule(3, crate::sim::CapPolicy::Evict);
        for x in 0..3u8 {
            assert!(board.place_signpost(0, x, 0, Direction::Up));
        }
        let mut watch = synced(&board);

        // The fourth: the oldest, at (0,0), is traded for it.
        assert!(board.place_signpost(0, 5, 3, Direction::Down));
        let events = diff(&board, &mut watch);
        let evicted: Vec<_> = events
            .iter()
            .filter_map(|e| match e {
                SimEvent::SignpostEvicted { owner, dir, .. } => Some((*owner, *dir)),
                SimEvent::CrabBanked { .. }
                | SimEvent::CrabEaten { .. }
                | SimEvent::CrabSpawned { .. }
                | SimEvent::CastleRaided { .. }
                | SimEvent::GullIncoming { .. }
                | SimEvent::GullArrived
                | SimEvent::GullTookOff
                | SimEvent::GullLanded { .. }
                | SimEvent::GullShooed { .. }
                | SimEvent::GullFlewOff { .. }
                | SimEvent::SignpostPlaced { .. }
                | SimEvent::SignpostRemoved { .. }
                | SimEvent::TierUp { .. }
                | SimEvent::TideEventFired { .. }
                | SimEvent::LureStarted { .. }
                | SimEvent::LureRefused { .. }
                | SimEvent::SurgeStarted
                | SimEvent::GoldenCalled { .. }
                | SimEvent::GoldenOut { .. }
                | SimEvent::WheelLocked { .. }
                | SimEvent::RoundEnded => None,
            })
            .collect();
        assert_eq!(
            evicted,
            vec![(0, Direction::Up)],
            "the traded post and the way it pointed: {events:?}"
        );
        // And the placement that paid for it sounds too, from the tile it
        // landed on: the board-wide count does not move, so nothing else
        // says a fourth post went down.
        assert!(
            events.iter().any(|e| matches!(
                e,
                SimEvent::SignpostPlaced { pos, .. } if *pos == layout::tile_center(&board, 5, 3)
            )),
            "the fourth post went down at (5,3): {events:?}"
        );

        // Pulling one yourself is a removal, not a trade.
        assert!(board.remove_signpost(0, 1, 0));
        let events = diff(&board, &mut watch);
        assert!(
            !events
                .iter()
                .any(|e| matches!(e, SimEvent::SignpostEvicted { .. })),
            "removing your own post is not an eviction: {events:?}"
        );
        assert!(
            events.iter().any(|e| matches!(
                e,
                SimEvent::SignpostRemoved { pos, .. } if *pos == layout::tile_center(&board, 1, 0)
            )),
            "but it is a removal, at its tile: {events:?}"
        );

        // Re-pointing one in place keeps the tile and the seat, so it is
        // none of the three: not a trade, and not a post coming or going.
        assert!(board.place_signpost(0, 2, 0, Direction::Left));
        let events = diff(&board, &mut watch);
        assert!(
            !events.iter().any(|e| matches!(
                e,
                SimEvent::SignpostEvicted { .. }
                    | SimEvent::SignpostPlaced { .. }
                    | SimEvent::SignpostRemoved { .. }
            )),
            "re-pointing is not a post changing hands: {events:?}"
        );
    }

    /// Two seats acting between one frame and the next each get their own
    /// cue, from their own tile.
    ///
    /// A single board-wide count is deaf to who moved: a placement and a
    /// removal in the same frame cancel to a net zero and *neither* player
    /// hears anything, which on a busy versus beach is the common case.
    #[test]
    fn one_seat_placing_while_another_pulls_sounds_for_both() {
        let mut board = Board::new(6, 4, 11);
        assert!(board.place_signpost(1, 4, 2, Direction::Left));
        let mut watch = synced(&board);

        // The same frame: seat 1 pulls theirs, seat 0 puts one down.
        assert!(board.remove_signpost(1, 4, 2));
        assert!(board.place_signpost(0, 1, 1, Direction::Up));
        let events = diff(&board, &mut watch);

        assert!(
            events.iter().any(|e| matches!(
                e,
                SimEvent::SignpostPlaced { pos, .. } if *pos == layout::tile_center(&board, 1, 1)
            )),
            "seat 0's placement, at its tile: {events:?}"
        );
        assert!(
            events.iter().any(|e| matches!(
                e,
                SimEvent::SignpostRemoved { pos, .. } if *pos == layout::tile_center(&board, 4, 2)
            )),
            "seat 1's removal, at its tile: {events:?}"
        );
    }

    /// Two boards that have never ticked share a clock reading of 0, so a
    /// swap between them (skipping puzzle levels from the Setup phase, an
    /// editor resize) must be recognised by identity: no stale crab
    /// departures, and no out-of-bounds probe when the new board is the
    /// smaller one.
    #[test]
    fn swap_between_unticked_boards_is_silent() {
        let mut large = Board::new(9, 7, 3);
        large.spawn_crab(8, 6, Direction::Right, Handedness::Left, CrabKind::Common);
        large.spawn_crab(1, 1, Direction::Right, Handedness::Left, CrabKind::Giant);
        let mut watch = synced(&large);
        assert_eq!(watch.identity.ticks, 0);

        // Smaller board, same seed, a different crab: the old crabs would
        // land off-board (the corner one) or read as eaten (the other).
        let mut small = Board::new(6, 4, 3);
        small.spawn_crab(2, 2, Direction::Left, Handedness::Right, CrabKind::Common);
        assert!(
            diff(&small, &mut watch).is_empty(),
            "a swap between un-ticked boards must be silent"
        );

        // Same size, same seed, differently populated: still a swap.
        let mut other = Board::new(6, 4, 3);
        other.spawn_crab(4, 1, Direction::Up, Handedness::Left, CrabKind::Common);
        assert!(
            diff(&other, &mut watch).is_empty(),
            "a same-sized un-ticked board with other crabs is a swap"
        );

        // But a change on the *same* un-ticked board is not a swap: a
        // signpost placed during Setup still announces itself.
        assert!(other.place_signpost(0, 1, 1, Direction::Down));
        let events = diff(&other, &mut watch);
        assert!(
            events
                .iter()
                .any(|e| matches!(e, SimEvent::SignpostPlaced { .. })),
            "setup-phase signposts must still fire, got {events:?}"
        );
    }

    /// The departure the tiles cannot explain. `Monopoly` banks half the
    /// loose crabs where they stand, so each goes from open sand with no
    /// castle at either end of its step and reads as a death: eighty-two
    /// of them on one measured tick, while the seat that had just taken
    /// half the beach got no hop, no bounce and no floating score.
    #[test]
    fn a_crab_the_tide_banked_reads_as_banked_and_not_as_eaten() {
        let mut board = Board::new(9, 7, 5);
        board.set_tile(7, 5, TileKind::Castle(1));
        // Out in the open, walking nowhere near a castle: the shape the
        // tiles get wrong.
        board.spawn_crab(1, 1, Direction::Right, Handedness::Left, CrabKind::Common);
        board.spawn_crab(2, 1, Direction::Right, Handedness::Left, CrabKind::Common);
        let prev = board.crabs()[0];
        assert!(
            matches!(
                crab_departure(&board, &prev, false),
                SimEvent::CrabEaten { .. }
            ),
            "off open sand, and nothing yet says otherwise"
        );

        board.force_tide_event(TideEvent::Monopoly, 1);
        let SimEvent::CrabBanked {
            id, owner, keep, ..
        } = crab_departure(&board, &prev, false)
        else {
            panic!("the tide put it in seat 1's keep");
        };
        assert_eq!(id, prev.id);
        assert_eq!(owner, 1, "and the seat that got it is the banker");
        assert_eq!(
            keep,
            layout::tile_center(&board, 7, 5),
            "flown to the keep it was banked into, not to the sand it left"
        );
    }

    /// A sweep that flies its crabs home: picked up, they are neither
    /// eaten nor banked; each lands as a bank at its keep, where the
    /// drawing has already flown it.
    #[test]
    fn a_flying_sweep_banks_at_the_keep_when_each_crab_lands() {
        let mut board = Board::new(9, 7, 5);
        board.rules_mut().sweep_flight = true;
        board.set_tile(7, 5, TileKind::Castle(1));
        for x in 1..5 {
            board.spawn_crab(x, 1, Direction::Down, Handedness::Left, CrabKind::Common);
        }
        board.tick_idle();
        let mut watch = synced(&board);
        board.force_tide_event(TideEvent::Monopoly, 1);
        let lifted = diff(&board, &mut watch);
        assert!(
            !lifted
                .iter()
                .any(|e| matches!(e, SimEvent::CrabEaten { .. } | SimEvent::CrabBanked { .. })),
            "picked up is neither: {lifted:?}"
        );
        let keep = layout::tile_center(&board, 7, 5);
        let mut landed = 0;
        while !board.sweeping().is_empty() {
            board.tick_idle();
            for event in diff(&board, &mut watch) {
                if let SimEvent::CrabBanked { owner: 1, pos, .. } = event
                    && pos == keep
                {
                    landed += 1;
                }
            }
        }
        assert_eq!(landed, 2, "both swept crabs banked at the keep");
    }

    /// The points a swept crab's landing shows are the points the sim
    /// paid: it banks under the claw call it was swept under, so a Right
    /// Claws spun while it is in the air must not turn a left-clawed
    /// crab's float into a loss while the score goes up.
    #[test]
    fn a_swept_crab_shows_what_it_paid_not_what_the_clock_says() {
        let mut board = Board::new(9, 7, 5);
        board.rules_mut().sweep_flight = true;
        board.rules_mut().timed_lock = true;
        board.rules_mut().sweep_keeps_worth = true;
        board.set_tile(7, 5, TileKind::Castle(1));
        board.set_score(1, 10);
        for x in 1..5 {
            board.spawn_crab(x, 1, Direction::Down, Handedness::Left, CrabKind::Common);
        }
        board.tick_idle();
        let mut watch = synced(&board);
        board.force_tide_event(TideEvent::Monopoly, 1);
        let _ = diff(&board, &mut watch);
        board.tick_idle();
        let _ = diff(&board, &mut watch);
        board.force_tide_event(TideEvent::RightClaws, 0);
        let mut shown = 0;
        while !board.sweeping().is_empty() {
            board.tick_idle();
            for event in diff(&board, &mut watch) {
                if let SimEvent::CrabBanked {
                    owner: 1, points, ..
                } = event
                {
                    shown += points;
                }
            }
        }
        assert!(
            board.in_claw_call(),
            "Right Claws is running at the landing"
        );
        assert!(shown > 0, "the floats show a gain");
        assert_eq!(10 + shown, board.scores()[1] as i32, "and the gain banked");
    }

    /// A sparkling crab Crab Monopoly flies home lands seconds after the
    /// event, in a look that fired nothing. The sim never spins the wheel
    /// for a swept crab, so its landing is a bank and not a refusal.
    #[test]
    fn a_swept_sparkling_crab_does_not_say_the_wheel_is_locked() {
        let mut board = Board::new(9, 7, 5);
        board.set_events_enabled(true);
        board.rules_mut().sweep_flight = true;
        board.set_tile(7, 5, TileKind::Castle(1));
        // Front of the line first: the sparkling one is the half taken.
        board.spawn_crab(1, 1, Direction::Down, Handedness::Left, CrabKind::Sparkling);
        board.spawn_crab(2, 1, Direction::Down, Handedness::Left, CrabKind::Common);
        board.tick_idle();
        let mut watch = synced(&board);
        board.force_tide_event(TideEvent::Monopoly, 1);
        let _ = diff(&board, &mut watch);
        assert_eq!(
            board.sweeping().len(),
            1,
            "the sparkling crab is in the air"
        );
        let mut landed = false;
        while !board.sweeping().is_empty() {
            board.tick_idle();
            let events = diff(&board, &mut watch);
            landed |= events.iter().any(|e| {
                matches!(
                    e,
                    SimEvent::CrabBanked {
                        kind: CrabKind::Sparkling,
                        ..
                    }
                )
            });
            assert!(
                !events
                    .iter()
                    .any(|e| matches!(e, SimEvent::WheelLocked { .. })),
                "{events:?}"
            );
        }
        assert!(landed, "the sparkling crab banked");
    }

    /// Through the whole differ, which is what the game actually runs: the
    /// tick a sweep lands on reports banks and not a single death.
    #[test]
    fn a_sweep_puts_no_deaths_on_the_stream() {
        let mut board = Board::new(9, 7, 11);
        board.set_tile(7, 5, TileKind::Castle(0));
        for x in 1..5u8 {
            board.spawn_crab(x, 1, Direction::Right, Handedness::Left, CrabKind::Common);
        }
        let mut watch = Watch::default();
        let _ = diff(&board, &mut watch);
        board.force_tide_event(TideEvent::Monopoly, 0);
        board.tick_idle();
        let events = diff(&board, &mut watch);
        let banked = events
            .iter()
            .filter(|e| matches!(e, SimEvent::CrabBanked { owner: 0, .. }))
            .count();
        let eaten = events
            .iter()
            .filter(|e| matches!(e, SimEvent::CrabEaten { .. }))
            .count();
        assert_eq!(banked, 2, "half of four, every one of them a bank");
        assert_eq!(eaten, 0, "and the gulls got nothing: {events:?}");
    }

    /// A crab remembered at a tile the current board does not have (a
    /// swap the differ was not told about) must not probe off-board.
    #[test]
    fn crab_departure_survives_a_smaller_board() {
        let mut large = Board::new(9, 7, 3);
        large.spawn_crab(8, 6, Direction::Right, Handedness::Left, CrabKind::Common);
        let prev = large.crabs()[0];
        let small = Board::new(6, 4, 3);
        assert!(matches!(
            crab_departure(&small, &prev, false),
            SimEvent::CrabEaten { .. }
        ));
    }

    /// A crab leaving the last column of a wrapping beach walks into a
    /// castle on the first. Read with the plain offset, the castle was off
    /// the board and the bank a gull's dinner: feathers, and the castle's
    /// owner never saw the crab arrive.
    #[test]
    fn a_crab_banking_across_the_seam_is_a_bank() {
        let mut board = Board::new(6, 4, 7);
        board.set_wrap(true);
        board.set_tile(0, 1, TileKind::Castle(1));
        board.spawn_crab(4, 1, Direction::Right, Handedness::Left, CrabKind::Common);
        let mut watch = Watch::default();
        diff(&board, &mut watch);
        let mut seen = Vec::new();
        for _ in 0..600 {
            board.tick_idle();
            seen.extend(diff(&board, &mut watch));
            if board.crabs().is_empty() {
                break;
            }
        }
        assert!(board.crabs().is_empty(), "the crab went somewhere");
        assert!(
            seen.iter()
                .any(|e| matches!(e, SimEvent::CrabBanked { owner: 1, .. })),
            "into the castle over the seam: {seen:?}"
        );
        assert!(
            !seen.iter().any(|e| matches!(e, SimEvent::CrabEaten { .. })),
            "and not into a gull: {seen:?}"
        );
    }

    /// A watcher who lost the thread is handed the round as it stands and
    /// the arena is built again from it: the same beach, its clock further
    /// along. Read as the old board ticking on, the crab that banked in
    /// the gap banked again on the first frame back, sound, pip and all.
    /// Laid out afresh, the board is new, and nothing on it is news.
    #[test]
    fn a_round_laid_out_again_further_along_is_not_news() {
        let mut board = Board::new(6, 4, 7);
        board.set_tile(3, 1, TileKind::Castle(1));
        board.spawn_crab(2, 1, Direction::Right, Handedness::Left, CrabKind::Common);
        let mut further = board.clone();
        while !further.crabs().is_empty() {
            further.tick_idle();
        }
        assert!(further.scores()[1] > 0, "the crab banked in the gap");
        let mut watch = Watch::default();
        diff(&board, &mut watch);
        let gap = diff(&further, &mut watch);
        assert!(!gap.is_empty(), "read as the same board, the gap is news");
        let mut app = App::new();
        app.add_message::<SimEvent>();
        app.insert_resource(Sim(board));
        app.init_resource::<BoardGeneration>();
        app.add_systems(Update, (track_board, observe_sim).chain());
        app.update();
        let before = app.world().resource::<BoardGeneration>().get();
        app.world_mut()
            .resource_mut::<BoardGeneration>()
            .laid_out(&further);
        app.insert_resource(Sim(further));
        app.update();
        let after = app.world().resource::<BoardGeneration>().get();
        assert_ne!(after, before, "a board laid out is a new board");
        let mut messages = app.world_mut().resource_mut::<Messages<SimEvent>>();
        let events: Vec<_> = messages.drain().collect();
        assert!(events.is_empty(), "and its past is not news: {events:?}");
    }

    /// The app-layer harness pattern: drive the real system inside a
    /// headless Bevy App (no plugins beyond the schedule) and read the
    /// messages it wrote, proving the ECS wiring end to end.
    #[test]
    fn observe_sim_runs_headless_in_an_app() {
        let mut app = App::new();
        app.add_message::<SimEvent>();
        let mut board = Board::new(6, 4, 7);
        board.set_tile(3, 1, TileKind::Castle(1));
        board.spawn_crab(2, 1, Direction::Right, Handedness::Left, CrabKind::Common);
        app.insert_resource(Sim(board));
        app.init_resource::<BoardGeneration>();
        app.add_systems(Update, (track_board, observe_sim).chain());
        app.update(); // syncs the watch to the starting board

        let mut banked = false;
        for _ in 0..600 {
            app.world_mut().resource_mut::<Sim>().0.tick_idle();
            app.update();
            let mut messages = app.world_mut().resource_mut::<Messages<SimEvent>>();
            if messages
                .drain()
                .any(|e| matches!(e, SimEvent::CrabBanked { owner: 1, .. }))
            {
                banked = true;
                break;
            }
        }
        assert!(banked, "the system never reported the bank through the App");
    }

    /// Frames where nobody touches the sim are skipped, and skipping them
    /// leaves the watch fit to report the next move: the board it holds is
    /// the board that is still there.
    #[test]
    fn an_untouched_sim_is_not_re_read() {
        let mut app = App::new();
        app.add_message::<SimEvent>();
        let mut board = Board::new(6, 4, 7);
        board.set_tile(3, 1, TileKind::Castle(1));
        board.spawn_crab(2, 1, Direction::Right, Handedness::Left, CrabKind::Common);
        app.insert_resource(Sim(board));
        app.init_resource::<BoardGeneration>();
        app.add_systems(Update, (track_board, observe_sim).chain());
        app.update(); // syncs the watch to the starting board

        for _ in 0..3 {
            app.update();
            let mut messages = app.world_mut().resource_mut::<Messages<SimEvent>>();
            assert_eq!(
                messages.drain().count(),
                0,
                "a still board reported something happening"
            );
        }

        let mut banked = false;
        for _ in 0..600 {
            app.world_mut().resource_mut::<Sim>().0.tick_idle();
            app.update();
            let mut messages = app.world_mut().resource_mut::<Messages<SimEvent>>();
            if messages
                .drain()
                .any(|e| matches!(e, SimEvent::CrabBanked { owner: 1, .. }))
            {
                banked = true;
                break;
            }
        }
        assert!(banked, "the bank went unreported after the idle frames");
    }

    /// Tier-ups name the seat whose castle grew.
    #[test]
    fn tier_up_names_its_owner() {
        let mut board = Board::new(6, 4, 7);
        let mut watch = synced(&board);
        board.set_score(3, 10); // tier 0 -> 1
        board.tick_idle();
        let events = diff(&board, &mut watch);
        assert!(
            events
                .iter()
                .any(|e| matches!(e, SimEvent::TierUp { owner: 3 })),
            "expected TierUp for seat 3, got {events:?}"
        );
    }
}