pinch-points 0.8.0

A fast, kid-friendly crab-routing game: route streams of crabs into your sandcastle before time runs out
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
//! The level text format: parsing a level file into a [`Board`], and
//! writing one back out.
//!
//! Kept apart from the level *model* next door: the format is the only
//! thing that cares about glyphs, lattices and `key: value` headers, and it
//! is the half with a round-trip contract to keep (see `tests/it/format.rs`).

use super::{Goal, Level, LevelKind};
use crate::sim::board::{Board, CapPolicy, GULL_CAP, TileKind};
use crate::sim::crab::{CrabKind, Handedness};
use crate::sim::direction::Direction;
use crate::sim::solve::Placement;
use crate::sim::{PlayerId, Spawner};

impl Level {
    pub fn parse(text: &str) -> Result<Level, String> {
        let mut lines = text.lines();
        let header = parse_header(&mut lines)?;
        let mut board = parse_lattice(lines, header.seed)?;
        place_entities(&mut board, &header)?;
        let level = Level {
            name: header.name.ok_or("missing name:")?,
            posts: header.posts.ok_or("missing posts:")?,
            solution: header.solution,
            goal: header.goal,
            // Filled in below: a file written before the editor had a toggle
            // has no `kind:` line and has to be read off the board.
            kind: LevelKind::Puzzle,
            crab_count: header.crabs.len() as u32,
            explicit_rule: header.rule.is_some(),
            board,
        };
        let kind = header.kind.unwrap_or_else(|| inferred_kind(&level));
        Ok(level.with_kind(kind))
    }

    /// Wrap an editor-built board as a level. The board is snapshotted as-is
    /// (crabs, gulls, walls, timers included), and the kind is read off it -
    /// call [`Level::with_kind`] to say otherwise, which is what the editor's
    /// toggle does.
    pub fn from_board(name: impl Into<String>, posts: u8, board: Board) -> Level {
        let level = Level {
            name: name.into(),
            posts,
            solution: Vec::new(),
            goal: Goal::AllCrabs,
            kind: LevelKind::Puzzle,
            crab_count: board.crabs().len() as u32,
            // The board's live rule is authoritative and serialized as-is.
            explicit_rule: true,
            board,
        };
        let kind = inferred_kind(&level);
        level.with_kind(kind)
    }

