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
//! A complete board, written out and read back exactly.
//!
//! The level format describes a *starting* board: authoring data, tile
//! aligned, no creature mid-stride and no PRNG position. That is the right
//! shape for a level and the wrong shape for saving a round in progress,
//! which needs every field [`Board::state_hash`] covers or the board it
//! reloads is a different board from the next tick onward.
//!
//! So this is the other half: `parse(to_snapshot(board))` has the same
//! state hash as `board` for any board, however far into a round it is.
//!
//! The completeness is held by the compiler, not by vigilance:
//! [`Board::parse_snapshot`] builds its result with a struct literal naming
//! every field, so a field added to `Board` fails to build here until
//! somebody decides how it travels.

use super::*;

/// Format marker. Bump it if the layout changes, so an old snapshot is
/// refused rather than half-read.
const HEADER: &str = "snapshot-v1";

/// The furthest clock a snapshot may carry: over four years of play at the
/// tick rate, and nothing booked off it comes near overflowing a `u64`.
const MAX_TICK: u64 = u32::MAX as u64;

/// The furthest the spawn, placement and bank counters may have got.
const MAX_COUNT: u32 = u32::MAX / 2;

impl Board {
    /// The whole board as text.
    pub fn to_snapshot(&self) -> String {
        use std::fmt::Write;
        let mut out = String::new();
        let (rng_state, rng_inc) = self.rng.hash_state();
        let _ = writeln!(out, "{HEADER}");
        let _ = writeln!(out, "size: {} {}", self.grid.width, self.grid.height);
        let _ = writeln!(out, "seed: {}", self.seed);
        let _ = writeln!(out, "rng: {rng_state} {rng_inc}");
        let _ = writeln!(out, "tick: {}", self.tick);
        let _ = writeln!(
            out,
            "rule: {} {}",
            self.rules.cap_policy.token(),
            self.rules.signpost_cap
        );
        let _ = writeln!(
            out,
            "counters: {} {} {} {} {}",
            self.signpost_seq,
            self.next_crab_id,
            self.next_gull_id,
            self.crabs_banked,
            self.golden_banked
        );
        let scores: Vec<String> = self.scores.iter().map(u32::to_string).collect();
        let _ = writeln!(out, "scores: {}", scores.join(" "));
        let _ = writeln!(out, "gull_period: {}", self.rules.gull_period);
        // Everything below is omitted at its default, as a board between
        // rounds mostly is.
        if usize::from(self.rules.gull_cap) != GULL_CAP {
            let _ = writeln!(out, "gull_cap: {}", self.rules.gull_cap);
        }
        if self.rules.gull_turnover {
            let _ = writeln!(out, "gull_turnover: on");
        }
        if self.rules.golden_every > 0 {
            let _ = writeln!(out, "golden_every: {}", self.rules.golden_every);
        }
        if self.rules.timed_lock {
            let _ = writeln!(out, "timed_lock: on");
        }
        if self.rules.sweep_flight {
            let _ = writeln!(out, "sweep_flight: on");
        }
        if self.rules.whole_flock {
            let _ = writeln!(out, "whole_flock: on");
        }
        if self.rules.sweep_keeps_worth {
            let _ = writeln!(out, "sweep_keeps_worth: on");
        }
        if self.rules.fair_spawns {
            let _ = writeln!(out, "fair_spawns: on");
        }
        // The whole call, public or not: a round resumed from a code
        // sends its golden crab out where and when this one would have.
        if let Some((at, tile)) = self.golden_call {
            let (x, y) = self.coords_u8(tile);
            let _ = writeln!(out, "golden_call: {at} {x} {y}");
        }
        if let Some(len) = self.rules.round_length {
            let _ = writeln!(out, "round: {len}");
        }
        if self.wrap {
            let _ = writeln!(out, "wrap: on");
        }
        if !self.rules.castle_raids {
            let _ = writeln!(out, "raids: off");
        }
        if let Some([left, right]) = self.rules.claw_hands {
            let _ = writeln!(out, "claw_hands: {left} {right}");
        }
        if self.tide.enabled {
            let _ = writeln!(out, "events: on");
        }
        if let Some((owner, ticks)) = self.lure {
            let _ = writeln!(out, "lure: {owner} {ticks}");
        }
        if self.lure_cooldown > 0 {
            let _ = writeln!(out, "cooldown: {}", self.lure_cooldown);
        }
        if self.tide.cooldown > 0 {
            let _ = writeln!(out, "event_cooldown: {}", self.tide.cooldown);
        }
        if let Some((mania, ticks)) = self.tide.mania {
            let name = match mania {
                Mania::Crab => "crab",
                Mania::Gull => "gull",
            };
            let _ = writeln!(out, "mania: {name} {ticks}");
        }
        if self.tide.claw_call > 0 {
            let _ = writeln!(out, "claw_call: {}", self.tide.claw_call);
        }
        if let Some((tempo, ticks)) = self.tide.tempo {
            let name = match tempo {
                Tempo::Fast => "fast",
                Tempo::Slow => "slow",
            };
            let _ = writeln!(out, "tempo: {name} {ticks}");
        }
        if let Some((event, at)) = self.tide.last {
            let _ = writeln!(out, "last_event: {} {at}", event.index());
        }
        for (seat, hand) in self.hands.iter().enumerate() {
            if let Some((tile, at)) = hand {
                let _ = writeln!(out, "hand: {seat} {tile} {at}");
            }
        }
        let _ = writeln!(out, "hwalls: {}", bits_to_hex(&self.grid.h_walls));
        let _ = writeln!(out, "vwalls: {}", bits_to_hex(&self.grid.v_walls));
        let tiles: Vec<String> = self
            .grid
            .tiles
            .iter()
            .map(|&kind| tile_token(kind))
            .collect();
        let _ = writeln!(out, "tiles: {}", tiles.join(" "));
        for (tile, slot) in self.signposts.iter().enumerate() {
            if let Some(post) = slot {
                let health = match post.health {
                    SignpostHealth::Full => "full",
                    SignpostHealth::Worn => "worn",
                };
                let _ = writeln!(
                    out,
                    "post: {tile} {} {} {health} {} {}",
                    post.dir.letter(),
                    post.owner,
                    post.seq,
                    post.placed
                );
            }
        }
        for crab in &self.crabs {
            let _ = writeln!(out, "crab: {}", crab_fields(crab));
        }
        // A crab in a Crab Monopoly sweep: who it flies to, when it leaves
        // and lands, then the crab exactly as a `crab:` line writes it, and
        // `claws` after it when it was swept under Right Claws (left off
        // otherwise, which is how every line read before it was kept).
        for flight in &self.sweeps.in_air {
            let called = if flight.claw_call { " claws" } else { "" };
            let _ = writeln!(
                out,
                "sweeping: {} {} {} {}{called}",
                flight.owner,
                flight.launch,
                flight.lands,
                crab_fields(&flight.crab),
            );
        }
        for gull in &self.gulls {
            // `remaining` is only meaningful mid-flight; a walking gull
            // writes a placeholder zero so every line has the same shape.
            let (state, remaining) = match gull.state {
                GullState::Walking => ("walk", 0),
                GullState::Flying { remaining } => ("fly", remaining),
            };
            let _ = writeln!(
                out,
                "gull: {} {} {} {} {} {} {} {} {state} {remaining} {}",
                gull.id,
                gull.tile,
                gull.dir.letter(),
                gull.progress,
                gull.prev.tile,
                gull.prev.progress,
                gull.prev.dir.letter(),
                gull.handed.token(),
                gull.takeoff_in
            );
        }
        // A gull on its way in: the tick it lands, its tile, its facing.
        for gull in &self.incoming {
            let _ = writeln!(
                out,
                "incoming: {} {} {}",
                gull.at,
                gull.tile,
                gull.dir.letter()
            );
        }
        // Who steered which gull, and what the steered gulls took from
        // whom: the raids' credit, which the rules never read but every
        // screen tells. Only gulls on the sand, the rule the parser holds a
        // snapshot to: [`Board::drop_gulls`] keeps the list that way, and
        // the filter keeps a slip there from writing a file nobody can
        // read back.
        let on_the_sand = |gull: &u32| self.gulls.iter().any(|g| g.id == *gull);
        for (gull, by) in self
            .steering
            .by_gull
            .iter()
            .filter(|(gull, _)| on_the_sand(gull))
        {
            let _ = writeln!(out, "steered: {gull} {by}");
        }
        for (by, row) in self.steering.taken.iter().enumerate() {
            for (victim, &points) in row.iter().enumerate() {
                if points > 0 {
                    let _ = writeln!(out, "stolen: {by} {victim} {points}");
                }
            }
        }
        out
    }

