pinch-points 0.8.0

A fast, kid-friendly crab-routing game: route streams of crabs into your sandcastle before time runs out
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
//! 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, 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.
    CastleRaided {
        owner: PlayerId,
        pos: Vec2,
        lost: u32,
    },
    /// 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 `Board::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 and Beach Day 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 },
    /// 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(),
        })
    }
}

/// Last-seen sim facts for the diff.
#[derive(Default)]
pub struct Watch {
    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>,
    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)>,
    gulls: usize,
    flying: usize,
    event_at: Option<u64>,
    last_event: Option<TideEvent>,
    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>,
    /// Where each gull was in the air, `None` while it was on the sand: a
    /// gull that had a flight position and now has none has just landed.
    gulls_aloft: HashMap<u32, Option<Vec2>>,
    /// Where each gull was last drawn, for the one that is gone next frame.
    gulls_at: HashMap<u32, Vec2>,
}

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 {
            ticks: board.ticks(),
            beach: (board.width(), board.height(), board.seed()),
            origin: Origin::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(),
            gulls: board.gulls().len(),
            flying: board
                .gulls()
                .iter()
                .filter(|g| matches!(g.state, GullState::Flying { .. }))
                .count(),
            event_at: board.last_event().map(|(_, at)| at),
            last_event: board.last_event().map(|(event, _)| 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_aloft: board
                .gulls()
                .iter()
                .map(|g| {
                    let aloft = matches!(g.state, GullState::Flying { .. })
                        .then(|| layout::creature_pos(board, g.tile, g.dir, g.progress));
                    (g.id, aloft)
                })
                .collect(),
            gulls_at: board
                .gulls()
                .iter()
                .map(|g| (g.id, layout::creature_pos(board, g.tile, g.dir, g.progress)))
                .collect(),
        }
    }
}

/// 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 (x, y) = board.coords_u8(prev.tile);
    let (dx, dy) = prev.dir.offset();
    let tile_or_empty = |x: i32, y: i32| {
        if x >= 0 && y >= 0 && x < i32::from(board.width()) && y < i32::from(board.height()) {
            board.tile_at(x as u8, y as u8)
        } else {
            TileKind::Empty
        }
    };
    // 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 the tiles have the last word if it happens.
    if let Some(owner) = board.swept_home(prev.id)
        && let Some((kx, ky)) = board.castle_of(owner)
    {
        return SimEvent::CrabBanked {
            id: prev.id,
            owner,
            pos,
            keep: layout::tile_center(board, kx, ky),
            points: prev.bank_points(board.crab_value(prev.kind), claw),
            kind: prev.kind,
            handed: prev.handed,
        };
    }
    let here = tile_or_empty(i32::from(x), i32::from(y));
    let ahead = (i32::from(x) + dx, i32::from(y) + dy);
    let entering = tile_or_empty(ahead.0, ahead.1);
    // Which of the two tiles is the castle is also *where* it is, and this
    // is the only moment anybody knows: the board it was read from is this
    // frame's, and the event is consumed on the next.
    let keep_at = |at: (i32, i32)| layout::tile_center(board, at.0 as u8, at.1 as u8);
    match (here, entering) {
        (TileKind::Castle(owner), _) => SimEvent::CrabBanked {
            id: prev.id,
            owner,
            pos,
            keep: keep_at((i32::from(x), i32::from(y))),
            points: prev.bank_points(board.crab_value(prev.kind), claw),
            kind: prev.kind,
            handed: prev.handed,
        },
        (_, TileKind::Castle(owner)) => SimEvent::CrabBanked {
            id: prev.id,
            owner,
            pos,
            keep: keep_at(ahead),
            points: prev.bank_points(board.crab_value(prev.kind), claw),
            kind: prev.kind,
            handed: prev.handed,
        },
        _ => SimEvent::CrabEaten { pos },
    }
}

/// 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>,
) {
    let mania = next.event_at != prev.event_at && next.last_event == Some(TideEvent::CrabMania);
    if mania {
        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, &pos) in &prev.gulls_at {
        if next.gulls_at.contains_key(id) {
            continue;
        }
        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.castle_raids() {
            events.push(SimEvent::GullShooed { pos, castle });
        }
    }
}

/// Diff the sim against the last frame and emit one message per happening.
/// A board swap (fresh level or round, detected by the tick clock rolling
/// back or by an un-ticked board's identity changing) resyncs silently so
/// loading never fires a burst of stale events.
pub fn observe_sim(sim: Res<Sim>, mut watch: Local<Watch>, mut events: MessageWriter<SimEvent>) {
    // 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);
    // A board swap usually rolls the tick clock back; everything the old
    // board was doing is not news about the new one. 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.
    let swapped = board.ticks() < watch.ticks
        || next.beach != watch.beach
        || (board.ticks() == 0 && next.origin != watch.origin);
    let events = if swapped {
        Vec::new()
    } else {
        changes(board, watch, &next)
    };
    *watch = next;
    events
}

/// 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,
            });
        }
    }

    // Gull population and flight transitions.
    if next.gulls > prev.gulls {
        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 let Some(Some(_)) = prev.gulls_aloft.get(&gull.id)
            && !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 next.event_at.is_some()
        && next.event_at != prev.event_at
        && let Some(event) = next.last_event
    {
        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.
    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 {
                    owner,
                    kind: CrabKind::Sparkling,
                    ..
                } = event
                else {
                    return None;
                };
                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 });
    }
    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
    }

    /// 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.set_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 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 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.set_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.set_gull_period(1);
        board.set_gull_cap(1);
        board.set_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 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.set_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.set_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.ticks,
            "the pasted round is further along"
        );
        assert!(
            diff(&pasted, &mut watch).is_empty(),
            "a different beach is a swap whatever its clock says"
        );
    }

    /// 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::GullArrived
                | SimEvent::GullTookOff
                | SimEvent::GullLanded { .. }
                | SimEvent::GullShooed { .. }
                | SimEvent::GullFlewOff { .. }
                | SimEvent::SignpostPlaced { .. }
                | SimEvent::SignpostRemoved { .. }
                | SimEvent::TierUp { .. }
                | SimEvent::TideEventFired { .. }
                | SimEvent::LureStarted { .. }
                | 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.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.set_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");
    }

    /// 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 { .. }
        ));
    }

    /// 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.add_systems(Update, observe_sim);
        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.add_systems(Update, observe_sim);
        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:?}"
        );
    }
}