    /// Serialize back to the text format `parse` reads. Round-trips exactly
    /// for an un-ticked board that `parse` built (creature sub-tile state is
    /// not representable, since levels describe starting states). A board
    /// edited by hand differs: placing a gull draws twice from the board's
    /// PRNG and the text carries the seed rather than the stream's
    /// position, so one that placed and erased gulls reads back with the
    /// survivors rolled afresh. Hence the editor certifies the text it will
    /// save rather than the board it edited (`level_here`).
    pub fn to_text(&self) -> String {
        use std::fmt::Write;
        let board = &self.board;
        let mut out = String::new();
        let _ = writeln!(out, "name: {}", self.name);
        let _ = writeln!(out, "posts: {}", self.posts);
        // Always written, both values: what the author chose is not always
        // what the board looks like, and a file that leaves it out is read
        // by guessing at the castles.
        let _ = writeln!(out, "kind: {}", self.kind.token());
        let _ = writeln!(out, "seed: {}", board.seed());
        // Puzzle levels (no explicit rule) reconstruct their rule from
        // `posts:` on parse; writing one would freeze the wrong default.
        if self.explicit_rule {
            let (cap, policy) = board.signpost_rule();
            let _ = writeln!(out, "rule: {} {cap}", policy.token());
        }
        for (player, &score) in board.scores().iter().enumerate() {
            if score > 0 {
                let _ = writeln!(out, "score: {player} {score}");
            }
        }
        for crab in board.crabs() {
            let (x, y) = board.coords_u8(crab.tile);
            let _ = writeln!(
                out,
                "crab: {x},{y} {} {} {}",
                crab.dir.letter(),
                crab.handed.token(),
                crab.kind.token()
            );
        }
        for (x, y, kind) in board.tiles() {
            if let TileKind::Spawner(s) = kind {
                let _ = writeln!(out, "spawner: {x},{y} {} {}", s.dir.letter(), s.period);
            }
        }
        for gull in board.gulls() {
            let (x, y) = board.coords_u8(gull.tile);
            let _ = writeln!(out, "gull: {x},{y} {}", gull.dir.letter());
        }
        if board.gull_period() > 0 {
            let _ = writeln!(out, "gull_period: {}", board.gull_period());
        }
        if usize::from(board.gull_cap()) != GULL_CAP {
            let _ = writeln!(out, "gull_cap: {}", board.gull_cap());
        }
        if board.gull_turnover() {
            let _ = writeln!(out, "gull_turnover: on");
        }
        if board.golden_every() > 0 {
            let _ = writeln!(out, "golden_every: {}", board.golden_every());
        }
        if board.timed_lock() {
            let _ = writeln!(out, "timed_lock: on");
        }
        if board.sweep_flight() {
            let _ = writeln!(out, "sweep_flight: on");
        }
        if let Some(round) = board.round_length() {
            let _ = writeln!(out, "round: {round}");
        }
        if board.wrap() {
            let _ = writeln!(out, "wrap: on");
        }
        // Written only when they are off, being on by default. An
        // editor-made puzzle states its rule and keeps whatever raids the
        // board had, so without this line it plays, is checked and is
        // hinted with raids on while every campaign puzzle plays without.
        if !board.castle_raids() {
            let _ = writeln!(out, "raids: off");
        }
        // Tide events are game state, not authoring flavour: dropping the
        // flag made replays of versus rounds silently diverge.
        if board.events_enabled() {
            let _ = writeln!(out, "events: on");
        }
        match self.goal {
            Goal::AllCrabs => {}
            Goal::Bank(n) => {
                let _ = writeln!(out, "goal: bank {n}");
            }
            Goal::Survive => {
                let _ = writeln!(out, "goal: survive");
            }
            Goal::Golden => {
                let _ = writeln!(out, "goal: golden");
            }
        }
        if !self.solution.is_empty() {
            let parts: Vec<String> = self
                .solution
                .iter()
                .map(|&(x, y, dir)| format!("{x},{y} {}", dir.letter()))
                .collect();
            let _ = writeln!(out, "solution: {}", parts.join("; "));
        }
        let _ = writeln!(out, "map:");

        // Lattice: (2h+1) rows × (2w+1) columns.
        let (w, h) = (board.width() as usize, board.height() as usize);
        let mut lattice = vec![vec![' '; 2 * w + 1]; 2 * h + 1];
        for row in lattice.iter_mut().step_by(2) {
            for cell in row.iter_mut().step_by(2) {
                *cell = '+';
            }
        }
        for (x, y, kind) in board.tiles() {
            let (lx, ly) = (2 * x as usize + 1, 2 * y as usize + 1);
            lattice[ly][lx] = tile_glyph(kind);
            if board.wall_at(x, y, Direction::Up) {
                lattice[ly - 1][lx] = '-';
            }
            if board.wall_at(x, y, Direction::Left) {
                lattice[ly][lx - 1] = '|';
            }
            if board.wall_at(x, y, Direction::Down) {
                lattice[ly + 1][lx] = '-';
            }
            if board.wall_at(x, y, Direction::Right) {
                lattice[ly][lx + 1] = '|';
            }
        }
        for row in lattice {
            let line: String = row.into_iter().collect();
            let _ = writeln!(out, "{}", line.trim_end());
        }
        out
    }
}

/// What a level with nothing to say about itself must be: castles for two
/// seats or more is a beach nobody plays alone. Only reached for text
/// written before the format carried a `kind:` line, and for boards handed
/// straight to [`Level::from_board`] (a recorded versus round, which is an
/// arena, and an editor snapshot, whose kind the editor then states).
fn inferred_kind(level: &Level) -> LevelKind {
    match level.seats() >= 2 {
        true => LevelKind::Arena,
        false => LevelKind::Puzzle,
    }
}

fn parse_xy(s: &str) -> Result<(u8, u8, &str), String> {
    let (xy, rest) = match s.split_once(char::is_whitespace) {
        Some((xy, rest)) => (xy, rest),
        None => (s, ""),
    };
    let (x, y) = xy
        .split_once(',')
        .ok_or_else(|| format!("expected x,y in {s:?}"))?;
    let x = x.trim().parse::<u8>().map_err(|e| format!("x: {e}"))?;
    let y = y.trim().parse::<u8>().map_err(|e| format!("y: {e}"))?;
    Ok((x, y, rest))
}

