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
//! Text level format and puzzle rules (spec ยง5.1).
//!
//! A level file has key/value header lines, then a `map:` section, e.g.:
//!
//! ```text
//! name: First Steps
//! posts: 1
//! crab: 0,1 R L common
//! solution: 3,1 U
//! map:
//! +-+-+-+-+
//! |. . . 0|
//! + +-+ + +
//! |. .|. .|
//! +-+-+-+-+
//! ```
//!
//! The map is a half-resolution lattice: tile `(x, y)` sits at lattice
//! `(2x+1, 2y+1)`; the character between two tiles is their shared wall
//! (`-`/`|` wall, anything else open). Tile characters: `.` sand, `#` rock,
//! `0`-`5` castle of that player (any seat below `MAX_PLAYERS`). Crabs and spawners are header lines, not
//! map characters, because they carry more data than one character holds:
//! `crab: x,y DIR HAND KIND` and `spawner: x,y DIR period`.
//!
//! Puzzles are played with a fixed signpost inventory (`posts:`) under
//! `CapPolicy::Reject`, and won when every crab has banked. `solution:` lines
//! are machine-checked by tests, so a level that ships is a level that is
//! solvable.
//!
//! `kind: puzzle|arena` says which of the two a level is (see [`LevelKind`]),
//! and so which list it joins. Files written before the editor had that
//! toggle leave it out, and are read off their castles.

mod format;

use crate::sim::board::{ArenaProblem, Board, CapPolicy};
use crate::sim::solve::Placement;

/// Sim ticks a puzzle may run before it counts as failed (60 s at 30 Hz).
/// Generous: it exists to catch crabs orbiting forever, not to add pressure.
pub const PUZZLE_TICK_LIMIT: u64 = 60 * crate::sim::TICKS_PER_SECOND as u64;

#[derive(Clone, Debug)]
pub struct Level {
    pub name: String,
    /// Signpost inventory for the puzzle.
    pub posts: u8,
    /// One known solution; validated by tests.
    pub solution: Vec<Placement>,
    pub goal: Goal,
    /// What the level is for: a stage to solve alone, or a beach to fight
    /// over. The author chooses it in the editor and it decides which of
    /// the two lists the level joins.
    pub kind: LevelKind,
    board: Board,
    crab_count: u32,
    /// True when the level text carried an explicit `rule:` line (versus
    /// replays); otherwise `board()` applies puzzle rules from `posts`.
    explicit_rule: bool,
    /// Where a level keeps its cleared tick when not under its name: a
    /// player's own level by its file, set by whoever read it off the
    /// shelf, and a shipped co-op stage under its ladder's key
    /// ([`crate::sim::coop_progress_key`]). `None` for a Tide Pool stage,
    /// and for one from a code or the editor's bench: those are filed by
    /// name.
    pub filing: Option<Filing>,
    /// The tables a versus beach is built for (`seats: 2 4 6`), smallest
    /// first; empty for any table its castles seat. A beach whose castles
    /// stand in opposite pairs is fair only at a table that fills whole
    /// pairs: with the top castle put away for a table of three, the
    /// castle across from the empty corner won 45-58% over thousands of
    /// rounds. So a map can say which tables it is for, and the others
    /// play a generated beach.
    pub tables: Vec<u8>,
    /// On an open beach built of identical strips, the strip's width in
    /// columns (`roll: 7`), 0 for none: each round rolls the beach round by
    /// a whole number of strips ([`crate::sim::Orientation::for_round`]),
    /// so which castle sits by the seam moves from round to round.
    pub roll: u8,
}

/// What a level files its cleared tick under, where its name will not
/// do: a player's level from the shelf, and a shipped co-op stage.
///
/// Not a shelf level's name: two files may carry the same one, and the stage list
/// tells them apart by renaming all but the first "X (2)" in file order,
/// so a new file sorting first took the tick of the one that had it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Filing {
    /// The key the tick is kept under, made from the file the level was
    /// read from.
    pub key: String,
    /// The name its tick was kept under before files had keys, where that
    /// name could only have meant this level; `None` where it could have
    /// meant another of the same name.
    pub legacy: Option<String>,
}

/// What a level was built to be.
///
/// The two want opposite things of a beach: a puzzle wants one bank and a
/// route to it, an arena wants a castle per seat and crabs arriving
/// forever. A file that does not say which has to be guessed at, and
/// guessing put a versus beach in the middle of the campaign.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum LevelKind {
    /// A stage for one player: route every crab home with the signposts the
    /// level grants. Joins the Tide Pool list.
    #[default]
    Puzzle,
    /// A beach for a match: a castle for each seat. Joins the map dial in
    /// Turf War and the lobby.
    Arena,
}

impl LevelKind {
    pub fn token(self) -> &'static str {
        match self {
            LevelKind::Puzzle => "puzzle",
            LevelKind::Arena => "arena",
        }
    }

    pub fn from_token(token: &str) -> Option<LevelKind> {
        match token {
            "puzzle" => Some(LevelKind::Puzzle),
            "arena" => Some(LevelKind::Arena),
            _ => None,
        }
    }
}

