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
//! 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, MAX_CREATURES, Rules, 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> {
        Level::parse_at(text, None)
    }

    /// [`Level::parse`], with the board built on `seed` instead of the
    /// one the text names, when there is one.
    pub(super) fn parse_at(text: &str, seed: Option<u64>) -> Result<Level, String> {
        let mut lines = text.lines();
        let mut header = parse_header(&mut lines)?;
        if let Some(seed) = seed {
            header.seed = seed;
        }
        if header.crabs.len() + header.gulls.len() > MAX_CREATURES {
            return Err(format!("more than {MAX_CREATURES} crabs and gulls"));
        }
        let mut board = parse_lattice(lines, header.seed)?;
        place_entities(&mut board, &header)?;
        check_tables(&board, &header.tables)?;
        check_roll(&board, header.roll)?;
        let posts = match (header.posts, header.rules.claw_hands) {
            (Some(posts), Some([left, right]))
                if u16::from(posts) != u16::from(left) + u16::from(right) =>
            {
                return Err(format!(
                    "posts: {posts} is not the two hands together ({left} + {right})"
                ));
            }
            (Some(posts), _) => posts,
            // A co-op stage's grant is its two hands: saying it twice is
            // allowed, saying it once is enough.
            (None, Some([left, right])) => left
                .checked_add(right)
                .ok_or("hands: more arrows than a stage can grant")?,
            (None, None) => return Err("missing posts:".to_string()),
        };
        if header.rules.claw_hands.is_none()
            && let Some(&(x, y, _, _)) = header.solution.iter().find(|step| step.3 != 0)
        {
            return Err(format!(
                "solution: {x},{y} names a hand, which only a co-op stage (hands:) has"
            ));
        }
        if header.rules.claw_hands.is_some() && header.kind == Some(LevelKind::Arena) {
            return Err("hands: a beach for a match has no hands".to_string());
        }
        let level = Level {
            name: header.name.ok_or("missing name:")?,
            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.explicit_rule,
            filing: None,
            tables: header.tables,
            roll: header.roll,
            board,
        };
        // A co-op stage is a stage, whatever its castles look like.
        let kind = match level.is_coop() {
            true => LevelKind::Puzzle,
            false => 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,
            filing: None,
            tables: Vec::new(),
            roll: 0,
            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 rules = board.rules();
        let mut out = String::new();
        let _ = writeln!(out, "name: {}", self.name);
        let _ = writeln!(out, "posts: {}", self.posts);
        if let Some([left, right]) = rules.claw_hands {
            let _ = writeln!(out, "hands: {left} {right}");
        }
        // 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 rules.gull_period > 0 {
            let _ = writeln!(out, "gull_period: {}", rules.gull_period);
        }
        if usize::from(rules.gull_cap) != GULL_CAP {
            let _ = writeln!(out, "gull_cap: {}", rules.gull_cap);
        }
        if rules.gull_turnover {
            let _ = writeln!(out, "gull_turnover: on");
        }
        if rules.golden_every > 0 {
            let _ = writeln!(out, "golden_every: {}", rules.golden_every);
        }
        if rules.timed_lock {
            let _ = writeln!(out, "timed_lock: on");
        }
        if rules.sweep_flight {
            let _ = writeln!(out, "sweep_flight: on");
        }
        if rules.whole_flock {
            let _ = writeln!(out, "whole_flock: on");
        }
        if rules.sweep_keeps_worth {
            let _ = writeln!(out, "sweep_keeps_worth: on");
        }
        if rules.fair_spawns {
            let _ = writeln!(out, "fair_spawns: on");
        }
        if let Some(round) = rules.round_length {
            let _ = writeln!(out, "round: {round}");
        }
        if board.wrap() {
            let _ = writeln!(out, "wrap: on");
        }
        if !self.tables.is_empty() {
            let tables: Vec<String> = self.tables.iter().map(u8::to_string).collect();
            let _ = writeln!(out, "seats: {}", tables.join(" "));
        }
        if self.roll > 0 {
            let _ = writeln!(out, "roll: {}", self.roll);
        }
        // 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 !rules.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, seat)| match rules.claw_hands {
                    // The hand that places it, by its claw, on a co-op stage
                    // only: every other stage has the one.
                    Some(_) => format!(
                        "{x},{y} {} {}",
                        dir.letter(),
                        crate::sim::board::claw_of(seat).map_or("?", Handedness::token)
                    ),
                    None => 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)>,
    /// The board's rules as the file states them, each one it does not
    /// mention left at the default.
    rules: Rules,
    /// Whether the file states a `rule:`, which a puzzle without one is
    /// given in [`Level::board`].
    explicit_rule: bool,
    events: bool,
    seed: u64,
    scores: Vec<(u8, u32)>,
    goal: Goal,
    wrap: bool,
    /// `None` when the file predates the editor's puzzle/arena toggle.
    kind: Option<LevelKind>,
    /// `seats:`, the tables the beach is built for (see [`Level::tables`]).
    tables: Vec<u8>,
    /// `roll:`, the open beach's strip (see [`Level::roll`]).
    roll: u8,
}