/// Everything the `key: value` header section declares, gathered before
/// the map lattice is read.
struct Header {
    name: Option<String>,
    posts: Option<u8>,
    solution: Vec<Placement>,
    crabs: Vec<(u8, u8, Direction, Handedness, CrabKind)>,
    spawners: Vec<(u8, u8, Direction, u32)>,
    gulls: Vec<(u8, u8, Direction)>,
    gull_period: u32,
    /// `None` when the file says nothing, which keeps the board's default.
    gull_cap: Option<u8>,
    gull_turnover: bool,
    golden_every: u32,
    timed_lock: bool,
    sweep_flight: bool,
    events: bool,
    round: Option<u32>,
    seed: u64,
    rule: Option<(u8, CapPolicy)>,
    scores: Vec<(u8, u32)>,
    goal: Goal,
    wrap: bool,
    /// `None` when the file predates the editor's puzzle/arena toggle.
    kind: Option<LevelKind>,
    /// Inverted like the snapshot's, because raids are the one board
    /// switch that is on by default: a file that says nothing keeps them,
    /// and only `raids: off` turns them away. A puzzle with no `rule:` of
    /// its own turns them off regardless, in [`Level::board`].
    no_castle_raids: bool,
}

impl Default for Header {
    fn default() -> Header {
        Header {
            name: None,
            posts: None,
            solution: Vec::new(),
            crabs: Vec::new(),
            spawners: Vec::new(),
            gulls: Vec::new(),
            gull_period: 0,
            gull_cap: None,
            gull_turnover: false,
            golden_every: 0,
            timed_lock: false,
            sweep_flight: false,
            events: false,
            round: None,
            // An arbitrary but fixed default, so a level file without a
            // `seed:` still replays identically everywhere.
            seed: 0x7ead_0001,
            rule: None,
            scores: Vec::new(),
            goal: Goal::AllCrabs,
            wrap: false,
            kind: None,
            no_castle_raids: false,
        }
    }
}

/// What one header line did: carried a value, or ended the header.
enum HeaderLine {
    Read,
    /// `map:`, after which the lattice starts on the next line.
    MapFollows,
}