    /// Read a snapshot back, or say why it is not one.
    ///
    /// Strict where the level format is lenient: a snapshot is written by
    /// this build for this build, so a line it cannot read is a corrupt save
    /// rather than a hand edit to shrug at.
    pub fn parse_snapshot(text: &str) -> Result<Board, String> {
        let mut lines = text.lines().map(str::trim).filter(|l| !l.is_empty());
        match lines.next() {
            Some(HEADER) => {}
            Some(other) => return Err(format!("not a snapshot: {other:?}")),
            None => return Err("empty snapshot".to_string()),
        }
        let mut fields = Fields::default();
        for line in lines {
            let (key, value) = line
                .split_once(':')
                .ok_or_else(|| format!("no key in {line:?}"))?;
            fields.read(key.trim(), value.trim())?;
        }
        fields.build()
    }
}

/// A snapshot's lines, gathered before any of them is trusted.
///
/// The lines `to_snapshot` always writes are all `Option` here and all
/// unwrapped in [`Fields::build`]: defaulting one turns a truncated save
/// into a board that parses and plays differently.
#[derive(Default)]
struct Fields {
    size: Option<(u8, u8)>,
    seed: Option<u64>,
    rng: Option<(u64, u64)>,
    tick: Option<u64>,
    rule: Option<(CapPolicy, u8)>,
    counters: Option<(u64, u32, u32, u32, u32)>,
    scores: Option<[u32; MAX_PLAYERS]>,
    gull_period: Option<u32>,
    gull_cap: Option<u8>,
    gull_turnover: bool,
    golden_every: u32,
    timed_lock: bool,
    sweep_flight: bool,
    whole_flock: bool,
    sweep_keeps_worth: bool,
    fair_spawns: bool,
    sweeping: Vec<Sweeping>,
    golden_call: Option<(u64, u8, u8)>,
    round_length: Option<u32>,
    wrap: bool,
    /// Stored the way the wire stores it, because `Default` here has to
    /// mean "the line was absent". Castle raids are the one board switch
    /// that is *on* by default, so a `castle_raids: bool` deriving `false`
    /// would turn them off in every snapshot that omitted the line.
    no_castle_raids: bool,
    claw_hands: Option<[u8; 2]>,
    events_enabled: bool,
    lure: Option<(PlayerId, u32)>,
    lure_cooldown: u32,
    event_cooldown: u32,
    mania: Option<(Mania, u32)>,
    tempo: Option<(Tempo, u32)>,
    claw_call: u32,
    last_event: Option<(TideEvent, u64)>,
    hands: [Option<(u16, u64)>; MAX_PLAYERS],
    h_walls: Option<Vec<bool>>,
    v_walls: Option<Vec<bool>>,
    tiles: Option<Vec<TileKind>>,
    posts: Vec<(usize, Signpost)>,
    crabs: Vec<Crab>,
    gulls: Vec<Gull>,
    incoming: Vec<IncomingGull>,
    steering: steering::Steering,
}