impl Default for Header {
    fn default() -> Header {
        Header {
            name: None,
            posts: None,
            solution: Vec::new(),
            crabs: Vec::new(),
            spawners: Vec::new(),
            gulls: Vec::new(),
            // 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`].
            rules: Rules::default(),
            explicit_rule: false,
            events: false,
            // An arbitrary but fixed default, so a level file without a
            // `seed:` still replays identically everywhere.
            seed: 0x7ead_0001,
            scores: Vec::new(),
            goal: Goal::AllCrabs,
            wrap: false,
            kind: None,
            tables: Vec::new(),
            roll: 0,
        }
    }
}

/// 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.rules.gull_period = value
                    .parse::<u32>()
                    .map_err(|e| format!("gull_period: {e}"))?;
            }
            "gull_cap" => {
                self.rules.gull_cap = value.parse::<u8>().map_err(|e| format!("gull_cap: {e}"))?;
            }
            "gull_turnover" => self.rules.gull_turnover = value == "on",
            "timed_lock" => self.rules.timed_lock = value == "on",
            "sweep_flight" => self.rules.sweep_flight = value == "on",
            "whole_flock" => self.rules.whole_flock = value == "on",
            "sweep_keeps_worth" => self.rules.sweep_keeps_worth = value == "on",
            "fair_spawns" => self.rules.fair_spawns = value == "on",
            "golden_every" => {
                self.rules.golden_every = crate::sim::board::golden_every(
                    value
                        .parse::<u32>()
                        .map_err(|e| format!("golden_every: {e}"))?,
                )?;
            }
            "round" => {
                self.rules.round_length =
                    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.rules.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",
            "seats" => {
                let mut tables = Vec::new();
                for part in value.split_whitespace() {
                    let seats = part.parse::<u8>().map_err(|e| format!("seats: {e}"))?;
                    if !(2..=crate::sim::MAX_PLAYERS as u8).contains(&seats) {
                        return Err(format!(
                            "seats: {seats} is not a table of 2 to {}",
                            crate::sim::MAX_PLAYERS
                        ));
                    }
                    if tables.last().is_some_and(|&last| last >= seats) {
                        return Err("seats: list each table once, smallest first".to_string());
                    }
                    tables.push(seats);
                }
                if tables.is_empty() {
                    return Err("seats: expected the table sizes, as `seats: 2 4`".to_string());
                }
                self.tables = tables;
            }
            "roll" => {
                self.roll = value.parse::<u8>().map_err(|e| format!("roll: {e}"))?;
                if self.roll == 0 {
                    return Err("roll: a strip is at least one column wide".to_string());
                }
            }
            "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.rules.signpost_cap = cap;
                self.rules.cap_policy = policy;
                self.explicit_rule = true;
            }
            "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 mut words = rest.split_whitespace();
                    let dir = parse_dir(words.next().unwrap_or(""))?;
                    // A trailing claw names the co-op hand that places it;
                    // none is P1's, as every solo stage's arrow is.
                    let seat = match words.next() {
                        None => 0,
                        Some(claw) => crate::sim::board::seat_of_claw(
                            Handedness::from_token(claw)
                                .ok_or_else(|| format!("solution: bad hand {claw:?}"))?,
                        ),
                    };
                    self.solution.push((x, y, dir, seat));
                }
            }
            "hands" => {
                let mut counts = value
                    .split_whitespace()
                    .map(|n| n.parse::<u8>().map_err(|e| format!("hands: {e}")));
                let (Some(left), Some(right), None) = (counts.next(), counts.next(), counts.next())
                else {
                    return Err("hands: expected P1's and P2's counts, as `hands: 1 1`".to_string());
                };
                self.rules.claw_hands = Some([left?, right?]);
            }
            // The medal lines of the timed challenges this build no longer
            // has. A level file written for them, or hand-edited from one,
            // still loads: the lines are read past and dropped.
            "silver" | "gold" => {}
            "map" => return Ok(HeaderLine::MapFollows),
            other => return Err(format!("unknown key {other:?}")),
        }
        Ok(HeaderLine::Read)
    }
}

impl Level {
    /// Whether a `seats:` line may name a table of `seats` on `board`: one
    /// the beach has castles for, in order. A bigger table would seat a
    /// player with nowhere to bank. The rule a file is refused by, and the
    /// one the editor drops a carried table by once its castles go.
    pub fn table_fits(board: &Board, seats: u8) -> bool {
        seats <= board.table_seats().unwrap_or(0)
    }

    /// Whether `board` may roll by `roll` columns: no roll at all, or an
    /// open beach made of whole strips that wide, which rolled by a strip
    /// is the same beach with its castles moved round the world.
    pub fn roll_fits(board: &Board, roll: u8) -> bool {
        roll == 0 || (board.wrap() && board.width().is_multiple_of(roll))
    }
}