impl Header {
    /// Fold one `key: value` line in. Each key parses its own value and
    /// says so in its own error message, which is the sort of thing a
    /// hand-edited level file needs to hear.
    fn read_line(&mut self, key: &str, value: &str) -> Result<HeaderLine, String> {
        match key {
            "name" => self.name = Some(value.to_string()),
            "posts" => {
                self.posts = Some(value.parse::<u8>().map_err(|e| format!("posts: {e}"))?);
            }
            "crab" => {
                let (x, y, rest) = parse_xy(value)?;
                let mut parts = rest.split_whitespace();
                let dir = parse_dir(parts.next().ok_or("crab: missing direction")?)?;
                let handed = parts.next().ok_or("crab: missing handedness")?;
                let handed = Handedness::from_token(handed)
                    .ok_or_else(|| format!("crab: bad handedness {handed:?}"))?;
                let kind = parts.next().ok_or("crab: missing kind")?;
                let kind =
                    CrabKind::from_token(kind).ok_or_else(|| format!("crab: bad kind {kind:?}"))?;
                self.crabs.push((x, y, dir, handed, kind));
            }
            "spawner" => {
                let (x, y, rest) = parse_xy(value)?;
                let mut parts = rest.split_whitespace();
                let dir = parse_dir(parts.next().ok_or("spawner: missing direction")?)?;
                let period = parts
                    .next()
                    .ok_or("spawner: missing period")?
                    .parse::<u32>()
                    .map_err(|e| format!("spawner period: {e}"))?;
                self.spawners.push((x, y, dir, period));
            }
            "gull" => {
                let (x, y, rest) = parse_xy(value)?;
                let dir = parse_dir(rest.trim())?;
                self.gulls.push((x, y, dir));
            }
            "gull_period" => {
                self.gull_period = value
                    .parse::<u32>()
                    .map_err(|e| format!("gull_period: {e}"))?;
            }
            "gull_cap" => {
                self.gull_cap = Some(value.parse::<u8>().map_err(|e| format!("gull_cap: {e}"))?);
            }
            "gull_turnover" => self.gull_turnover = value == "on",
            "timed_lock" => self.timed_lock = value == "on",
            "sweep_flight" => self.sweep_flight = value == "on",
            "golden_every" => {
                self.golden_every = value
                    .parse::<u32>()
                    .map_err(|e| format!("golden_every: {e}"))?;
            }
            "round" => {
                self.round = Some(value.parse::<u32>().map_err(|e| format!("round: {e}"))?);
            }
            "seed" => {
                self.seed = value.parse::<u64>().map_err(|e| format!("seed: {e}"))?;
            }
            "goal" => {
                self.goal = match value.split_once(' ') {
                    Some(("bank", n)) => {
                        Goal::Bank(n.trim().parse().map_err(|e| format!("goal bank: {e}"))?)
                    }
                    None if value == "survive" => Goal::Survive,
                    None if value == "golden" => Goal::Golden,
                    None if value == "all" => Goal::AllCrabs,
                    _ => return Err(format!("goal: bad value {value:?}")),
                };
            }
            "raids" => self.no_castle_raids = value == "off",
            "kind" => {
                self.kind = Some(
                    LevelKind::from_token(value)
                        .ok_or_else(|| format!("kind: bad value {value:?}"))?,
                );
            }
            "wrap" => self.wrap = value == "on",
            "events" => self.events = value == "on",
            "rule" => {
                let (policy, cap) = value
                    .split_once(' ')
                    .ok_or("rule: expected `<evict|reject> <cap>`")?;
                let cap = cap
                    .trim()
                    .parse::<u8>()
                    .map_err(|e| format!("rule cap: {e}"))?;
                let policy = policy.trim();
                let policy = CapPolicy::from_token(policy)
                    .ok_or_else(|| format!("rule: bad policy {policy:?}"))?;
                // Evicting needs something to evict: at a cap of zero the
                // first placement would look for an oldest post that is
                // not there. Reject at zero is a puzzle with no posts.
                if cap == 0 && policy == CapPolicy::Evict {
                    return Err("rule: evict needs a cap of at least 1".to_string());
                }
                self.rule = Some((cap, policy));
            }
            "score" => {
                let (player, score) = value
                    .split_once(' ')
                    .ok_or("score: expected `<player> <score>`")?;
                let player = player
                    .trim()
                    .parse::<u8>()
                    .map_err(|e| format!("score: {e}"))?;
                let score = score
                    .trim()
                    .parse::<u32>()
                    .map_err(|e| format!("score: {e}"))?;
                if crate::sim::board::seat(player).is_none() {
                    return Err(format!("score: player {player} out of range"));
                }
                self.scores.push((player, score));
            }
            "solution" => {
                for placement in value.split(';') {
                    let (x, y, rest) = parse_xy(placement.trim())?;
                    let dir = parse_dir(rest.trim())?;
                    self.solution.push((x, y, dir));
                }
            }
            "map" => return Ok(HeaderLine::MapFollows),
            other => return Err(format!("unknown key {other:?}")),
        }
        Ok(HeaderLine::Read)
    }
}

/// Stage 1: the `key: value` lines up to (and consuming) `map:`.
fn parse_header(lines: &mut std::str::Lines) -> Result<Header, String> {
    let mut header = Header::default();
    for line in lines.by_ref() {
        let line = line.trim();
        // Comments are only possible before the map (map rows use '#').
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let Some((key, value)) = line.split_once(':') else {
            return Err(format!("expected `key: value` before map, got {line:?}"));
        };
        if let HeaderLine::MapFollows = header.read_line(key.trim(), value.trim())? {
            break;
        }
    }
    Ok(header)
}