impl Fields {
    /// Take one `key: value` line.
    fn read(&mut self, key: &str, value: &str) -> Result<(), String> {
        let mut words = value.split_whitespace();
        match key {
            "size" => {
                let w = next_num::<u8>(&mut words, "size width")?;
                let h = next_num::<u8>(&mut words, "size height")?;
                if w == 0 || h == 0 {
                    return Err("a board is at least 1x1".to_string());
                }
                self.size = Some((w, h));
            }
            "seed" => self.seed = Some(next_num(&mut words, "seed")?),
            "rng" => {
                let state = next_num(&mut words, "rng state")?;
                self.rng = Some((state, next_num(&mut words, "rng inc")?));
            }
            "tick" => self.tick = Some(next_num(&mut words, "tick")?),
            "rule" => {
                let token = words.next().ok_or("rule: missing policy")?;
                let policy = CapPolicy::from_token(token)
                    .ok_or_else(|| format!("rule: bad policy {token:?}"))?;
                let cap = next_num(&mut words, "rule cap")?;
                if cap == 0 && policy == CapPolicy::Evict {
                    return Err("rule: evict needs a cap of at least 1".to_string());
                }
                self.rule = Some((policy, cap));
            }
            "counters" => {
                self.counters = Some((
                    next_num(&mut words, "signpost_seq")?,
                    next_num(&mut words, "next_crab_id")?,
                    next_num(&mut words, "next_gull_id")?,
                    next_num(&mut words, "crabs_banked")?,
                    next_num(&mut words, "golden_banked")?,
                ));
            }
            "scores" => {
                let mut seats = [0u32; MAX_PLAYERS];
                for (seat, slot) in seats.iter_mut().enumerate() {
                    *slot = next_num(&mut words, "score")
                        .map_err(|e| format!("{e} for seat {seat}"))?;
                }
                self.scores = Some(seats);
            }
            "gull_period" => self.gull_period = Some(next_num(&mut words, "gull_period")?),
            "gull_cap" => self.gull_cap = Some(next_num(&mut words, "gull_cap")?),
            "gull_turnover" => self.gull_turnover = value == "on",
            "golden_every" => {
                self.golden_every = golden_every(next_num(&mut words, "golden_every")?)?;
            }
            "timed_lock" => self.timed_lock = value == "on",
            "sweep_flight" => self.sweep_flight = value == "on",
            "whole_flock" => self.whole_flock = value == "on",
            "sweep_keeps_worth" => self.sweep_keeps_worth = value == "on",
            "fair_spawns" => self.fair_spawns = value == "on",
            "golden_call" => {
                self.golden_call = Some((
                    next_num(&mut words, "golden_call tick")?,
                    next_num(&mut words, "golden_call x")?,
                    next_num(&mut words, "golden_call y")?,
                ));
            }
            "round" => self.round_length = Some(next_num(&mut words, "round")?),
            "wrap" => self.wrap = value == "on",
            "raids" => self.no_castle_raids = value == "off",
            "claw_hands" => {
                self.claw_hands = Some([
                    next_num(&mut words, "claw_hands left")?,
                    next_num(&mut words, "claw_hands right")?,
                ]);
            }
            "events" => self.events_enabled = value == "on",
            "lure" => {
                // A seat, like every other owner the snapshot names: the
                // sim shrugs off a lure for nobody, but the round's tally
                // keeps one per seat and indexed it when the lure closed.
                let owner = next_num::<PlayerId>(&mut words, "lure owner")?;
                if seat(owner).is_none() {
                    return Err(format!("lure owner: no seat {owner}"));
                }
                self.lure = Some((owner, ticks_left(&mut words, "lure")?));
            }
            "cooldown" => self.lure_cooldown = next_num(&mut words, "cooldown")?,
            "event_cooldown" => {
                self.event_cooldown = next_num(&mut words, "event_cooldown")?;
            }
            "mania" => {
                let which = words.next().ok_or("mania: missing kind")?;
                let kind = match which {
                    "crab" => Mania::Crab,
                    "gull" => Mania::Gull,
                    other => return Err(format!("mania: bad kind {other:?}")),
                };
                self.mania = Some((kind, ticks_left(&mut words, "mania")?));
            }
            "tempo" => {
                let which = words.next().ok_or("tempo: missing speed")?;
                let shift = match which {
                    "fast" => Tempo::Fast,
                    "slow" => Tempo::Slow,
                    other => return Err(format!("tempo: bad speed {other:?}")),
                };
                self.tempo = Some((shift, ticks_left(&mut words, "tempo")?));
            }
            "claw_call" => self.claw_call = next_num::<u32>(&mut words, "claw_call")?,
            "last_event" => {
                let index = next_num::<usize>(&mut words, "last_event index")?;
                let event = *TideEvent::ALL
                    .get(index)
                    .ok_or_else(|| format!("last_event: no event {index}"))?;
                self.last_event = Some((event, next_num(&mut words, "last_event tick")?));
            }
            "hand" => {
                let seat = next_num::<usize>(&mut words, "hand seat")?;
                let tile = next_num(&mut words, "hand tile")?;
                let at = next_num(&mut words, "hand tick")?;
                *self
                    .hands
                    .get_mut(seat)
                    .ok_or_else(|| format!("hand: no seat {seat}"))? = Some((tile, at));
            }
            "hwalls" => self.h_walls = Some(hex_to_bits(value)?),
            "vwalls" => self.v_walls = Some(hex_to_bits(value)?),
            "tiles" => {
                self.tiles = Some(
                    value
                        .split_whitespace()
                        .map(tile_from_token)
                        .collect::<Result<_, _>>()?,
                );
            }
            "post" => self.posts.push(parse_post(&mut words)?),
            "crab" => self.crabs.push(parse_crab(&mut words)?),
            "sweeping" => {
                let owner: PlayerId = next_num(&mut words, "sweeping owner")?;
                if usize::from(owner) >= MAX_PLAYERS {
                    return Err(format!("sweeping: no seat {owner}"));
                }
                let launch = next_num(&mut words, "sweeping launch")?;
                let lands = next_num(&mut words, "sweeping lands")?;
                if lands < launch {
                    return Err(format!(
                        "sweeping: lands at {lands}, before it leaves at {launch}"
                    ));
                }
                let crab = parse_crab(&mut words)?;
                let claw_call = match words.next() {
                    None => false,
                    Some("claws") => true,
                    Some(other) => return Err(format!("sweeping: bad call {other:?}")),
                };
                self.sweeping.push(Sweeping {
                    crab,
                    owner,
                    launch,
                    lands,
                    claw_call,
                });
            }
            "gull" => self.gulls.push(parse_gull(&mut words)?),
            "incoming" => self.incoming.push(IncomingGull {
                at: next_num(&mut words, "incoming tick")?,
                tile: next_num(&mut words, "incoming tile")?,
                dir: next_dir(&mut words, "incoming direction")?,
            }),
            "steered" => {
                let gull = next_num(&mut words, "steered gull")?;
                let by: PlayerId = next_num(&mut words, "steered seat")?;
                if seat(by).is_none() {
                    return Err(format!("steered: no seat {by}"));
                }
                if self.steering.steerer(gull).is_some() {
                    return Err(format!("steered: gull {gull} twice"));
                }
                if self.steering.by_gull.len() >= MAX_CREATURES {
                    return Err(format!("more than {MAX_CREATURES} steered gulls"));
                }
                self.steering.steer(gull, by);
            }
            "stolen" => {
                let by: PlayerId = next_num(&mut words, "stolen seat")?;
                let victim: PlayerId = next_num(&mut words, "stolen victim")?;
                let (Some(by), Some(victim)) = (seat(by), seat(victim)) else {
                    return Err(format!("stolen: no seats {by} and {victim}"));
                };
                self.steering.taken[by][victim] = next_num(&mut words, "stolen points")?;
            }
            other => return Err(format!("unknown key {other:?}")),
        }
        // Counted as they come, so a code with a hundred thousand of them
        // is turned away at the first one too many rather than read whole.
        if self.crabs.len() + self.gulls.len() + self.sweeping.len() + self.incoming.len()
            > MAX_CREATURES
        {
            return Err(format!("more than {MAX_CREATURES} crabs and gulls"));
        }
        Ok(())
    }