/// A `seats:` line names only tables the beach has castles for
/// ([`Level::table_fits`]).
fn check_tables(board: &Board, tables: &[u8]) -> Result<(), String> {
    let castles = board.table_seats().unwrap_or(0);
    match tables
        .iter()
        .find(|&&seats| !Level::table_fits(board, seats))
    {
        Some(seats) => Err(format!(
            "seats: a table of {seats} on a beach with {castles} castles in order"
        )),
        None => Ok(()),
    }
}

/// A `roll:` line is for an open beach made of whole strips
/// ([`Level::roll_fits`]).
fn check_roll(board: &Board, roll: u8) -> Result<(), String> {
    if Level::roll_fits(board, roll) {
        return Ok(());
    }
    if !board.wrap() {
        return Err("roll: only an open beach (`wrap: on`) rolls round".to_string());
    }
    Err(format!(
        "roll: {roll} columns do not divide the beach's {}",
        board.width()
    ))
}

/// 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(())
    };
    // The board's switches first: a creature turns off a wall the moment it
    // is placed, and on an open beach the rim is no wall. Placed before
    // `wrap: on` was read, a crab on the edge facing out was turned round
    // by a wall the level does not have.
    *board.rules_mut() = header.rules;
    if header.wrap {
        board.set_wrap(true);
    }
    if header.events {
        board.set_events_enabled(true);
    }
    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"));
        }
        // A spawner is a tile, so it would take the place of whatever the
        // map drew there: a castle under a `spawner:` line was erased
        // without a word, and with it a seat or a puzzle's only bank.
        // Refused like a crab on a rock, and so is a second spawner on
        // the same tile, which would quietly overrule the first.
        let under = match board.tile_at(x, y) {
            TileKind::Empty => None,
            TileKind::Rock => Some("a rock"),
            TileKind::Castle(_) => Some("a castle"),
            TileKind::Turnstile { .. } => Some("a log"),
            TileKind::Kelp => Some("kelp"),
            TileKind::Pool => Some("a pool"),
            TileKind::Spawner(_) => Some("another spawner"),
        };
        if let Some(under) = under {
            return Err(format!("spawner at ({x},{y}) is on {under}"));
        }
        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);
    }
    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)
    }

    /// A level with more creatures than any beach holds is refused before
    /// a board is built for it.
    #[test]
    fn a_level_with_a_crowd_past_the_cap_is_refused() {
        let crowd = |n: usize| "crab: 0,0 R R common\n".repeat(n);
        let most = level_with(&crowd(MAX_CREATURES)).expect("the most that reads");
        assert_eq!(most.crab_count as usize, MAX_CREATURES);
        let err = level_with(&crowd(MAX_CREATURES + 1)).expect_err("one over");
        assert!(err.contains(&MAX_CREATURES.to_string()), "{err}");
        let flock = format!("{}gull: 0,0 R\n", crowd(MAX_CREATURES));
        assert!(level_with(&flock).is_err(), "gulls count too");
    }

    /// On an open beach the rim is no wall, so a creature on the edge
    /// facing out keeps facing out: it walks round the seam rather than
    /// being turned by a wall the level does not have.
    #[test]
    fn a_creature_facing_off_an_open_beach_keeps_its_heading() {
        let text = "name: T\nposts: 1\nwrap: on\ncrab: 0,1 L L common\ngull: 2,0 U\n\
                    map:\n+-+-+-+\n|. . .|\n+ + + +\n|. . .|\n+-+-+-+\n";
        let board = Level::parse(text).expect("parses").board();
        assert_eq!(board.crabs()[0].dir, Direction::Left, "the crab");
        assert_eq!(board.gulls()[0].dir, Direction::Up, "the gull");
        // Walled in, the same crab turns, as ever.
        let closed = Level::parse(&text.replace("wrap: on\n", ""))
            .expect("parses")
            .board();
        assert_ne!(closed.crabs()[0].dir, Direction::Left);
    }

    /// Every goal a stage 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}");
        }
    }

    /// A spawner is a tile, so one placed over anything but sand would
    /// erase what the map drew: a castle under it took a seat, or a
    /// puzzle's only bank, with nothing said. Each is refused by name.
    #[test]
    fn a_spawner_over_a_drawn_tile_is_refused() {
        let map = |line: &str| {
            Level::parse(&format!(
                "name: T\nposts: 1\n{line}\nmap:\n+-+-+-+\n|0|#|T|\n+-+-+-+\n|K|~|.|\n+-+-+-+\n"
            ))
        };
        for (x, y, what) in [
            (0, 0, "a castle"),
            (1, 0, "a rock"),
            (2, 0, "a log"),
            (0, 1, "kelp"),
            (1, 1, "a pool"),
        ] {
            let err = map(&format!("spawner: {x},{y} R 4")).unwrap_err();
            assert!(err.contains(&format!("is on {what}")), "{err}");
        }
        let err = map("spawner: 2,1 R 4\nspawner: 2,1 L 8").unwrap_err();
        assert!(err.contains("is on another spawner"), "{err}");
        let level = map("spawner: 2,1 R 4").expect("sand takes a spawner");
        assert_eq!(level.board.tile_at(0, 0), TileKind::Castle(0));
    }

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