/// Stage 2: the odd-sized wall lattice into a board of tiles and walls.
fn parse_lattice<'a>(lines: impl Iterator<Item = &'a str>, seed: u64) -> Result<Board, String> {
    let lattice: Vec<&str> = lines.filter(|l: &&str| !l.trim().is_empty()).collect();
    if lattice.is_empty() {
        return Err("missing map section".into());
    }
    let lat_h = lattice.len();
    let lat_w = lattice[0].chars().count();
    if lat_h.is_multiple_of(2) || lat_w.is_multiple_of(2) {
        return Err(format!(
            "map lattice must be odd-sized, got {lat_w}×{lat_h}"
        ));
    }
    // A lattice spends `2n + 1` lines on `n` tiles, so three is the
    // narrowest that holds one and `2·255 + 1` the widest a `u8` dimension
    // can name. Checking odd-sized alone let both ends through: a lone
    // border line made a zero-sized board, which `Board::new` refuses with
    // a panic, and an over-wide one wrapped the cast, loading a 300-tile
    // beach as 44.
    if lat_w < 3 || lat_h < 3 {
        return Err(format!(
            "map lattice must hold at least one tile, got {lat_w}×{lat_h}"
        ));
    }
    let (tiles_w, tiles_h) = (lat_w / 2, lat_h / 2);
    let (Ok(width), Ok(height)) = (u8::try_from(tiles_w), u8::try_from(tiles_h)) else {
        return Err(format!(
            "map is {tiles_w}×{tiles_h} tiles, past the {} a side the format can name",
            u8::MAX
        ));
    };
    // A row wider than the top border is a different thing: nothing trims
    // a line longer, so it is a map drawn wrong, and reading it to the
    // border's width would drop its last tiles and walls without a word.
    if let Some((row, width)) = lattice
        .iter()
        .map(|row| row.chars().count())
        .enumerate()
        .find(|(_, width)| *width > lat_w)
    {
        return Err(format!(
            "map row {row} is {width} wide, past the top border's {lat_w}"
        ));
    }
    // Short rows pad with spaces rather than erroring: text editors trim
    // trailing whitespace, and wrap-map rows legitimately end in spaces
    // (open edges) - to_text itself emits them trimmed.
    let grid: Vec<Vec<char>> = lattice
        .iter()
        .map(|row| {
            let mut chars: Vec<char> = row.chars().collect();
            chars.resize(lat_w, ' ');
            chars
        })
        .collect();

    // The seed matters only where the PRNG is consumed (spawner and gull
    // handedness, takeoff timers); serialized levels carry it so replays
    // rebuild bit-identical boards.
    // Both were just checked against the lattice; `Board::new` panics on a
    // zero, which is how a lone border line once took the game down.
    debug_assert!(width > 0 && height > 0, "a {width}x{height} board");
    let mut board = Board::new(width, height, seed);
    for y in 0..height {
        for x in 0..width {
            let c = grid[y as usize * 2 + 1][x as usize * 2 + 1];
            match tile_from_glyph(c) {
                Some(TileKind::Empty) => {}
                Some(tile) => board.set_tile(x, y, tile),
                None => return Err(format!("bad tile char {c:?} at ({x},{y})")),
            }
            // Up edge of (x, y) is lattice row 2y, column 2x+1.
            if grid[y as usize * 2][x as usize * 2 + 1] == '-' {
                board.set_wall(x, y, Direction::Up, true);
            }
            // Left edge is lattice row 2y+1, column 2x.
            if grid[y as usize * 2 + 1][x as usize * 2] == '|' {
                board.set_wall(x, y, Direction::Left, true);
            }
        }
    }
    // Bottom and right borders of the lattice.
    for x in 0..width {
        if grid[height as usize * 2][x as usize * 2 + 1] == '-' {
            board.set_wall(x, height - 1, Direction::Down, true);
        }
    }
    for y in 0..height {
        if grid[y as usize * 2 + 1][width as usize * 2] == '|' {
            board.set_wall(width - 1, y, Direction::Right, true);
        }
    }
    Ok(board)
}

/// Stage 3: header-declared spawners, creatures, and board switches, with
/// bounds validation against the lattice-derived size.
fn place_entities(board: &mut Board, header: &Header) -> Result<(), String> {
    let (width, height) = (board.width(), board.height());
    let check = |what: &str, x: u8, y: u8| -> Result<(), String> {
        if x >= width || y >= height {
            return Err(format!(
                "{what} at ({x},{y}) is off the {width}x{height} board"
            ));
        }
        Ok(())
    };
    for &(x, y, dir, period) in &header.spawners {
        check("spawner", x, y)?;
        if period == 0 {
            return Err(format!("spawner at ({x},{y}): period must be at least 1"));
        }
        board.set_tile(x, y, TileKind::Spawner(Spawner { dir, period }));
    }
    for &(x, y, dir, handed, kind) in &header.crabs {
        check("crab", x, y)?;
        if board.tile_at(x, y) == TileKind::Rock {
            return Err(format!("crab at ({x},{y}) is standing on a rock"));
        }
        board.spawn_crab(x, y, dir, handed, kind);
    }
    for &(x, y, dir) in &header.gulls {
        check("gull", x, y)?;
        if !board.gull_may_stand(x, y) {
            return Err(format!(
                "gull at ({x},{y}) is standing on a rock or in kelp"
            ));
        }
        board.spawn_gull(x, y, dir);
    }
    board.set_gull_period(header.gull_period);
    if let Some(cap) = header.gull_cap {
        board.set_gull_cap(cap);
    }
    board.set_gull_turnover(header.gull_turnover);
    board.set_golden_every(header.golden_every);
    board.set_timed_lock(header.timed_lock);
    board.set_sweep_flight(header.sweep_flight);
    board.set_round_length(header.round);
    if header.no_castle_raids {
        board.set_castle_raids(false);
    }
    if header.wrap {
        board.set_wrap(true);
    }
    if header.events {
        board.set_events_enabled(true);
    }
    if let Some((cap, policy)) = header.rule {
        board.set_signpost_rule(cap, policy);
    }
    for &(player, score) in &header.scores {
        board.set_score(player, score);
    }
    Ok(())
}