    /// Everything gathered, checked against everything else, as a board.
    fn build(self) -> Result<Board, String> {
        let (width, height) = self.size.ok_or("snapshot has no size")?;
        let (rng_state, rng_inc) = self.rng.ok_or("snapshot has no rng")?;
        let (cap_policy, signpost_cap) = self.rule.ok_or("snapshot has no rule")?;
        let (signpost_seq, next_crab_id, next_gull_id, crabs_banked, golden_banked) =
            self.counters.ok_or("snapshot has no counters")?;
        let seed = self.seed.ok_or("snapshot has no seed")?;
        let tick = self.tick.ok_or("snapshot has no tick")?;
        let scores = self.scores.ok_or("snapshot has no scores")?;
        let gull_period = self.gull_period.ok_or("snapshot has no gull_period")?;
        let (w, h) = (width as usize, height as usize);
        let tiles = self.tiles.ok_or("snapshot has no tiles")?;
        if tiles.len() != w * h {
            return Err(format!("{} tiles for a {w}x{h} board", tiles.len()));
        }
        let h_walls = sized(
            self.h_walls.ok_or("snapshot has no hwalls")?,
            (h + 1) * w,
            "hwalls",
        )?;
        let v_walls = sized(
            self.v_walls.ok_or("snapshot has no vwalls")?,
            h * (w + 1),
            "vwalls",
        )?;
        let grid = Grid {
            width,
            height,
            h_walls,
            v_walls,
            tiles,
        };
        // From here on, what every tick leaves true (`check_invariants`)
        // is checked rather than trusted. A snapshot is text, carried in a
        // save file or a share code anybody can edit, and a board that
        // breaks one of these trips an assertion or overflows a counter a
        // tick after it loads: the parser refuses it instead.
        if self.wrap && grid.rim_walled() {
            return Err("a wall on the rim of an open beach".to_string());
        }
        if golden_banked > crabs_banked {
            return Err(format!(
                "{golden_banked} golden crabs banked of {crabs_banked} crabs"
            ));
        }
        // Each is added to on the next spawn, placement, bank or tick, by
        // more than one a tick (a golden call and a sweep are booked ticks
        // ahead, a flood spawns crabs by the handful), so a counter one
        // short of its type's end still overflows. Held to half of what a
        // `u32` counts, no round ever played gets near them, and the room
        // above is more than any round could use up.
        if tick > MAX_TICK
            || signpost_seq > u64::from(MAX_COUNT)
            || next_crab_id > MAX_COUNT
            || next_gull_id > MAX_COUNT
            || crabs_banked > MAX_COUNT
        {
            return Err("counters: no room left to count on".to_string());
        }
        let mut signposts = vec![None; w * h];
        let mut held = [0usize; MAX_PLAYERS];
        for (tile, post) in self.posts {
            let slot = signposts
                .get_mut(tile)
                .ok_or_else(|| format!("post: tile {tile} is off a {w}x{h} board"))?;
            if grid.tiles[tile] != TileKind::Empty {
                return Err(format!(
                    "post: tile {tile} is a {:?}, not sand",
                    grid.tiles[tile]
                ));
            }
            if post.seq >= signpost_seq {
                return Err(format!(
                    "post: seq {} is not behind the counter at {signpost_seq}",
                    post.seq
                ));
            }
            held[usize::from(post.owner)] += 1;
            if held[usize::from(post.owner)] > usize::from(signpost_cap) {
                return Err(format!(
                    "post: seat {} holds more than the cap of {signpost_cap}",
                    post.owner
                ));
            }
            *slot = Some(post);
        }
        let poses = |who: &str, tile: u16, progress: u16, prev: &Pose| {
            for (what, tile, progress) in [
                ("tile", tile, progress),
                ("prev_tile", prev.tile, prev.progress),
            ] {
                if usize::from(tile) >= w * h {
                    return Err(format!("{who} {what} {tile}, off the board"));
                }
                // A step is never as long as a tile, and the sim takes a
                // whole tile off before the tick ends.
                if progress >= SUBUNITS_PER_TILE {
                    return Err(format!("{who} progress {progress}, past a whole tile"));
                }
            }
            Ok(())
        };
        for crab in self
            .crabs
            .iter()
            .chain(self.sweeping.iter().map(|f| &f.crab))
        {
            poses("crab", crab.tile, crab.progress, &crab.prev)?;
        }
        for gull in &self.gulls {
            poses("gull", gull.tile, gull.progress, &gull.prev)?;
        }

        // A gull on its way in comes down on sand of this beach, on a tick
        // still to come and no further off than the spawner sends for one,
        // in the order the spawner sent: the sim lands them first to last
        // and never looks past the first.
        let mut last_at = tick;
        for gull in &self.incoming {
            let tile = usize::from(gull.tile);
            if tile >= w * h || matches!(grid.tiles[tile], TileKind::Rock | TileKind::Kelp) {
                return Err(format!("incoming: tile {tile} cannot take a gull"));
            }
            if gull.at < last_at || gull.at > tick + u64::from(GULL_LEAD) {
                return Err(format!(
                    "incoming: tick {} is out of turn (now {tick})",
                    gull.at
                ));
            }
            last_at = gull.at;
        }

        // A hand stands on this beach, and put its post down on a tick
        // already played.
        for (tile, at) in self.hands.iter().flatten() {
            if usize::from(*tile) >= w * h {
                return Err(format!("hand: tile {tile} is off a {w}x{h} board"));
            }
            if *at > tick {
                return Err(format!("hand: tick {at} is still to come ({tick})"));
            }
        }

        // A steered gull is one on the sand: the list forgets a gull on the
        // tick it leaves.
        for (gull, _) in &self.steering.by_gull {
            if !self.gulls.iter().any(|g| g.id == *gull) {
                return Err(format!("steered: no gull {gull}"));
            }
        }

        // A call names a spawner hole on this beach, or the crab it
        // promises has nowhere to come out.
        let golden_call = match self.golden_call {
            None => None,
            Some((at, x, y)) => {
                if x >= width || y >= height {
                    return Err(format!("golden_call: ({x},{y}) is off the beach"));
                }
                let tile = usize::from(y) * w + usize::from(x);
                if !matches!(grid.tiles[tile], TileKind::Spawner(_)) {
                    return Err(format!("golden_call: ({x},{y}) is not a spawner"));
                }
                // A call is only ever made on a board that calls them, and
                // goes out on the tick it names: one for a tick already
                // played would stay on the board, public, for the rest of
                // the round.
                if self.golden_every == 0 {
                    return Err("golden_call: this board calls no golden crabs".to_string());
                }
                if at < tick {
                    return Err(format!("golden_call: tick {at} is already past ({tick})"));
                }
                Some((at, tile as u16))
            }
        };

        // Named in full on purpose: a new `Board` field stops compiling here
        // until it is decided how, or whether, it survives a save.
        Ok(Board {
            grid,
            seed,
            signposts,
            rules: Rules {
                signpost_cap,
                cap_policy,
                gull_period,
                gull_cap: self.gull_cap.unwrap_or(GULL_CAP as u8),
                gull_turnover: self.gull_turnover,
                golden_every: self.golden_every,
                timed_lock: self.timed_lock,
                sweep_flight: self.sweep_flight,
                whole_flock: self.whole_flock,
                sweep_keeps_worth: self.sweep_keeps_worth,
                fair_spawns: self.fair_spawns,
                round_length: self.round_length,
                castle_raids: !self.no_castle_raids,
                claw_hands: self.claw_hands,
            },
            crabs: self.crabs,
            scores,
            rng: Pcg32::from_state(rng_state, rng_inc),
            tick,
            signpost_seq,
            next_crab_id,
            gulls: self.gulls,
            next_gull_id,
            incoming: self.incoming,
            lure: self.lure,
            lure_cooldown: self.lure_cooldown,
            crabs_banked,
            golden_banked,
            golden_call,
            wrap: self.wrap,
            tide: events::Tide {
                enabled: self.events_enabled,
                cooldown: self.event_cooldown,
                mania: self.mania,
                tempo: self.tempo,
                claw_call: self.claw_call,
                last: self.last_event,
                // The trophies' business, not the beach's: a snapshot
                // carries the rules and nothing else.
                spun_by: None,
                // Drained within the tick that fills it, so a snapshot
                // taken between ticks never has one to carry.
                queue: Vec::new(),
            },
            sweeps: Sweeps {
                in_air: self.sweeping,
                // News for the frame it happened on, and this is not that
                // frame: a round picked back up has no sweep to report.
                landed: Vec::new(),
            },
            // News for its own frame, like the landings above.
            refused_lures: Vec::new(),
            walked_home: Vec::new(),
            hands: self.hands,
            steering: self.steering,
        })
    }
}

/// A golden crab cadence the sim can keep: none, or long enough that the
/// call it draws lands on a tick still to come. Shared with the level
/// format, which reads the same key.
///
/// The call goes out a third of the stretch or more after the tick it is
/// drawn on, and is drawn after that tick's own check; a stretch of one or
/// two ticks has no third, so it called the tick it was drawn on, which
/// never comes round again, and the call hung on the board for good.
pub(crate) fn golden_every(ticks: u32) -> Result<u32, String> {
    match ticks {
        1..=2 => Err(format!(
            "golden_every: {ticks} is too short, 0 (off) or at least 3"
        )),
        _ => Ok(ticks),
    }
}

fn sized(bits: Vec<bool>, want: usize, what: &str) -> Result<Vec<bool>, String> {
    // The count the size implies, give or take the nibble the hex rounds
    // up to: fewer is a truncated save, a nibble or more over is a wall
    // map for another board, and reading the first `want` of that would
    // be walls for a beach this is not.
    if bits.len() < want || bits.len() >= want + 4 {
        return Err(format!("{what}: {} bits, wanted {want}", bits.len()));
    }
    let mut bits = bits;
    bits.truncate(want);
    Ok(bits)
}

fn next_num<T: std::str::FromStr>(
    words: &mut std::str::SplitWhitespace,
    what: &str,
) -> Result<T, String> {
    let word = words.next().ok_or_else(|| format!("{what}: missing"))?;
    word.parse()
        .map_err(|_| format!("{what}: bad number {word:?}"))
}

/// The ticks left on a running lure, mania or tempo. At least one: the
/// sim clears each of these the tick it reaches zero and never writes a
/// zero, and `tick` counts down before it looks, so a zero read back here
/// would count past the bottom on the first tick.
fn ticks_left(words: &mut std::str::SplitWhitespace, what: &str) -> Result<u32, String> {
    match next_num(words, &format!("{what} ticks"))? {
        0 => Err(format!("{what}: a running one has at least a tick left")),
        ticks => Ok(ticks),
    }
}

fn next_dir(words: &mut std::str::SplitWhitespace, what: &str) -> Result<Direction, String> {
    let word = words.next().ok_or_else(|| format!("{what}: missing"))?;
    Direction::from_letter(word).ok_or_else(|| format!("{what}: bad direction {word:?}"))
}