/// What a stage asks of the player. `AllCrabs` is classic puzzle mode; the
/// rest are goals a stage may state instead (`goal:`), each judged by
/// [`Level::outcome`].
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum Goal {
    /// Every crab that ever exists must bank (spec ยง5.1).
    #[default]
    AllCrabs,
    /// Bank at least this many crabs before the tide.
    Bank(u32),
    /// No crab may be eaten before the tide comes in.
    Survive,
    /// Bank a golden crab before the tide.
    Golden,
}

impl Goal {
    /// Whether winning means no crab was lost: every one banked, or none
    /// eaten. A stage asking for a number of them, or for the golden one,
    /// can be won with crabs given to the gulls, sometimes on purpose.
    pub fn saves_every_crab(self) -> bool {
        match self {
            Goal::AllCrabs | Goal::Survive => true,
            Goal::Bank(_) | Goal::Golden => false,
        }
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum PuzzleOutcome {
    Running,
    Won,
    /// Some crab is still loose at the tick limit.
    Lost,
}

impl Level {
    /// A fresh board for this level. Puzzle levels get fixed-inventory rules
    /// from `posts`; levels carrying an explicit `rule:` (recorded versus
    /// matches) keep the rule the match was played under.
    ///
    /// An arena that states no rule keeps the board's own, which is the
    /// versus one: `posts:` says how many the *author* had to hand, not how
    /// a match is played on it, and read as a rule it gives a table three
    /// signposts each and no way to replace them.
    pub fn board(&self) -> Board {
        let mut board = self.board.clone();
        if !self.explicit_rule && self.kind == LevelKind::Puzzle {
            board.set_signpost_rule(self.posts, CapPolicy::Reject);
            // A campaign puzzle's castle is the finish line, not a bank to
            // be robbed: see `Rules::castle_raids`.
            board.rules_mut().castle_raids = false;
        }
        board
    }

    /// [`Level::board`] on a fresh random stream: the same beach, built
    /// again from `seed`. A versus round on a beach somebody made draws a
    /// seed like any other, or every round on it replayed the file's one
    /// stream: the same spawn kinds, the same gull entry points, and the
    /// AI's same moments to think.
    ///
    /// Built again rather than reseeded in place, because placing the
    /// level's own gulls draws from the stream: a board whose seed was
    /// swapped afterwards would not be the one its replay rebuilds from
    /// the seed it records.
    pub fn board_seeded(&self, seed: u64) -> Board {
        match Level::parse_at(&self.to_text(), Some(seed)) {
            Ok(level) => level.board(),
            Err(e) => {
                debug_assert!(false, "{:?} does not read back: {e}", self.name);
                self.board()
            }
        }
    }

    /// The board a table of `seats` plays this beach on, on the round's
    /// `seed`: castles for seats past the table put away
    /// ([`Board::retire_castles_from`]). The one way a handmade beach
    /// becomes a round's board, on the couch, online and in the bot
    /// tools alike, so every peer builds the same one and the replay
    /// records it.
    pub fn table_board(&self, seed: u64, seats: u8) -> Board {
        let mut board = self.board_seeded(seed);
        board.retire_castles_from(seats);
        board
    }

    /// Whether a table of `seats` can play this beach: a castle for every
    /// seat, no owner skipped ([`Board::table_seats`]), and one of the
    /// tables it names if it names any ([`Level::tables`]). Castles for
    /// more players than sit down are fine, and put away when the board is
    /// built ([`Level::table_board`]).
    pub fn fits(&self, seats: u8) -> bool {
        self.table_seats().is_some_and(|castles| castles >= seats)
            && (self.tables.is_empty() || self.tables.contains(&seats))
    }

    /// See [`Board::table_seats`].
    pub fn table_seats(&self) -> Option<u8> {
        self.board.table_seats()
    }

    /// See [`Board::arena_problem`].
    pub fn arena_problem(&self) -> Option<ArenaProblem> {
        self.board.arena_problem()
    }

    pub fn crab_count(&self) -> u32 {
        self.crab_count
    }

    /// What the level's cleared tick is kept under: its [`Filing`] key for
    /// a player's level off the shelf, else its name.
    pub fn progress_key(&self) -> &str {
        self.filing
            .as_ref()
            .map_or(self.name.as_str(), |filing| filing.key.as_str())
    }

    /// Say what the level is for. The editor's toggle is authoritative: a
    /// level saved as a puzzle stays one however many castles it grew.
    pub fn with_kind(mut self, kind: LevelKind) -> Level {
        self.kind = kind;
        self
    }

    /// How many seats the beach could hold: one castle each, counted by
    /// owner. What the map dial checks a handmade beach against, and what
    /// tells a level with no `kind:` line of its own what it must be.
    pub fn seats(&self) -> u8 {
        self.board.castle_seats()
    }

    /// Run `board` idle until the goal is decided, and say when it was.
    ///
    /// [`Level::outcome`] is what makes it terminate: every goal loses or
    /// wins by the board's [`Level::deadline`], so the loop needs no guard
    /// of its own.
    pub fn play_out(&self, board: &mut Board) -> (PuzzleOutcome, u64) {
        loop {
            board.tick_idle();
            match self.outcome(board) {
                PuzzleOutcome::Running => {}
                done @ (PuzzleOutcome::Won | PuzzleOutcome::Lost) => return (done, board.ticks()),
            }
        }
    }

    /// Place the authored solution on `board`, each arrow by the hand the
    /// file names (seat 0 unless a co-op stage says P2's). `Err` names the
    /// first placement the board refused, which on a shipped level is a
    /// broken level file and never something to shrug off.
    pub fn place_solution(&self, board: &mut Board) -> Result<(), Placement> {
        for &(x, y, dir, seat) in &self.solution {
            if !board.place_signpost(seat, x, y, dir) {
                return Err((x, y, dir, seat));
            }
        }
        Ok(())
    }

    /// The two hands of a co-op stage, `[P1, P2]`: how many claw-keyed
    /// arrows each player has ([`crate::sim::Rules::claw_hands`]). `None`
    /// on every other level. Read off the board's own rule, so the level
    /// and the beach it builds cannot disagree.
    pub fn hands(&self) -> Option<[u8; 2]> {
        self.board.rules().claw_hands
    }

    /// Whether this is a co-op stage: one played by two, each with a hand
    /// of claw-keyed arrows.
    pub fn is_coop(&self) -> bool {
        self.hands().is_some()
    }

    /// The same level with its arrows dealt again: `Some` hands make it a
    /// co-op stage granting their sum, `None` a solo one granting `posts`.
    /// What the co-op guards and the editor's check try a level under:
    /// every arrow in one hand, or every arrow turning every crab.
    pub fn with_hands(&self, hands: Option<[u8; 2]>, posts: u8) -> Level {
        let mut level = self.clone();
        level.board.rules_mut().claw_hands = hands;
        level.posts = hands.map_or(posts, |[left, right]| left.saturating_add(right));
        if level.explicit_rule {
            let policy = level.board.signpost_rule().1;
            level.board.set_signpost_rule(level.posts, policy);
        }
        level.solution.clear();
        level
    }

    /// A fresh board with the authored solution standing on it.
    pub fn solved_board(&self) -> Result<Board, Placement> {
        let mut board = self.board();
        self.place_solution(&mut board)?;
        Ok(board)
    }

    /// The tick by which every goal on `board` is decided: its own round
    /// when it carries one, else [`PUZZLE_TICK_LIMIT`], which stands in for
    /// a stage with no timer, which would otherwise never end. One answer
    /// for the outcome, the solver's scan and the clock, so a stage that
    /// states a longer round is not cut off at the limit anyway.
    pub fn deadline(board: &Board) -> u64 {
        board
            .rules()
            .round_length
            .map_or(PUZZLE_TICK_LIMIT, u64::from)
    }

    /// Win/loss state of a board created by [`Level::board`], judged by the
    /// level's goal. All goals use banked-count accounting (spec ยง5.1: a
    /// crab a gull ate is a loss for AllCrabs/Survive, never a quiet
    /// disappearance). [`Level::deadline`] is the clock it is judged on.
    pub fn outcome(&self, board: &Board) -> PuzzleOutcome {
        // A crab Crab Monopoly is carrying home is off the beach but not
        // eaten: it banks when it lands.
        let alive = (board.crabs().len() + board.sweeping().len()) as u32;
        let eaten = board.crabs_banked() + alive < board.crabs_spawned();
        let timed_out = board.ticks() >= Self::deadline(board);
        // What each goal counts as already lost, and as already won. Losing
        // is checked first: a goal met on the same tick a crab was eaten does
        // not save an AllCrabs or Survive stage.
        let (lost, won) = match self.goal {
            Goal::AllCrabs => (
                eaten,
                alive == 0 && board.crabs_banked() == board.crabs_spawned(),
            ),
            Goal::Bank(n) => (false, board.crabs_banked() >= n),
            // Survive is the one goal the clock is *for*: running it out is
            // the win (see `deadline` for which clock).
            Goal::Survive => (eaten, timed_out),
            Goal::Golden => (false, board.golden_banked() >= 1),
        };
        if lost {
            PuzzleOutcome::Lost
        } else if won {
            PuzzleOutcome::Won
        } else if timed_out {
            // Every other goal loses when the tide beats it to the finish.
            PuzzleOutcome::Lost
        } else {
            PuzzleOutcome::Running
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::sim::direction::Direction;

    #[test]
    fn parse_rejects_bad_tile_chars() {
        let text = "name: Bad\nposts: 1\nmap:\n+-+\n|X|\n+-+\n";
        let err = Level::parse(text).unwrap_err();
        assert!(err.contains("bad tile char"), "{err}");
    }

    #[test]
    fn parse_rejects_unknown_keys() {
        let text = "name: Bad\nwibble: 3\nmap:\n+-+\n|.|\n+-+\n";
        let err = Level::parse(text).unwrap_err();
        assert!(err.contains("unknown key"), "{err}");
    }

    #[test]
    fn parse_rejects_malformed_solutions_and_directions() {
        let text = "name: Bad\nposts: 1\nsolution: 0,0 Q\nmap:\n+-+\n|.|\n+-+\n";
        assert!(Level::parse(text).is_err());
        let text = "name: Bad\nposts: 1\nsolution: zero,0 U\nmap:\n+-+\n|.|\n+-+\n";
        assert!(Level::parse(text).is_err());
    }

    /// A degenerate lattice is refused, not asserted against: `parse` reads
    /// text a stranger wrote (a pasted level code, a hand-edited custom
    /// level) and both callers handle the error. Checking odd-sized alone
    /// let a lone border line through as a zero-sized board, which
    /// `Board::new` met with a panic.
    #[test]
    fn parse_rejects_a_map_with_no_tiles() {
        for text in [
            "name: Bad\nposts: 1\nmap:\n+-+-+\n",   // one row of border
            "name: Bad\nposts: 1\nmap:\n+\n|\n+\n", // one column of border
            "name: Bad\nposts: 1\nmap:\n+\n",
        ] {
            let err = Level::parse(text).unwrap_err();
            assert!(err.contains("at least one tile"), "{text:?} gave {err}");
        }
    }

    /// A board dimension is a `u8`, and the cast to one used to wrap: a
    /// 300-tile lattice loaded as a 44-tile beach, silently not the level
    /// the text described.
    #[test]
    fn parse_rejects_a_map_too_wide_to_name() {
        let border: String = "+-".repeat(300) + "+";
        let row: String = "|.".repeat(300) + "|";
        let text = format!("name: Vast\nposts: 1\nmap:\n{border}\n{row}\n{border}\n");
        let err = Level::parse(&text).unwrap_err();
        assert!(err.contains("300"), "{err}");
        // And the widest board that *does* fit still parses.
        let border: String = "+-".repeat(255) + "+";
        let row: String = "|.".repeat(255) + "|";
        let text = format!("name: Wide\nposts: 1\nmap:\n{border}\n{row}\n{border}\n");
        let level = Level::parse(&text).expect("255 tiles is nameable");
        assert_eq!(level.board.width(), 255);
    }

    /// Short rows pad with spaces by design: editors trim trailing
    /// whitespace, and wrap maps end rows with spaces (open edges), so a
    /// strict width check would reject to_text's own trimmed output.
    #[test]
    fn parse_pads_short_map_rows() {
        let text = "name: Trimmed\nposts: 1\nmap:\n+-+-+\n|.\n+-+-+\n";
        let level = Level::parse(text).expect("pads, never panics");
        assert_eq!(level.board.width(), 2);
    }

    use super::*;
    use crate::sim::board::TileKind;

    /// A row wider than the top border is a map drawn wrong, not one to
    /// read to the border's width: read that way, the row's last tiles and
    /// walls go without a word.
    #[test]
    fn parse_refuses_a_map_row_wider_than_its_border() {
        let text = "name: T\nposts: 1\nmap:\n+-+-+\n|.|.|.|\n+-+-+\n";
        let err = Level::parse(text).unwrap_err();
        assert!(err.contains("row 1 is 7 wide"), "{err}");
    }

    /// Castle raids travel with the level. A puzzle with no `rule:` of its
    /// own turns them off in `board()` regardless; one that states its
    /// rule, as every editor-made puzzle does, keeps whatever the file
    /// says, and the file says `raids: off` when they are.
    #[test]
    fn castle_raids_survive_the_format() {
        let map = "map:\n+-+-+\n|. 0|\n+ + +\n|. .|\n+-+-+\n";
        let head = "name: T\nposts: 1\nrule: reject 1\ncrab: 0,0 R R common\n";
        let kept = Level::parse(&format!("{head}{map}")).expect("level");
        assert!(kept.board().rules().castle_raids, "stated rule, raids kept");
        assert!(
            !kept.to_text().contains("raids:"),
            "the default is not written"
        );
        let off = Level::parse(&format!("{head}raids: off\n{map}")).expect("level");
        assert!(!off.board().rules().castle_raids);
        let text = off.to_text();
        assert!(text.contains("raids: off"), "{text}");
        let back = Level::parse(&text).expect("round trip");
        assert!(!back.board().rules().castle_raids);
    }

    /// A big beach's gull cap travels with the level, so a replay of a round
    /// on one plays back under the cap it was played under. The default is
    /// not written, which keeps every file from before the cap readable and
    /// unchanged.
    #[test]
    fn the_gull_cap_survives_the_format() {
        let map = "map:\n+-+-+\n|. 0|\n+ + +\n|. .|\n+-+-+\n";
        let head = "name: T\nposts: 1\ncrab: 0,0 R R common\n";
        let plain = Level::parse(&format!("{head}{map}")).expect("level");
        assert_eq!(
            usize::from(plain.board().rules().gull_cap),
            crate::sim::GULL_CAP
        );
        assert!(
            !plain.to_text().contains("gull_cap"),
            "the default is not written"
        );
        let big = Level::parse(&format!("{head}gull_cap: 14\n{map}")).expect("level");
        assert_eq!(big.board().rules().gull_cap, 14);
        let back = Level::parse(&big.to_text()).expect("round trip");
        assert_eq!(back.board().rules().gull_cap, 14);
        assert!(
            !plain.board().rules().gull_turnover,
            "off unless the file says so"
        );
        assert!(!plain.to_text().contains("gull_turnover"));
        let turning = Level::parse(&format!("{head}gull_turnover: on\n{map}")).expect("level");
        let back = Level::parse(&turning.to_text()).expect("round trip");
        assert!(back.board().rules().gull_turnover);
        assert!(
            !plain.board().rules().timed_lock,
            "off unless the file says so"
        );
        assert!(!plain.to_text().contains("timed_lock"));
        let timed = Level::parse(&format!("{head}timed_lock: on\n{map}")).expect("level");
        let back = Level::parse(&timed.to_text()).expect("round trip");
        assert!(back.board().rules().timed_lock);
        assert!(
            !plain.board().rules().sweep_flight,
            "off unless the file says so"
        );
        assert!(!plain.to_text().contains("sweep_flight"));
        let flying = Level::parse(&format!("{head}sweep_flight: on\n{map}")).expect("level");
        let back = Level::parse(&flying.to_text()).expect("round trip");
        assert!(back.board().rules().sweep_flight);
        assert!(
            !plain.board().rules().whole_flock,
            "off unless the file says so"
        );
        assert!(!plain.to_text().contains("whole_flock"));
        let whole = Level::parse(&format!("{head}whole_flock: on\n{map}")).expect("level");
        let back = Level::parse(&whole.to_text()).expect("round trip");
        assert!(back.board().rules().whole_flock);
        assert!(
            !plain.board().rules().sweep_keeps_worth,
            "off unless the file says so"
        );
        assert!(!plain.to_text().contains("sweep_keeps_worth"));
        let keeping = Level::parse(&format!("{head}sweep_keeps_worth: on\n{map}")).expect("level");
        let back = Level::parse(&keeping.to_text()).expect("round trip");
        assert!(back.board().rules().sweep_keeps_worth);
        // A golden crab cadence too short to call a tick still to come is
        // refused, rather than calling one that never comes out.
        for every in [1, 2] {
            let err = Level::parse(&format!("{head}golden_every: {every}\n{map}"))
                .expect_err("too short");
            assert!(err.contains("golden_every"), "{err}");
        }
        let calling = Level::parse(&format!("{head}golden_every: 3\n{map}")).expect("level");
        assert_eq!(calling.board().rules().golden_every, 3);
    }

    /// A stage that states a round longer than the campaign tick limit is
    /// judged on its round, the limit standing in only for a stage with no
    /// timer: a Survive stage with ninety seconds on the clock was declared
    /// won at sixty.
    #[test]
    fn a_stated_round_outlasts_the_tick_limit() {
        let text = "name: T\nposts: 0\ngoal: survive\nround: 2700\nmap:\n\
                    +-+-+\n|. .|\n+ + +\n|. .|\n+-+-+\n";
        let level = Level::parse(text).expect("level");
        let mut board = level.board();
        assert_eq!(Level::deadline(&board), 2700);
        for _ in 0..PUZZLE_TICK_LIMIT {
            board.tick_idle();
        }
        assert_eq!(
            level.outcome(&board),
            PuzzleOutcome::Running,
            "the limit is not the round"
        );
        let (outcome, at) = level.play_out(&mut board);
        assert_eq!((outcome, at), (PuzzleOutcome::Won, 2700));
        // And without a round the limit is the deadline, as before.
        let untimed = Level::parse(&text.replace("round: 2700\n", "")).expect("level");
        assert_eq!(Level::deadline(&untimed.board()), PUZZLE_TICK_LIMIT);
    }

    /// Every goal but Survive loses when the deadline beats it: the
    /// board's round when it states one, the campaign limit when it does
    /// not. A crab circling a castle-less beach is never banked and never
    /// eaten, so only the clock can end it.
    #[test]
    fn the_deadline_loses_every_goal_but_survive() {
        let map = "map:\n+-+-+\n|. .|\n+ + +\n|. .|\n+-+-+\n";
        let timed = Level::parse(&format!(
            "name: T\nposts: 0\nround: 300\ncrab: 0,0 R R common\n{map}"
        ))
        .expect("level");
        let mut board = timed.board();
        assert_eq!(timed.play_out(&mut board), (PuzzleOutcome::Lost, 300));
        let untimed = Level::parse(&format!("name: T\nposts: 0\ncrab: 0,0 R R common\n{map}"))
            .expect("level");
        let mut board = untimed.board();
        assert_eq!(
            untimed.play_out(&mut board),
            (PuzzleOutcome::Lost, PUZZLE_TICK_LIMIT)
        );
    }

    /// `raids: on` is the default said out loud, and is read as such: only
    /// `off` turns them away, and a stated rule keeps whatever the file
    /// says.
    #[test]
    fn raids_on_is_the_default_said_out_loud() {
        let text = "name: T\nposts: 1\nrule: reject 1\nraids: on\ncrab: 0,0 R R common\nmap:\n\
                    +-+-+\n|. 0|\n+ + +\n|. .|\n+-+-+\n";
        let level = Level::parse(text).expect("level");
        assert!(level.board().rules().castle_raids);
        assert!(!level.to_text().contains("raids:"), "not worth writing");
    }

    /// A turnstile's pivot survives the format: a replay stores its
    /// starting board as a level, and generated arenas mirror their logs,
    /// so a dropped pivot would flip half of them on every recorded round.
    #[test]
    fn a_turnstiles_pivot_survives_the_format() {
        for next_right in [true, false] {
            let mut board = Board::new(4, 3, 1);
            board.set_tile(1, 1, TileKind::Turnstile { next_right });
            let text = Level::from_board("Pivot", 1, board).to_text();
            let parsed = Level::parse(&text).expect("own output").board();
            assert_eq!(
                parsed.tile_at(1, 1),
                TileKind::Turnstile { next_right },
                "next_right {next_right} was not preserved:\n{text}"
            );
        }
    }

    const TINY: &str = "\
name: Tiny
posts: 1
crab: 0,0 R L common
solution: 2,0 D
map:
+-+-+-+
|. . .|
+ +-+ +
|. . 0|
+-+-+-+
";

    const DUO: &str = "\
name: Duo
hands: 1 1
crab: 0,0 R L common
crab: 0,1 R R common
solution: 2,0 D L; 1,1 U R
map:
+-+-+-+
|. . .|
+ + + +
|. . 0|
+-+-+-+
";

    /// A co-op stage reads its two hands, grants their sum, and names the
    /// hand on each arrow of its solution; written back, it says the same.
    #[test]
    fn a_coop_stage_survives_the_format() {
        let level = Level::parse(DUO).expect("parses");
        assert_eq!(level.hands(), Some([1, 1]));
        assert_eq!(level.posts, 2);
        assert_eq!(level.kind, LevelKind::Puzzle);
        assert_eq!(
            level.solution,
            [(2, 0, Direction::Down, 0), (1, 1, Direction::Up, 1)]
        );
        assert_eq!(level.board().rules().claw_hands, Some([1, 1]));
        let text = level.to_text();
        assert!(text.contains("hands: 1 1"), "{text}");
        assert!(text.contains("solution: 2,0 D L; 1,1 U R"), "{text}");
        let again = Level::parse(&text).expect("own output");
        assert_eq!(again.solution, level.solution);
        assert_eq!(again.board().state_hash(), level.board().state_hash());
        assert_eq!(again.to_text(), text);
    }

    /// The hands and the grant cannot disagree, a solo stage names no
    /// hand, and a beach for a match has none.
    #[test]
    fn a_coop_stage_refuses_what_contradicts_it() {
        let posts = DUO.replace("hands: 1 1", "posts: 3\nhands: 1 1");
        assert!(Level::parse(&posts).unwrap_err().contains("two hands"));
        let solo = DUO.replace("hands: 1 1\n", "posts: 2\n");
        assert!(Level::parse(&solo).unwrap_err().contains("names a hand"));
        let arena = DUO.replace("hands: 1 1", "hands: 1 1\nkind: arena");
        assert!(Level::parse(&arena).unwrap_err().contains("no hands"));
        assert!(Level::parse(&DUO.replace("hands: 1 1", "hands: 1")).is_err());
        // A hand left off is P1's, as on every solo stage.
        let bare = Level::parse(&DUO.replace("2,0 D L", "2,0 D")).expect("parses");
        assert_eq!(bare.solution[0], (2, 0, Direction::Down, 0));
    }

    /// Dealt again, a co-op stage keeps its beach and changes only its
    /// hands: one player's, or ordinary arrows that turn every crab.
    #[test]
    fn a_coop_stage_deals_its_arrows_again() {
        let level = Level::parse(DUO).expect("parses");
        let alone = level.with_hands(Some([2, 0]), 0);
        assert_eq!((alone.posts, alone.hands()), (2, Some([2, 0])));
        let solo = level.with_hands(None, 2);
        assert_eq!((solo.posts, solo.hands()), (2, None));
        assert_eq!(solo.board().signpost_cap_of(0), 2);
        assert!(solo.solution.is_empty(), "the deal's own answer is unknown");
    }

    #[test]
    fn terrain_tiles_round_trip() {
        let mut board = Board::new(4, 3, 7);
        board.set_tile(1, 1, TileKind::Turnstile { next_right: true });
        board.set_tile(2, 1, TileKind::Kelp);
        board.set_tile(3, 1, TileKind::Pool);
        let text = Level::from_board("Terrain", 2, board).to_text();
        let level = Level::parse(&text).expect("parses");
        assert_eq!(
            level.board.tile_at(1, 1),
            TileKind::Turnstile { next_right: true }
        );
        assert_eq!(level.board.tile_at(2, 1), TileKind::Kelp);
        assert_eq!(level.board.tile_at(3, 1), TileKind::Pool);
        assert_eq!(level.to_text(), text, "text form is stable");
    }

    #[test]
    fn parses_dimensions_walls_and_tiles() {
        let level = Level::parse(TINY).expect("parses");
        assert_eq!(level.name, "Tiny");
        assert_eq!(level.posts, 1);
        assert_eq!(level.crab_count(), 1);
        let board = level.board();
        assert_eq!((board.width(), board.height()), (3, 2));
        assert_eq!(board.tile_at(2, 1), TileKind::Castle(0));
        assert!(board.wall_at(1, 0, Direction::Down));
        assert!(!board.wall_at(0, 0, Direction::Down));
        assert_eq!(board.crabs().len(), 1);
    }

    #[test]
    fn solution_wins_the_puzzle() {
        let level = Level::parse(TINY).expect("parses");
        let mut board = level.solved_board().expect("every placement lands");
        assert_eq!(level.play_out(&mut board).0, PuzzleOutcome::Won);
    }

    #[test]
    fn serialization_round_trips() {
        let level = Level::parse(TINY).expect("parses");
        let text = level.to_text();
        let again = Level::parse(&text).unwrap_or_else(|e| panic!("reparse: {e}\n{text}"));
        assert_eq!(level.name, again.name);
        assert_eq!(level.posts, again.posts);
        assert_eq!(level.solution, again.solution);
        assert_eq!(
            level.board().state_hash(),
            again.board().state_hash(),
            "round-tripped board must be bit-identical"
        );
    }

    #[test]
    fn timed_level_loses_at_the_wave() {
        // A `round:` shorter than the crab's walk: the tide freezes the sim
        // and the puzzle must resolve to Lost, not sit Running forever.
        let text = TINY.replace("posts: 1", "posts: 1\nround: 10");
        let level = Level::parse(&text).expect("parses");
        let mut board = level.board();
        for _ in 0..12 {
            board.tick_idle();
        }
        assert!(board.round_over());
        assert_eq!(level.outcome(&board), PuzzleOutcome::Lost);
    }

    #[test]
    fn goal_wrap_and_new_kinds_round_trip() {
        let text = "\
name: Fancy
posts: 2
rule: evict 3
round: 900
wrap: on
goal: bank 30
crab: 0,0 R L golden
crab: 2,1 L R sparkling
map:
+-+-+-+-+
|. . . .|
+ + + + +
|. 0 . .|
+-+-+-+-+
";
        let level = Level::parse(text).expect("parses");
        assert_eq!(level.goal, Goal::Bank(30));
        assert!(level.board().wrap());
        let again = Level::parse(&level.to_text()).expect("reparses");
        assert_eq!(again.goal, level.goal);
        assert_eq!(
            again.board().state_hash(),
            level.board().state_hash(),
            "wrap/goal/kind round-trip must be bit-identical"
        );
    }

    #[test]
    fn goal_outcomes_judge_correctly() {
        // Bank goal: reached mid-round.
        let bank = Level::parse(
            "name: B\nposts: 0\nrule: evict 3\nround: 900\ngoal: bank 1\n\
             crab: 0,1 R L common\nmap:\n+-+-+-+\n|. . .|\n+ + + +\n|. . 0|\n+-+-+-+\n",
        )
        .expect("parses");
        let mut board = bank.board();
        assert_eq!(bank.outcome(&board), PuzzleOutcome::Running);
        for _ in 0..200 {
            board.tick_idle();
        }
        assert_eq!(bank.outcome(&board), PuzzleOutcome::Won);

        // Survive goal: an eaten crab is an instant loss. The gull starts on
        // the crab's tile, so the very first collision pass eats it.
        let survive = Level::parse(
            "name: S\nposts: 0\nrule: evict 3\nround: 900\ngoal: survive\n\
             crab: 1,0 R L common\ngull: 1,0 R\nmap:\n+-+-+-+-+-+-+-+-+-+\n\
             |. . . . . . . . .|\n+-+-+-+-+-+-+-+-+-+\n",
        )
        .expect("parses");
        let mut board = survive.board();
        board.tick_idle();
        assert_eq!(
            survive.outcome(&board),
            PuzzleOutcome::Lost,
            "the gull got someone"
        );
    }

    /// A crab Crab Monopoly is flying home is neither on the beach nor
    /// banked yet, and used to be judged eaten for the length of its
    /// flight, losing a Survive or AllCrabs stage that nobody lost.
    #[test]
    fn a_crab_in_the_air_is_not_eaten() {
        let level = Level::parse(
            "name: S\nposts: 0\nrule: evict 3\nround: 900\ngoal: survive\n\
             crab: 1,0 R L common\ncrab: 2,0 R L common\nmap:\n+-+-+-+-+-+-+\n\
             |. . . . . 0|\n+-+-+-+-+-+-+\n",
        )
        .expect("parses");
        let mut board = level.board();
        board.set_events_enabled(true);
        board.rules_mut().sweep_flight = true;
        board.force_tide_event(crate::sim::TideEvent::Monopoly, 0);
        assert!(!board.sweeping().is_empty(), "one is in the air");
        assert_eq!(level.outcome(&board), PuzzleOutcome::Running);
    }

    /// The kind survives the format both ways round, and is the author's
    /// answer rather than the board's: a puzzle with four castles saved as
    /// a puzzle comes back a puzzle.
    #[test]
    fn the_kind_round_trips_and_outranks_the_castles() {
        let level = Level::parse(TINY).expect("parses");
        assert_eq!(level.kind, LevelKind::Puzzle, "one castle, one player");
        for kind in [LevelKind::Puzzle, LevelKind::Arena] {
            let text = level.clone().with_kind(kind).to_text();
            assert_eq!(Level::parse(&text).expect("reparses").kind, kind, "{text}");
        }
        // Four castles and the author still says puzzle.
        let four = "\
name: Four
posts: 1
kind: puzzle
crab: 0,0 R L common
map:
+-+-+-+-+
|0 1 2 3|
+-+-+-+-+
";
        let level = Level::parse(four).expect("parses");
        assert_eq!(level.seats(), 4);
        assert_eq!(level.kind, LevelKind::Puzzle, "the line beats the board");
        assert!(Level::parse(&four.replace("kind: puzzle", "kind: mud")).is_err());
    }

    /// A table seats a beach whose castles run from 0 with none skipped,
    /// and at most as many players as it has castles; the board it plays
    /// has the castles past the table put away, the same on every seed.
    #[test]
    fn a_table_plays_the_castles_it_has_seats_for() {
        let beach = |row: &str| {
            Level::parse(&format!(
                "name: B\nposts: 1\nkind: arena\nmap:\n+-+-+-+-+\n|{row}|\n+-+-+-+-+\n"
            ))
            .expect("parses")
        };
        let four = beach("0 1 2 3");
        assert_eq!(four.table_seats(), Some(4));
        assert!(four.fits(2) && four.fits(4) && !four.fits(5));
        let board = four.table_board(9, 2);
        assert_eq!(board.castle_owners().collect::<Vec<_>>(), vec![0, 1]);
        assert_eq!(board.seats_in_play(), 2);
        assert_eq!(board.tile_at(2, 0), TileKind::Empty);
        assert_eq!(
            board.state_hash(),
            four.table_board(9, 2).state_hash(),
            "built alike"
        );
        let gapped = beach("0 . 2 .");
        assert_eq!(gapped.seats(), 2, "two owners, counted");
        assert_eq!(gapped.table_seats(), None, "but seat 1 has no castle");
        assert!(!gapped.fits(2) && !gapped.fits(1));
    }

    /// A file written before the editor had a toggle says nothing about
    /// what it is, so the castles answer for it: one bank is a stage,
    /// castles for two players is a beach nobody plays alone.
    #[test]
    fn a_file_with_no_kind_is_read_off_its_castles() {
        assert_eq!(Level::parse(TINY).expect("parses").kind, LevelKind::Puzzle);
        let two = "\
name: Old Arena
posts: 3
crab: 0,0 R L common
map:
+-+-+-+
|0 . 1|
+-+-+-+
";
        let level = Level::parse(two).expect("parses");
        assert_eq!(level.seats(), 2);
        assert_eq!(level.kind, LevelKind::Arena);
        // And once read, it is written down: the guess happens once.
        assert!(
            level.to_text().contains("kind: arena"),
            "{}",
            level.to_text()
        );
    }

    #[test]
    fn inventory_is_enforced() {
        let level = Level::parse(TINY).expect("parses");
        let mut board = level.board();
        assert!(board.place_signpost(0, 0, 1, Direction::Up));
        // posts: 1, so the second placement must be rejected, not evict.
        assert!(!board.place_signpost(0, 1, 1, Direction::Up));
        assert_eq!(board.signpost_count(0), 1);
    }

    /// A beach built on a round's seed is on that seed's stream, and is
    /// the board its replay rebuilds: the level written off it names the
    /// new seed, and placing its gull draws the same numbers again.
    #[test]
    fn a_beach_on_a_fresh_seed_replays_from_what_it_records() {
        let level = Level::parse(
            "name: B\nposts: 3\nkind: arena\nseed: 1\ngull: 4,0 R\nmap:\n\
             +-+-+-+-+-+-+-+-+-+\n|0 . . . . . . . 1|\n+-+-+-+-+-+-+-+-+-+\n",
        )
        .expect("parses");
        let fresh = level.board_seeded(77);
        assert_eq!(fresh.seed(), 77);
        assert_ne!(
            fresh.state_hash(),
            level.board_seeded(78).state_hash(),
            "another seed, another stream"
        );
        let recorded = Level::from_board("B", 3, fresh.clone()).to_text();
        let rebuilt = Level::parse(&recorded).expect("reads back").board();
        assert_eq!(rebuilt.state_hash(), fresh.state_hash());
    }
}