/// The map glyph for a tile; `tile_from_glyph` is its inverse (spawners
/// serialize in the header, so they read back as sand here).
fn tile_glyph(tile: TileKind) -> char {
    match tile {
        TileKind::Empty | TileKind::Spawner(_) => '.',
        TileKind::Rock => '#',
        TileKind::Castle(owner) => (b'0' + owner) as char,
        // Upper case is a log about to deflect right, lower case one about
        // to deflect left. The pivot has to survive: generated arenas mirror
        // their logs, and a replay stores its starting board *as* a level.
        TileKind::Turnstile { next_right: true } => 'T',
        TileKind::Turnstile { next_right: false } => 't',
        TileKind::Kelp => 'K',
        TileKind::Pool => '~',
    }
}

fn tile_from_glyph(c: char) -> Option<TileKind> {
    match c {
        '.' | ' ' => Some(TileKind::Empty),
        '#' => Some(TileKind::Rock),
        'T' => Some(TileKind::Turnstile { next_right: true }),
        't' => Some(TileKind::Turnstile { next_right: false }),
        'K' => Some(TileKind::Kelp),
        '~' => Some(TileKind::Pool),
        // As many seats as the sim has, not the four it had when the glyphs
        // were chosen: a six-castle board writes '4' and '5', and a reader
        // that rejects them turns every six-player replay into a parse error.
        '0'..='9' if crate::sim::board::seat(c as u8 - b'0').is_some() => {
            Some(TileKind::Castle((c as u8 - b'0') as PlayerId))
        }
        _ => None,
    }
}