fn parse_post(words: &mut std::str::SplitWhitespace) -> Result<(usize, Signpost), String> {
    let tile = next_num::<usize>(words, "post tile")?;
    let dir = next_dir(words, "post direction")?;
    let owner = next_num::<PlayerId>(words, "post owner")?;
    if seat(owner).is_none() {
        return Err(format!("post owner: no seat {owner}"));
    }
    let word = words.next().ok_or("post health: missing")?;
    let health = match word {
        "full" => SignpostHealth::Full,
        "worn" => SignpostHealth::Worn,
        other => return Err(format!("post: bad health {other:?}")),
    };
    let seq = next_num(words, "post seq")?;
    let placed = next_num(words, "post placed")?;
    Ok((
        tile,
        Signpost {
            dir,
            owner,
            health,
            seq,
            placed,
        },
    ))
}

/// The three `prev` words of a creature line, in the order they are
/// written: tile, progress, direction.
fn parse_pose(words: &mut std::str::SplitWhitespace, who: &str) -> Result<Pose, String> {
    let tile = next_num(words, &format!("{who} prev_tile"))?;
    let progress = next_num(words, &format!("{who} prev_progress"))?;
    let dir = next_dir(words, &format!("{who} prev_dir"))?;
    Ok(Pose {
        tile,
        dir,
        progress,
    })
}

/// A crab as its line writes it, after the line's own key: the fields
/// [`parse_crab`] reads back, in its order. Shared by `crab:` and the crab
/// a `sweeping:` line carries, so the two cannot drift apart.
fn crab_fields(crab: &Crab) -> String {
    format!(
        "{} {} {} {} {} {} {} {} {}",
        crab.id,
        crab.tile,
        crab.dir.letter(),
        crab.progress,
        crab.prev.tile,
        crab.prev.progress,
        crab.prev.dir.letter(),
        crab.handed.token(),
        crab.kind.token()
    )
}

fn parse_crab(words: &mut std::str::SplitWhitespace) -> Result<Crab, String> {
    let id = next_num(words, "crab id")?;
    let tile = next_num(words, "crab tile")?;
    let dir = next_dir(words, "crab direction")?;
    let progress = next_num(words, "crab progress")?;
    let prev = parse_pose(words, "crab")?;
    let word = words.next().ok_or("crab handedness: missing")?;
    let handed =
        Handedness::from_token(word).ok_or_else(|| format!("crab: bad handedness {word:?}"))?;
    let word = words.next().ok_or("crab kind: missing")?;
    let kind = CrabKind::from_token(word).ok_or_else(|| format!("crab: bad kind {word:?}"))?;
    Ok(Crab {
        id,
        tile,
        dir,
        progress,
        prev,
        handed,
        kind,
    })
}

fn parse_gull(words: &mut std::str::SplitWhitespace) -> Result<Gull, String> {
    let id = next_num(words, "gull id")?;
    let tile = next_num(words, "gull tile")?;
    let dir = next_dir(words, "gull direction")?;
    let progress = next_num(words, "gull progress")?;
    let prev = parse_pose(words, "gull")?;
    let word = words.next().ok_or("gull handedness: missing")?;
    let handed =
        Handedness::from_token(word).ok_or_else(|| format!("gull: bad handedness {word:?}"))?;
    let word = words.next().ok_or("gull state: missing")?;
    let remaining = next_num(words, "gull flight remaining")?;
    let state = match word {
        "walk" => GullState::Walking,
        "fly" => GullState::Flying { remaining },
        other => return Err(format!("gull: bad state {other:?}")),
    };
    let takeoff_in = next_num(words, "gull takeoff_in")?;
    Ok(Gull {
        id,
        tile,
        dir,
        progress,
        prev,
        handed,
        state,
        takeoff_in,
    })
}

/// Walls as hex nibbles, least-significant bit first.
pub(crate) fn bits_to_hex(bits: &[bool]) -> String {
    bits.chunks(4)
        .map(|chunk| {
            let nibble = chunk
                .iter()
                .enumerate()
                .fold(0u32, |acc, (i, &bit)| acc | (u32::from(bit) << i));
            char::from_digit(nibble, 16).expect("a nibble is one hex digit")
        })
        .collect()
}

fn hex_to_bits(text: &str) -> Result<Vec<bool>, String> {
    let mut bits = Vec::with_capacity(text.len() * 4);
    for ch in text.chars() {
        let nibble = ch
            .to_digit(16)
            .ok_or_else(|| format!("walls: {ch:?} is not hex"))?;
        bits.extend((0..4).map(|i| nibble & (1 << i) != 0));
    }
    Ok(bits)
}

/// A tile as the snapshot writes it.
pub(crate) fn tile_token(kind: TileKind) -> String {
    match kind {
        TileKind::Empty => ".".to_string(),
        TileKind::Rock => "#".to_string(),
        TileKind::Castle(owner) => format!("c{owner}"),
        TileKind::Spawner(s) => format!("s{}{}", s.dir.letter(), s.period),
        TileKind::Turnstile { next_right: true } => "T".to_string(),
        TileKind::Turnstile { next_right: false } => "t".to_string(),
        TileKind::Kelp => "K".to_string(),
        TileKind::Pool => "~".to_string(),
    }
}