fn parse_dir(s: &str) -> Result<Direction, String> {
    Direction::from_letter(s).ok_or_else(|| format!("bad direction {s:?}"))
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A 2x2 board, sand except for a rock at (1,1), with the given header
    /// lines in front of it.
    fn level_with(header: &str) -> Result<Level, String> {
        let text =
            format!("name: T\nposts: 1\n{header}\nmap:\n+-+-+\n|.|.|\n+-+-+\n|.|#|\n+-+-+\n");
        Level::parse(&text)
    }

    /// Every goal a challenge can set survives being written out and read
    /// back, and `all` reads as the default it is.
    #[test]
    fn every_goal_survives_the_trip_through_text() {
        for (line, goal) in [
            ("goal: bank 12", Goal::Bank(12)),
            ("goal: survive", Goal::Survive),
            ("goal: golden", Goal::Golden),
            ("goal: all", Goal::AllCrabs),
        ] {
            let level = level_with(line).expect(line);
            assert_eq!(level.goal, goal, "{line}");
            let back = Level::parse(&level.to_text()).expect("reads back");
            assert_eq!(back.goal, goal, "{line} through to_text");
        }
    }

    /// A goal that is none of them, or a bank that is not a number, is
    /// refused with the line's name rather than read as "every crab".
    #[test]
    fn a_goal_nobody_can_meet_is_refused() {
        for line in ["goal: win", "goal: bank lots", "goal: bank"] {
            let err = level_with(line).unwrap_err();
            assert!(err.contains("goal"), "{line}: {err}");
        }
    }

    /// A rule is a policy and a cap, and evicting needs something to evict:
    /// each malformed one is refused with its reason.
    #[test]
    fn a_rule_that_cannot_be_played_is_refused() {
        for (line, why) in [
            ("rule: evict", "expected"),
            ("rule: evict many", "rule cap"),
            ("rule: steal 3", "bad policy"),
            ("rule: evict 0", "at least 1"),
        ] {
            let err = level_with(line).unwrap_err();
            assert!(err.contains(why), "{line}: {err}");
        }
        assert!(
            level_with("rule: reject 0").is_ok(),
            "a puzzle with no posts"
        );
    }

    /// A score names a seat that exists and a number; anything else is
    /// refused rather than written onto a castle nobody holds.
    #[test]
    fn a_score_for_nobody_is_refused() {
        for (line, why) in [
            ("score: 1", "expected"),
            ("score: x 5", "score"),
            ("score: 1 lots", "score"),
            ("score: 9 5", "out of range"),
        ] {
            let err = level_with(line).unwrap_err();
            assert!(err.contains(why), "{line}: {err}");
        }
    }

    /// Placement is the last thing `parse` checks, and each refusal names
    /// its reason: these files are hand-edited and pasted as codes, and
    /// "invalid level" tells the author nothing. A spawner with period 0
    /// divides the sim's tick by zero; a crab on a rock stands where
    /// nothing walks; an entity off the board indexes past the tile
    /// vector.
    #[test]
    fn placing_an_entity_where_it_cannot_go_is_refused_with_the_reason() {
        let err = level_with("spawner: 0,0 R 0").unwrap_err();
        assert!(err.contains("period must be at least 1"), "{err}");
        let err = level_with("rule: evict 0").unwrap_err();
        assert!(err.contains("at least 1"), "{err}");
        assert!(
            level_with("rule: reject 0").is_ok(),
            "no posts to give is a legal puzzle"
        );
        let err = level_with("crab: 1,1 R L common").unwrap_err();
        assert!(err.contains("standing on a rock"), "{err}");
        let err = level_with("gull: 1,1 R").unwrap_err();
        assert!(err.contains("standing on a rock"), "{err}");
        // Kelp is the other tile a gull cannot stand in, and the sim
        // asserts on it just the same: a refusal here, not a panic.
        let kelp = "name: T\nposts: 1\ngull: 1,1 R\nmap:\n+-+-+\n|.|.|\n+-+-+\n|.|K|\n+-+-+\n";
        let err = Level::parse(kelp).unwrap_err();
        assert!(err.contains("in kelp"), "{err}");
        for line in ["spawner: 2,0 R 4", "crab: 0,2 R L common", "gull: 5,5 D"] {
            let err = level_with(line).unwrap_err();
            assert!(err.contains("off the 2x2 board"), "{line}: {err}");
        }
        // And the same lines with their coordinates fixed are placed.
        let level = level_with("spawner: 0,0 R 4\ncrab: 1,0 R L common\ngull: 0,1 R")
            .expect("a valid placement");
        assert_eq!(level.board.crabs().len(), 1);
        assert_eq!(level.board.gulls().len(), 1);
        assert!(matches!(level.board.tile_at(0, 0), TileKind::Spawner(_)));
    }

    /// Every glyph the writer puts on a map row reads back as the tile it
    /// was written for. A replay stores its starting board *as* a level
    /// and generated arenas mirror their logs, so a turnstile that came
    /// back facing the other way would deflect every crab the wrong side
    /// on the second play of the same round.
    #[test]
    fn every_tile_glyph_reads_back_as_the_tile_it_was_written_for() {
        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..crate::sim::MAX_PLAYERS as u8 {
            kinds.push(TileKind::Castle(owner));
        }
        for kind in kinds {
            let glyph = tile_glyph(kind);
            assert_eq!(
                tile_from_glyph(glyph),
                Some(kind),
                "{kind:?} was written {glyph:?} and came back as something else"
            );
        }
        // A blank is sand, so a row may be padded with spaces.
        assert_eq!(tile_from_glyph(' '), Some(TileKind::Empty));
        // And a spawner is the one tile the lattice does not carry: it is
        // declared in the header, with the period and facing a glyph has
        // nowhere to put, so the map row under it is plain sand.
        assert_eq!(
            tile_glyph(TileKind::Spawner(Spawner {
                dir: Direction::Right,
                period: 4,
            })),
            '.',
        );
    }

    /// A glyph nobody writes is refused rather than read as sand. These
    /// files are hand-edited, and a typo quietly becoming empty beach is a
    /// level that loads and is not the one that was drawn.
    #[test]
    fn a_glyph_nobody_writes_is_refused_rather_than_read_as_sand() {
        for stray in ['x', '@', '9', '?', '\t'] {
            assert_eq!(tile_from_glyph(stray), None, "{stray:?} meant something");
        }
        let text = "name: T\nposts: 1\nmap:\n+-+-+\n|.|x|\n+-+-+\n|.|.|\n+-+-+\n";
        let err = Level::parse(text).expect_err("read a stray glyph as a tile");
        assert!(err.contains('x'), "the refusal says which glyph: {err}");
    }

    /// A coordinate that is not one is refused with the reason, since
    /// every entity line in the format starts with a pair.
    #[test]
    fn a_coordinate_that_is_not_a_pair_of_numbers_is_refused() {
        assert!(parse_xy("1,1").is_ok(), "the plain form");
        assert_eq!(parse_xy("2,3 rest").expect("a pair"), (2, 3, "rest"));
        for bad in ["11", "1;1", "a,1", "1,b", "1,", ",1", "300,1", "-1,0", ""] {
            assert!(parse_xy(bad).is_err(), "{bad:?} was taken for a coordinate");
        }
    }

    /// The header is `key: value` up to the map, and a line that is not
    /// that is a file this reader cannot be sure it understands.
    #[test]
    fn a_header_line_that_is_not_a_key_and_a_value_is_refused() {
        let err = Level::parse("name T\nmap:\n+-+\n|.|\n+-+\n")
            .expect_err("read a header line with no key");
        assert!(err.contains("key: value"), "{err}");

        // A key this build does not know is refused too, rather than
        // skipped: it means something to whoever wrote it.
        let err = Level::parse("name: T\nweather: fog\nmap:\n+-+\n|.|\n+-+\n")
            .expect_err("read a key it does not know");
        assert!(err.contains("weather"), "{err}");

        // Comments and blank lines before the map are not header lines.
        let commented = Level::parse(
            "# drawn on a train\n\nname: T\nposts: 1\nmap:\n+-+-+\n|.|.|\n+-+-+\n|.|.|\n+-+-+\n",
        );
        assert!(
            commented.is_ok(),
            "a comment before the map is not a bad key: {commented:?}"
        );
    }

    /// A map section has to be a lattice: a wall row, then alternating
    /// tile and wall rows, all the same width. Anything else describes no
    /// board, and read loosely it describes the wrong one.
    #[test]
    fn a_map_that_is_not_a_lattice_is_refused() {
        let cases = [
            ("no map at all", "name: T\nposts: 1\n"),
            ("a map section with nothing in it", "name: T\nmap:\n"),
            (
                "rows of different widths",
                "name: T\nmap:\n+-+-+\n|.|.|\n+-+\n|.|\n+-+\n",
            ),
            ("an even number of rows", "name: T\nmap:\n+-+\n|.|\n"),
        ];
        for (what, text) in cases {
            assert!(
                Level::parse(text).is_err(),
                "{what}: parsed into a board anyway"
            );
        }
    }

    /// What a level is for, when its file does not say: a board with
    /// castles for two is somebody's arena, and a board with one or none
    /// is a puzzle. The stage lists are built by this.
    #[test]
    fn a_level_with_no_kind_of_its_own_is_told_by_its_castles() {
        let puzzle = "name: T\nposts: 1\nmap:\n+-+-+\n|0|.|\n+-+-+\n|.|.|\n+-+-+\n";
        assert_eq!(
            Level::parse(puzzle).expect("a one-castle board").kind,
            LevelKind::Puzzle,
            "one castle is a puzzle"
        );
        let arena = "name: T\nposts: 1\nmap:\n+-+-+\n|0|1|\n+-+-+\n|.|.|\n+-+-+\n";
        assert_eq!(
            Level::parse(arena).expect("a two-castle board").kind,
            LevelKind::Arena,
            "two castles is somewhere to play"
        );
        // And a file that says so is taken at its word.
        let told = "name: T\nkind: puzzle\nposts: 1\nmap:\n+-+-+\n|0|1|\n+-+-+\n|.|.|\n+-+-+\n";
        assert_eq!(
            Level::parse(told)
                .expect("a level that names its kind")
                .kind,
            LevelKind::Puzzle,
        );
    }
}