fn tile_from_token(token: &str) -> Result<TileKind, String> {
    match token {
        "." => Ok(TileKind::Empty),
        "#" => Ok(TileKind::Rock),
        "T" => Ok(TileKind::Turnstile { next_right: true }),
        "t" => Ok(TileKind::Turnstile { next_right: false }),
        "K" => Ok(TileKind::Kelp),
        "~" => Ok(TileKind::Pool),
        _ => {
            let (tag, rest) = token.split_at_checked(1).ok_or("empty tile token")?;
            match tag {
                "c" => {
                    let owner: PlayerId = rest
                        .parse()
                        .map_err(|_| format!("tile: bad castle owner in {token:?}"))?;
                    if seat(owner).is_none() {
                        return Err(format!("tile: no seat {owner}"));
                    }
                    Ok(TileKind::Castle(owner))
                }
                "s" => {
                    let (letter, period) = rest
                        .split_at_checked(1)
                        .ok_or_else(|| format!("tile: bad spawner {token:?}"))?;
                    let dir = Direction::from_letter(letter)
                        .ok_or_else(|| format!("tile: bad spawner direction in {token:?}"))?;
                    let period: u32 = period
                        .parse()
                        .map_err(|_| format!("tile: bad spawner period in {token:?}"))?;
                    if period == 0 {
                        return Err("tile: a spawner period is at least 1 tick".to_string());
                    }
                    Ok(TileKind::Spawner(Spawner { dir, period }))
                }
                _ => Err(format!("tile: unknown token {token:?}")),
            }
        }
    }
}

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

    /// A board with every field pushed off its default, including the three
    /// the fuzz loop never reaches, because a mania, a tempo shift and a
    /// recorded last event all need a sparkling crab banked.
    ///
    /// Reaches in and sets the private fields directly rather than playing
    /// toward them: the point is coverage of the *format*, and engineering
    /// a tide event to check one line would test the roulette instead.
    fn awkward_board() -> Board {
        let mut board = Board::new(5, 4, 0xABCD);
        board.set_tile(0, 0, TileKind::Castle(0));
        board.set_tile(4, 3, TileKind::Castle(1));
        board.set_tile(2, 1, TileKind::Rock);
        board.set_tile(1, 2, TileKind::Kelp);
        board.set_tile(3, 2, TileKind::Pool);
        board.set_tile(2, 2, TileKind::Turnstile { next_right: false });
        board.set_tile(
            0,
            2,
            TileKind::Spawner(Spawner {
                dir: Direction::Right,
                period: 37,
            }),
        );
        board.set_wrap(true);
        board.set_wall(1, 1, Direction::Up, true);
        board.rules_mut().castle_raids = false;
        board.rules_mut().gull_cap = 9;
        board.rules_mut().gull_turnover = true;
        board.rules_mut().timed_lock = true;
        board.rules_mut().sweep_flight = true;
        board.rules_mut().whole_flock = true;
        board.rules_mut().sweep_keeps_worth = true;
        board.rules_mut().fair_spawns = true;
        board.rules_mut().claw_hands = Some([2, 1]);
        board.set_events_enabled(true);
        board.rules_mut().round_length = Some(1234);
        board.rules_mut().gull_period = 97;
        board.set_signpost_rule(2, CapPolicy::Reject);
        board.set_score(0, 17);
        board.set_score(3, 4);

        board.rng = Pcg32::from_state(0x1234_5678_9ABC_DEF0, 0x0FED_CBA9_8765_4321);
        board.tick = 4321;
        board.signpost_seq = 99;
        board.next_crab_id = 7;
        board.next_gull_id = 3;
        board.crabs_banked = 12;
        board.golden_banked = 2;
        board.lure = Some((1, 145));
        board.hands[1] = Some((6, 300));
        board.lure_cooldown = 60;
        board.tide.cooldown = 210;
        board.tide.mania = Some((Mania::Gull, 88));
        board.tide.tempo = Some((Tempo::Slow, 44));
        board.tide.last = Some((TideEvent::FreshSand, 3000));
        board.signposts[6] = Some(Signpost {
            dir: Direction::Left,
            owner: 1,
            health: SignpostHealth::Worn,
            seq: 5,
            placed: 300,
        });
        board.crabs.push(Crab {
            id: 4,
            tile: 8,
            dir: Direction::Down,
            progress: 133,
            prev: Pose {
                tile: 3,
                dir: Direction::Right,
                progress: 200,
            },
            handed: Handedness::Right,
            kind: CrabKind::Golden,
        });
        board.gulls.push(Gull {
            id: 2,
            tile: 9,
            dir: Direction::Up,
            progress: 77,
            prev: Pose {
                tile: 14,
                dir: Direction::Left,
                progress: 12,
            },
            handed: Handedness::Left,
            state: GullState::Flying { remaining: 3 },
            takeoff_in: 222,
        });
        board.sweeps.launch(Sweeping {
            crab: Crab {
                id: 5,
                tile: 6,
                dir: Direction::Left,
                progress: 40,
                prev: Pose {
                    tile: 6,
                    dir: Direction::Left,
                    progress: 20,
                },
                handed: Handedness::Left,
                kind: CrabKind::Common,
            },
            owner: 1,
            launch: 4330,
            lands: 4360,
            claw_call: true,
        });
        board
    }

    #[test]
    fn a_board_with_everything_set_survives_a_snapshot() {
        let board = awkward_board();
        let text = board.to_snapshot();
        let back = Board::parse_snapshot(&text).expect("its own output");
        assert_eq!(
            back.state_hash(),
            board.state_hash(),
            "the snapshot came back a different board:\n{text}"
        );
        // The lines that only this test reaches are really being written,
        // rather than the hash matching because both sides dropped them.
        for expected in [
            "lure: 1 145",
            "cooldown: 60",
            "mania: gull 88",
            "tempo: slow 44",
            "last_event: 6 3000",
            "wrap: on",
            "raids: off",
            "events: on",
            "rule: reject 2",
            "gull_cap: 9",
            "gull_turnover: on",
            "timed_lock: on",
            "sweep_flight: on",
            "whole_flock: on",
            "sweep_keeps_worth: on",
            "fair_spawns: on",
            " common claws",
        ] {
            assert!(text.contains(expected), "missing {expected:?} in\n{text}");
        }
        // And the default direction, which is the one a missing line has to
        // mean: raids on writes nothing and must come back on.
        let mut raiding = awkward_board();
        raiding.rules_mut().castle_raids = true;
        let text = raiding.to_snapshot();
        assert!(
            !text.contains("raids:"),
            "a default is not written:\n{text}"
        );
        assert!(
            Board::parse_snapshot(&text)
                .expect("its own output")
                .rules()
                .castle_raids,
            "an absent raids line must read as raids on:\n{text}"
        );
        assert!(text.contains(" worn "), "the worn signpost:\n{text}");
        assert!(text.contains(" fly 3 "), "the gull mid-flight:\n{text}");
    }

    /// A snapshot from another build, or no snapshot at all, is refused
    /// rather than half-read into a board that plays differently.
    #[test]
    fn what_is_not_a_snapshot_is_refused() {
        let good = awkward_board().to_snapshot();
        assert!(Board::parse_snapshot("").is_err(), "empty");
        assert!(Board::parse_snapshot("hello").is_err(), "not a snapshot");
        assert!(
            Board::parse_snapshot(&good.replace(HEADER, "snapshot-v2")).is_err(),
            "another version"
        );
        assert!(
            Board::parse_snapshot(&good.replace("tiles:", "tyles:")).is_err(),
            "a key this build does not know"
        );
        assert!(
            Board::parse_snapshot(&good.replace("size: 5 4", "size: 6 4")).is_err(),
            "a tile count that does not fit the size"
        );
        // Values the sim never writes and could not run: an evict cap of
        // zero has nothing to evict on the first placement, and a timer
        // at zero counts past the bottom on the first tick.
        assert!(good.contains("rule: reject 2"), "{good}");
        assert!(
            Board::parse_snapshot(&good.replace("rule: reject 2", "rule: evict 0")).is_err(),
            "evict with nothing to evict"
        );

        // A post owned by a seat that does not exist would index the
        // score table past its end; a wall map longer than the board's
        // is a wall map for another board.
        let posted = good
            .lines()
            .find(|l| l.starts_with("post:"))
            .expect("a post");
        let orphan = posted.replace(" 1 ", " 9 ");
        assert_ne!(posted, orphan, "{posted}");
        assert!(Board::parse_snapshot(&good.replace(posted, &orphan)).is_err());
        let walls = good
            .lines()
            .find(|l| l.starts_with("hwalls:"))
            .expect("walls");
        assert!(Board::parse_snapshot(&good.replace(walls, &format!("{walls}f"))).is_err());
        for line in ["lure: 1 0", "mania: gull 0", "tempo: slow 0"] {
            let key = line.split(':').next().unwrap();
            let zeroed: String = good
                .lines()
                .map(|l| if l.starts_with(key) { line } else { l })
                .collect::<Vec<_>>()
                .join("\n");
            assert!(zeroed.contains(line), "{key} is set on the awkward board");
            assert!(
                Board::parse_snapshot(&zeroed).is_err(),
                "{line} should be refused"
            );
        }
        // A truncated save: every line but the header removed in turn.
        let lines: Vec<&str> = good.lines().collect();
        for drop in 1..lines.len() {
            let mut kept = lines.clone();
            let line = kept.remove(drop);
            // The optional round-state lines are absent at their defaults,
            // so dropping one is a legal (different) board, not a bad file.
            let optional = [
                "gull_cap:",
                "gull_turnover:",
                "golden_every:",
                "timed_lock:",
                "sweep_flight:",
                "whole_flock:",
                "sweep_keeps_worth:",
                "fair_spawns:",
                "sweeping:",
                "golden_call:",
                "round:",
                "wrap:",
                "raids:",
                "claw_hands:",
                "events:",
                "lure:",
                "cooldown:",
                "event_cooldown:",
                "mania:",
                "tempo:",
                "last_event:",
                "hand:",
                "post:",
                "crab:",
                "gull:",
            ];
            if optional
                .iter()
                .any(|key| line.trim_start().starts_with(key))
            {
                continue;
            }
            assert!(
                Board::parse_snapshot(&kept.join("\n")).is_err(),
                "dropping {line:?} should not still parse"
            );
        }
    }

    /// Replace the value of `key` in a snapshot, leaving the rest alone.
    fn bend(text: &str, key: &str, value: &str) -> String {
        text.lines()
            .map(|line| match line.starts_with(&format!("{key}:")) {
                true => format!("{key}: {value}"),
                false => line.to_string(),
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    /// A creature standing off the end of the board is refused where it
    /// arrives rather than where it is used, which would be the next tick,
    /// indexing a tile array that has no such tile.
    #[test]
    fn a_creature_standing_off_the_board_is_refused() {
        let good = awkward_board().to_snapshot();
        // 5x4, so tile 20 is one past the last one there is.
        for (what, from, to) in [
            ("crab", "crab: 4 8 ", "crab: 4 20 "),
            ("gull", "gull: 2 9 ", "gull: 2 20 "),
        ] {
            assert!(
                good.contains(from),
                "{what} is not where the fixture puts it:\n{good}"
            );
            let refused = Board::parse_snapshot(&good.replace(from, to))
                .expect_err("took a creature off the board");
            assert!(
                refused.contains("off the board"),
                "{what}: complained about something else: {refused}"
            );
        }
    }

    /// What every tick leaves true is checked on the way in, so a hand-made
    /// or damaged snapshot is refused by the parser rather than tripping an
    /// assertion, or overflowing a counter, a tick after it loads. Each
    /// bend below breaks exactly one of them, on a board that otherwise
    /// parses.
    #[test]
    fn a_snapshot_no_tick_could_leave_is_refused() {
        let good = awkward_board().to_snapshot();
        assert!(Board::parse_snapshot(&good).is_ok(), "the fixture parses");
        let post = "post: 6 L 1 worn 5 300";
        assert!(good.contains(post), "the fixture's post moved:\n{good}");
        let crab = "crab: 4 8 D 133 3 200";
        assert!(good.contains(crab), "the fixture's crab moved:\n{good}");
        let cases = [
            (
                "a post on a rock",
                good.replace(post, "post: 7 L 1 worn 5 300"),
            ),
            (
                "a post from the future",
                good.replace(post, "post: 6 L 1 worn 99 300"),
            ),
            (
                "posts over the cap",
                good.replace(
                    post,
                    &format!("{post}\npost: 1 U 1 full 6 300\npost: 2 U 1 full 7 300"),
                ),
            ),
            (
                "more gold than crabs",
                bend(&good, "counters", "99 7 3 1 2"),
            ),
            (
                "a crab id with no room",
                bend(&good, "counters", "99 4294967295 3 12 2"),
            ),
            (
                "a gull id with no room",
                bend(&good, "counters", "99 7 4294967295 12 2"),
            ),
            (
                "a post count with no room",
                bend(&good, "counters", "18446744073709551615 7 3 12 2"),
            ),
            (
                "a bank count with no room",
                bend(&good, "counters", "99 7 3 4294967295 2"),
            ),
            (
                "a clock with no room",
                bend(&good, "tick", "18446744073709551615"),
            ),
            (
                "a clock with no room for a call booked ahead",
                bend(&good, "tick", &(MAX_TICK + 1).to_string()),
            ),
            (
                "a crab id with no room for a flood",
                bend(&good, "counters", &format!("99 {} 3 12 2", MAX_COUNT + 1)),
            ),
            (
                "a bank count with no room for a flood",
                bend(&good, "counters", &format!("99 7 3 {} 2", MAX_COUNT + 1)),
            ),
            ("a lure for nobody", format!("{good}\nlure: 200 5")),
            ("a hand from the future", bend(&good, "hand", "1 6 5000")),
            ("a hand off the board", bend(&good, "hand", "1 20 300")),
            ("a hand for nobody", bend(&good, "hand", "6 6 300")),
            (
                "a crab past its tile",
                good.replace(crab, "crab: 4 8 D 256 3 200"),
            ),
            (
                "a crab past its last tile",
                good.replace(crab, "crab: 4 8 D 133 3 65535"),
            ),
            (
                "a crab from off the board",
                good.replace(crab, "crab: 4 8 D 133 20 200"),
            ),
        ];
        for (what, bent) in cases {
            assert_ne!(bent, good, "{what}: nothing was bent");
            assert!(
                Board::parse_snapshot(&bent).is_err(),
                "{what}: parsed anyway"
            );
        }
    }

    /// The counters are held well short of their type's end, not one
    /// short: a tick books calls and sweeps ahead of itself, and a flood
    /// spawns crabs by the handful. At the bound a board still loads, and
    /// plays a tick.
    #[test]
    fn a_snapshot_at_the_counters_bound_loads_and_plays() {
        let good = awkward_board().to_snapshot();
        let bent = bend(&good, "tick", &MAX_TICK.to_string());
        let bent = bend(
            &bent,
            "counters",
            &format!("99 {MAX_COUNT} {MAX_COUNT} {MAX_COUNT} 2"),
        );
        let mut board = Board::parse_snapshot(&bent).expect("at the bound parses");
        for _ in 0..30 {
            board.tick_idle();
        }
    }

    /// A snapshot holds no more crabs and gulls than a level may, counting
    /// the crabs in the air: a pasted code with a crowd past it is
    /// refused, not read whole and played.
    #[test]
    fn a_snapshot_with_a_crowd_past_the_cap_is_refused() {
        let good = awkward_board().to_snapshot();
        let crab = "crab: 4 8 D 133 3 200";
        let line = good
            .lines()
            .find(|l| l.starts_with(crab))
            .expect("the fixture's crab");
        let have = good
            .lines()
            .filter(|l| {
                ["crab:", "gull:", "sweeping:"]
                    .iter()
                    .any(|k| l.starts_with(k))
            })
            .count();
        let crowd = |n: usize| format!("{good}\n{}", format!("{line}\n").repeat(n));
        let err = Board::parse_snapshot(&crowd(MAX_CREATURES + 1 - have)).expect_err("one over");
        assert!(err.contains(&MAX_CREATURES.to_string()), "{err}");
    }

    /// The rim of an open beach takes no wall: the level format opens it
    /// when it reads `wrap: on`, and a wall on one side of the seam was a
    /// door that only shut one way. A snapshot is held to the same rule as
    /// every other way a board is built.
    #[test]
    fn an_open_beach_has_an_open_rim_whichever_way_it_is_built() {
        let mut board = Board::new(5, 4, 1);
        board.set_wrap(true);
        // The editor's way: a wall asked for on the rim is not stored.
        board.set_wall(0, 0, Direction::Up, true);
        board.set_wall(4, 2, Direction::Right, true);
        assert!(!board.wall_at(0, 0, Direction::Up));
        assert!(!board.wall_at(4, 2, Direction::Right));
        assert!(board.on_open_rim(0, 0, Direction::Up));
        assert!(!board.on_open_rim(1, 1, Direction::Up), "inside is a wall");
        // Inside the rim walls go up as ever, and come back from a save.
        board.set_wall(1, 1, Direction::Up, true);
        let back = Board::parse_snapshot(&board.to_snapshot()).expect("parses");
        assert!(back.wall_at(1, 1, Direction::Up));
        let level = crate::sim::Level::from_board("Open", 3, board.clone());
        let read = crate::sim::Level::parse(&level.to_text())
            .expect("parses")
            .board();
        assert!(
            read.wrap() && read.wall_at(1, 1, Direction::Up),
            "the level agrees"
        );
        assert!(!read.wall_at(0, 0, Direction::Up));

        // And a snapshot with one on the rim anyway is refused.
        let mut walled = board.clone();
        walled.grid.h_walls[0] = true;
        assert!(Board::parse_snapshot(&walled.to_snapshot()).is_err());

        // Closing the beach again walls the whole rim, as it always did.
        board.set_wrap(false);
        assert!(board.wall_at(0, 0, Direction::Up));
        assert!(!board.on_open_rim(0, 0, Direction::Up));
    }

    /// A number that is not one is not a zero. Read as a default, a code
    /// saying `tick: soon` would hand back a board that parses, plays, and
    /// disagrees with the one that was saved.
    #[test]
    fn a_number_that_is_not_one_is_refused_rather_than_defaulted() {
        let good = awkward_board().to_snapshot();
        for (key, junk) in [
            ("seed", "soon"),
            ("tick", "-1"),
            ("gull_period", "lots"),
            ("size", "5 wide"),
            ("rng", "1"),
            ("counters", "99 7 3 12"),
            ("scores", "17 0 0 x 0 0"),
        ] {
            let bent = bend(&good, key, junk);
            assert_ne!(bent, good, "{key}: no such line to bend");
            assert!(
                Board::parse_snapshot(&bent).is_err(),
                "{key}: took {junk:?} for a number"
            );
        }
    }

    /// The wall lattices travel as hex, four bits a digit, so a lattice
    /// whose length is not a multiple of four has a tail of padding that
    /// both halves have to agree to ignore.
    #[test]
    fn a_wall_lattice_survives_the_trip_through_hex() {
        for len in [0usize, 1, 3, 4, 5, 8, 17, 64] {
            let bits: Vec<bool> = (0..len).map(|i| i % 3 == 0).collect();
            let hex = bits_to_hex(&bits);
            let back = hex_to_bits(&hex).expect("its own hex reads back");
            assert!(back.len() >= len, "{len} bits came back as {}", back.len());
            assert_eq!(back[..len], bits[..], "{len} bits came back changed");
            assert!(
                back[len..].iter().all(|bit| !bit),
                "{len} bits padded with something other than sand: {hex}"
            );
        }
        assert!(hex_to_bits("nothex").is_err(), "took letters for digits");
    }

    /// Every tile kind writes a token only it writes and reads back as
    /// itself. A castle carries its owner in the token, so one that came
    /// back as another seat's would hand the round's points to a stranger.
    #[test]
    fn every_tile_kind_survives_its_own_token() {
        let mut kinds = vec![
            TileKind::Empty,
            TileKind::Rock,
            TileKind::Kelp,
            TileKind::Pool,
            TileKind::Turnstile { next_right: true },
            TileKind::Turnstile { next_right: false },
        ];
        for owner in 0..MAX_PLAYERS as u8 {
            kinds.push(TileKind::Castle(owner));
        }
        let mut seen: Vec<String> = Vec::new();
        for kind in kinds {
            let token = tile_token(kind);
            assert_eq!(
                tile_from_token(&token).expect("its own token reads back"),
                kind,
                "{kind:?} came back as something else"
            );
            assert!(
                !seen.contains(&token),
                "{kind:?} shares the token {token:?} with something else"
            );
            seen.push(token);
        }
        assert!(
            tile_from_token("~~~").is_err(),
            "took a token nobody writes"
        );
        assert!(tile_from_token("").is_err(), "took an empty token");
    }

    /// A beach two hundred ticks into a round with three tide events live
    /// at once: a crab mania, a claw call and a quickened tempo.
    fn stirred() -> Board {
        use crate::sim::{
            BotLevel, MAX_PLAYERS, PlayerAction, TideEvent, bot_action, generate_arena,
        };
        let mut board = generate_arena(3, 2, 8, 6);
        for _ in 0..200 {
            let actions: [PlayerAction; MAX_PLAYERS] =
                std::array::from_fn(|seat| bot_action(&board, seat as u8, BotLevel::Hard));
            board.tick(&actions);
        }
        board.force_tide_event(TideEvent::CrabMania, 0);
        board.force_tide_event(TideEvent::RightClaws, 0);
        board.force_tide_event(TideEvent::SpeedUp, 0);
        board
    }

    /// Every live event is written out and read back: a round resumed or a
    /// watcher caught up mid-mania plays the mania out, rather than a beach
    /// that has quietly calmed down and hashes differently from the table.
    #[test]
    fn live_tide_events_survive_a_snapshot() {
        let board = stirred();
        let text = board.to_snapshot();
        for line in ["mania: crab", "claw_call:", "tempo: fast"] {
            assert!(text.contains(line), "{line} is written: {text}");
        }
        let back = Board::parse_snapshot(&text).expect("reads back");
        assert_eq!(back.state_hash(), board.state_hash());
        assert_eq!(back.to_snapshot(), text);
    }

    /// A golden crab call no tick will ever send out is refused: one for a
    /// tick already played, one on a board that calls none, and a cadence
    /// too short to call a tick still to come. Each would sit on the
    /// board, public, for the rest of the round.
    #[test]
    fn a_golden_call_that_can_never_come_out_is_refused() {
        let mut board = Board::new(9, 7, 11);
        board.set_tile(1, 1, TileKind::Castle(0));
        board.set_tile(
            0,
            3,
            TileKind::Spawner(Spawner {
                dir: Direction::Right,
                period: 9,
            }),
        );
        board.rules_mut().golden_every = 600;
        for _ in 0..10 {
            board.tick_idle();
        }
        let good = board.to_snapshot();
        assert!(Board::parse_snapshot(&good).is_ok(), "the fixture parses");
        assert!(good.contains("golden_call: "), "a call to bend:\n{good}");
        let cases = [
            (bend(&good, "golden_call", "9 0 3"), "already past"),
            (
                good.lines()
                    .filter(|line| !line.starts_with("golden_every:"))
                    .collect::<Vec<_>>()
                    .join("\n"),
                "calls no golden crabs",
            ),
            (bend(&good, "golden_every", "2"), "too short"),
            (bend(&good, "golden_every", "1"), "too short"),
        ];
        for (broken, why) in cases {
            let err = Board::parse_snapshot(&broken).expect_err(why);
            assert!(err.contains(why), "{why}: {err}");
        }
        // The call for the very next tick is still to come, and kept.
        let next = bend(&good, "golden_call", "10 0 3");
        assert!(Board::parse_snapshot(&next).is_ok(), "{next}");
        assert!(Board::parse_snapshot(&bend(&good, "golden_every", "3")).is_ok());
    }

    /// Each field the parser checks refuses a value it cannot mean, with
    /// the field's name, rather than defaulting it into a different beach.
    #[test]
    fn a_field_that_cannot_mean_anything_is_refused_by_name() {
        let text = stirred().to_snapshot();
        let first_post = text
            .lines()
            .find(|line| line.starts_with("post: "))
            .expect("posts on the beach")
            .to_string();
        let cases: [(String, &str); 7] = [
            (text.replacen("size: 9 7", "size: 0 7", 1), "at least 1x1"),
            (text.replacen("mania: crab", "mania: sand", 1), "bad kind"),
            (text.replacen("tempo: fast", "tempo: warp", 1), "bad speed"),
            (
                text.lines()
                    .filter(|line| !line.starts_with("vwalls:"))
                    .collect::<Vec<_>>()
                    .join("\n"),
                "no vwalls",
            ),
            (
                text.replacen(&first_post, &first_post.replacen(" full ", " torn ", 1), 1),
                "bad health",
            ),
            (text.replacen(" c0 ", " c9 ", 1), "no seat"),
            (text.replacen("sD94", "sD0", 1), "at least"),
        ];
        for (broken, why) in cases {
            assert_ne!(broken, text, "the case changed something ({why})");
            let err = Board::parse_snapshot(&broken).expect_err(why);
            assert!(err.contains(why), "{why}: {err}");
        }
    }
}