pinch-points 0.1.0

A fast, kid-friendly crab-routing game: route streams of crabs into your sandcastle before the tide comes in
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
//! Match setup: the intermediary screen between the menu and a local versus
//! round. Pick the seat count, how many seats the AI plays, the map, gull
//! pressure, and round length; Enter starts the match.

use crate::app::Screen;
use crate::app::cycle::Cycle;
use crate::app::i18n::fill;
use crate::app::palette;
use crate::sim::BotLevel;
use crate::sim::MAX_PLAYERS;
use crate::transport::MatchTerms;
use bevy::prelude::*;

/// The playable beach for a local match.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum MapChoice {
    #[default]
    Classic,
    GenSmall,
    GenClassic,
    GenLarge,
    GenXl,
    /// Open ocean: a generated beach with no edges. Appended rather than
    /// slotted in beside its size, because the index is what a `Start`
    /// datagram carries, and reordering would silently change which beach a
    /// host is inviting everyone to.
    GenOcean,
    /// A beach somebody built in the editor. Which one is not on the wire:
    /// the beach itself rides along with the invitation, because no peer
    /// but the host has the file it came from.
    Custom,
}

impl MapChoice {
    pub const ALL: [MapChoice; 7] = [
        MapChoice::Classic,
        MapChoice::GenSmall,
        MapChoice::GenClassic,
        MapChoice::GenLarge,
        MapChoice::GenXl,
        MapChoice::GenOcean,
        MapChoice::Custom,
    ];

    pub fn size(self) -> (u8, u8) {
        match self {
            MapChoice::Classic | MapChoice::GenClassic => (12, 9),
            MapChoice::GenSmall => (9, 7),
            MapChoice::GenLarge => (16, 11),
            MapChoice::GenXl => (20, 13),
            MapChoice::GenOcean => (16, 11),
            // Whatever the level says; the board arrives built, so this is
            // only used to decide whether a table fits, and a handmade
            // beach is offered only when it does.
            MapChoice::Custom => (20, 13),
        }
    }

    /// Whether the beach has edges. Open ocean does not: a creature walking
    /// off one side comes back on the other, the same wrap the campaign
    /// teaches at level 26.
    pub fn wraps(self) -> bool {
        matches!(self, MapChoice::GenOcean)
    }
}

/// How aggressive the ambient gull spawner is.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum GullPressure {
    Calm,
    #[default]
    Normal,
    Frenzy,
}

impl GullPressure {
    pub const ALL: [GullPressure; 3] = [
        GullPressure::Calm,
        GullPressure::Normal,
        GullPressure::Frenzy,
    ];

    pub fn period(self) -> u32 {
        match self {
            GullPressure::Calm => 340,
            GullPressure::Normal => 240,
            GullPressure::Frenzy => 150,
        }
    }
}

/// Round length.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum RoundLength {
    Short,
    #[default]
    Standard,
    Long,
}

impl RoundLength {
    pub const ALL: [RoundLength; 3] =
        [RoundLength::Short, RoundLength::Standard, RoundLength::Long];

    pub fn ticks(self) -> u32 {
        match self {
            RoundLength::Short => 2 * 60 * crate::sim::TICKS_PER_SECOND,
            RoundLength::Standard => 3 * 60 * crate::sim::TICKS_PER_SECOND,
            RoundLength::Long => 5 * 60 * crate::sim::TICKS_PER_SECOND,
        }
    }
}

impl crate::app::cycle::Cycle for MapChoice {
    const VARIANTS: &'static [Self] = &Self::ALL;
}
impl crate::app::cycle::Cycle for GullPressure {
    const VARIANTS: &'static [Self] = &Self::ALL;
}
impl crate::app::cycle::Cycle for RoundLength {
    const VARIANTS: &'static [Self] = &Self::ALL;
}
impl crate::app::cycle::Cycle for crate::sim::BotLevel {
    const VARIANTS: &'static [Self] = &BOT_LEVELS;
}

/// One match-setup row; input and render both match on this. The AI-level
/// rows are per seat, one for each seat the AI can take, and the ones
/// beyond the current AI count are hidden.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Row {
    Players,
    Bots,
    /// Difficulty for the `n`-th AI seat, counting down from the top seat.
    BotLevel(u8),
    Map,
    Gulls,
    Round,
    Mode,
    /// What to call seat `n`. One row per seat in the match; typing into it
    /// renames that seat everywhere the game mentions it.
    Name(u8),
}

/// The most seats the AI can hold: everyone but one human.
pub const MAX_BOTS: usize = MAX_PLAYERS - 1;

/// Seats a four-castle beach holds. Past this the match needs a generated
/// arena wide enough for the two long-edge castles.
pub const CLASSIC_SEATS: u8 = 4;
/// The narrowest board that seats five or six: the two extra castles sit
/// mid-edge, and they need room between the corners and the spawner holes.
pub const WIDE_ENOUGH: u8 = 16;

impl Row {
    pub const ALL: [Row; 6 + MAX_BOTS + MAX_PLAYERS] = [
        Row::Players,
        Row::Bots,
        Row::BotLevel(0),
        Row::BotLevel(1),
        Row::BotLevel(2),
        Row::BotLevel(3),
        Row::BotLevel(4),
        Row::Map,
        Row::Gulls,
        Row::Round,
        Row::Mode,
        // Last on the list: the rows above are the ones every match needs,
        // and Enter on a name row types instead of starting the match.
        Row::Name(0),
        Row::Name(1),
        Row::Name(2),
        Row::Name(3),
        Row::Name(4),
        Row::Name(5),
    ];
}

const ROWS: usize = Row::ALL.len();

/// The configured local match. Persists between rounds so "again!" needs no
/// re-setup; `armed` is set when the player launches from this screen and
/// consumed by `load_versus`.
#[derive(Resource)]
pub struct MatchConfig {
    pub seats: u8,
    pub bots: u8,
    /// Difficulty per seat, so one player can spar with a fierce rival and
    /// an easy one at the same table. Only the AI-held seats are read.
    pub bot_levels: [BotLevel; MAX_PLAYERS],
    pub map: MapChoice,
    /// Which handmade beach, when `map` is [`MapChoice::Custom`]. An index
    /// into [`custom_beaches`], which is read fresh each time the dial is
    /// turned: the editor may have saved another one since.
    pub custom: usize,
    pub gulls: GullPressure,
    pub round: RoundLength,
    /// Best-of-5 series instead of a single round.
    pub series: bool,
    /// True when the next versus round should be built from this config.
    pub armed: bool,
}

impl Default for MatchConfig {
    fn default() -> Self {
        MatchConfig {
            seats: 2,
            bots: 0,
            bot_levels: [BotLevel::Normal; MAX_PLAYERS],
            map: MapChoice::Classic,
            custom: 0,
            gulls: GullPressure::Normal,
            round: RoundLength::Standard,
            series: false,
            armed: false,
        }
    }
}

pub const BOT_LEVELS: [BotLevel; 3] = [BotLevel::Easy, BotLevel::Normal, BotLevel::Hard];

/// The wire form of this screen's choices, for a host to send and every peer
/// to build the same beach from. `teams` and `seed` are not on this screen:
/// teams is a setting, and the seed is drawn when the match launches.
pub fn terms(config: &MatchConfig, teams: crate::app::teams::TeamMode, seed: u64) -> MatchTerms {
    MatchTerms {
        bots: config.bots,
        // Every AI seat plays at the top seat's level: the wire carries one
        // difficulty, and a lobby has no per-seat rows to fill anyway.
        bot_level: config.bot_levels[usize::from(config.seats.saturating_sub(1))].index() as u8,
        map: config.map.index() as u8,
        gulls: config.gulls.index() as u8,
        round: config.round.index() as u8,
        teams: teams.index() as u8,
        seed,
        series: u8::from(config.series),
    }
}

/// A [`MatchConfig`] and team mode that read back the same dials a set of
/// wire [`MatchTerms`] carries, for painting a joiner's terms card: it is
/// shown the match it is joining, not its own setup screen's idea of one.
/// The seat count is the humans plus AI the terms name; `custom`/`armed`
/// are display-only here. A `Custom` map cannot be named from the wire (the
/// beach travels as bytes, not an index), so it reads as the generated size
/// it will actually play on.
pub fn config_from_terms(terms: &MatchTerms) -> (MatchConfig, crate::app::teams::TeamMode) {
    let bots = terms.bots.min(MAX_PLAYERS as u8);
    let config = MatchConfig {
        seats: bots.max(2),
        bots,
        bot_levels: [BotLevel::from_index(usize::from(terms.bot_level)); MAX_PLAYERS],
        map: MapChoice::from_index(usize::from(terms.map)),
        custom: 0,
        gulls: GullPressure::from_index(usize::from(terms.gulls)),
        round: RoundLength::from_index(usize::from(terms.round)),
        series: terms.series == 1,
        armed: false,
    };
    (
        config,
        crate::app::teams::TeamMode::from_index(usize::from(terms.teams)),
    )
}

/// The same terms on a new beach: a fresh seed, and the map stepped on as
/// a local series steps it, through [`next_map`] and its guards. Everything
/// the table agreed (seat count, gull pressure, round length, scoring) is
/// kept, because a series is one match played several times, not several
/// matches.
///
/// `seats` is the table as it sits, which the terms themselves do not
/// carry: it is what keeps a table of five off the four-castle beaches.
/// The shelf is not consulted, because online the beach a handmade round
/// is played on rides in the invitation itself, unchanged from round to
/// round (`net/rounds.rs` resends it), so `Custom` is not a stop the terms
/// can step onto: with no shelf the stepper walks past it.
pub fn next_round_terms(terms: MatchTerms, seats: u8, seed: u64) -> MatchTerms {
    let mut config = MatchConfig {
        map: MapChoice::from_index(usize::from(terms.map)),
        seats,
        ..MatchConfig::default()
    };
    next_map(&mut config, &CustomBeaches::default());
    MatchTerms {
        map: config.map.index() as u8,
        seed,
        ..terms
    }
}

/// Whether `map` has room for a table of `seats`. Five and six castles
/// need a wide beach: the two extra sit mid-edge, and the handcrafted
/// classic arena and the small generated one hold four, clamping a bigger
/// table's castles down to it. A handmade beach answers by its castle
/// count instead (see [`CustomBeaches::fitting`]).
pub fn holds(map: MapChoice, seats: u8) -> bool {
    seats <= CLASSIC_SEATS || map.size().0 >= WIDE_ENOUGH
}

/// Step the map on for the next round of a series: the dial's own step
/// ([`cycle_map`], which walks the shelf and skips it when empty), and
/// then on again past any beach the table does not fit on.
///
/// The one place a series and the dial differ: the dial, turned onto a
/// small beach by hand, drops the seats it cannot hold, because the hand
/// on it asked for that beach. A series asked for nobody to leave the
/// table, so it keeps the seats and skips the beach. Before this the
/// series stepped with a plain `cycled(true)`, and a table of five went
/// from the open ocean onto `Custom` with nothing on the shelf, then onto
/// the classic arena with two of them castle-less.
pub fn next_map(config: &mut MatchConfig, beaches: &CustomBeaches) {
    // Bounded by the number of stops there are: every wide beach holds
    // every table, so this returns well before the bound, but a loop over
    // a dial should not be able to spin.
    for _ in 0..MapChoice::ALL.len() + beaches.0.len() {
        cycle_map(config, true, beaches);
        if holds(config.map, config.seats) {
            return;
        }
    }
}

/// Keep the map somewhere the table can play after something other than
/// the dial moved: the seat count, or the shelf between two visits to the
/// screen. Off `Custom` when no beach seats everyone (onto the stop after
/// it, as the dial itself steps), onto the widest beach when five or six
/// are seated and the map holds four. Without this the row kept reading a
/// beach the match would not be played on: `Custom` with nothing fitting
/// launched a generated 20x13 arena under the classic arena's name.
pub fn settle_map(config: &mut MatchConfig, beaches: &CustomBeaches) {
    if config.map == MapChoice::Custom {
        match beaches.fitting(config.seats).len() {
            0 => config.map = MapChoice::Custom.cycled(true),
            fitting => config.custom = config.custom.min(fitting - 1),
        }
    }
    if !holds(config.map, config.seats) {
        config.map = MapChoice::GenXl;
    }
}

/// The board those terms describe, built through the same path a local match
/// uses so online and offline cannot drift apart.
/// The handmade beaches on this machine, as of the last time a screen that
/// offers them opened.
///
/// A resource and not a function call, because the two places that read it
/// are drawn every frame: `map_label` used to go to the disk and parse
/// every level file sixty times a second, which is a strange thing for a
/// menu to do.
#[derive(Resource, Default)]
pub struct CustomBeaches(pub Vec<Beach>);

/// One handmade beach on the shelf, with the bytes it would travel as.
///
/// Packed once when the shelf is read rather than once per invitation:
/// the size decides whether the beach can be sent at all, and that answer
/// is wanted by a menu label drawn every frame.
pub struct Beach {
    pub level: crate::sim::Level,
    wire: Vec<u8>,
}

impl Beach {
    fn new(level: crate::sim::Level) -> Beach {
        let wire = crate::lzw::compress(level.to_text().as_bytes(), 8);
        Beach { level, wire }
    }

    /// Too big to fit an invitation. Such a beach is still perfectly
    /// playable at this table; it just cannot travel to another one, so
    /// the dial says so rather than letting the host find out by having
    /// nobody join.
    pub fn too_big_to_send(&self) -> bool {
        self.wire.len() > crate::transport::MAX_BEACH_BYTES
    }
}

/// Re-read the shelf. Runs on entering the screens that offer a beach, so
/// one saved in the editor a moment ago is on the dial.
pub fn refresh_custom_beaches(mut beaches: ResMut<CustomBeaches>) {
    beaches.0 = crate::app::campaign::custom_arenas(crate::app::campaign::load_custom_levels())
        .into_iter()
        .map(Beach::new)
        .collect();
}

impl CustomBeaches {
    /// The ones that could host a match at this size: a versus arena wants
    /// a castle per seat, and a puzzle built for one crab has one.
    pub fn fitting(&self, seats: u8) -> Vec<&Beach> {
        self.0
            .iter()
            .filter(|beach| beach.level.seats() >= seats)
            .collect()
    }
}

/// The aside for the map row when the shelf has beaches on it and this
/// table is too big for every one of them.
///
/// The dial skipping an empty stop is right - a press that changes nothing
/// is a dead press - but it left the reason unsaid. A beach with two
/// castles simply stopped being offered the moment a third player joined
/// the table, which from the other side of the screen looks like a beach
/// the game has lost.
pub fn beaches_note(
    config: &MatchConfig,
    tr: &crate::app::i18n::Tr,
    beaches: &CustomBeaches,
) -> Option<String> {
    let all_too_small = !beaches.0.is_empty() && beaches.fitting(config.seats).is_empty();
    all_too_small.then(|| fill(tr.map_none_seats, &[("n", &config.seats.to_string())]))
}

/// Turn the map dial one step, walking the built-in beaches and then the
/// handmade ones. `Custom` is one stop on `MapChoice`, so the dial stays
/// on it while there are more beaches to walk through, and steps off when
/// it runs out. With nothing saved it is skipped entirely: an empty stop
/// on a dial is a dead press.
pub fn cycle_map(config: &mut MatchConfig, right: bool, beaches: &CustomBeaches) {
    let beaches = beaches.fitting(config.seats).len();
    if config.map == MapChoice::Custom {
        let next = config.custom as i64 + if right { 1 } else { -1 };
        if (0..beaches as i64).contains(&next) {
            config.custom = next as usize;
            return;
        }
    }
    config.map = config.map.cycled(right);
    if config.map == MapChoice::Custom {
        if beaches == 0 {
            config.map = config.map.cycled(right);
        } else {
            // Entering the run from the far side lands on its far end.
            config.custom = if right { 0 } else { beaches - 1 };
        }
    }
}

/// What the map dial reads, which for a handmade beach is its own name.
///
/// `Custom` with no beach that seats the table (the shelf changed, or the
/// table grew, since it was chosen; [`settle_map`] steps off it where it
/// can) reads as the beach that will actually be played: both the local
/// launch and the wire build a generated 20x13 arena for it, which is the
/// XL beach, so that is the name shown. It used to say "Classic".
pub fn map_label(
    config: &MatchConfig,
    tr: &crate::app::i18n::Tr,
    beaches: &CustomBeaches,
) -> String {
    if config.map == MapChoice::Custom {
        return beaches
            .fitting(config.seats)
            .get(config.custom)
            .map_or_else(
                || tr.map_names[MapChoice::GenXl.index()].to_string(),
                |beach| {
                    // A beach too big to travel is marked on the dial. It
                    // plays here either way, so the label says what is lost
                    // rather than hiding the beach the author chose.
                    let template = match beach.too_big_to_send() {
                        true => tr.map_custom_local,
                        false => tr.map_custom,
                    };
                    fill(template, &[("n", &beach.level.name)])
                },
            );
    }
    tr.map_names[config.map.index()].to_string()
}

/// The beach the host is sending, compressed, or empty when the round is
/// played on one both peers can build from a seed.
///
/// `seats` is how many turned up, not how many the host had in mind when
/// it picked: a handmade beach with two castles cannot hold a table of
/// five, and the seats without one could never score. A beach that no
/// longer fits is dropped here, and the round falls back to the generated
/// arena the terms name.
pub fn beach_bytes(config: &MatchConfig, seats: u8, beaches: &CustomBeaches) -> Vec<u8> {
    if config.map != MapChoice::Custom {
        return Vec::new();
    }
    beaches
        .fitting(config.seats)
        .get(config.custom)
        .filter(|beach| beach.level.seats() >= seats)
        .filter(|beach| {
            // A beach that will not fit a datagram is dropped here, where
            // the fallback is a generated arena everybody can build. Sent
            // anyway it would be truncated on arrival and refused, and the
            // joiner would wait out an invitation that never decoded.
            let sendable = !beach.too_big_to_send();
            if !sendable {
                warn!(
                    "{:?} is too big to send ({} bytes packed, {} allowed): \
                     the round falls back to a generated beach",
                    beach.level.name,
                    beach.wire.len(),
                    crate::transport::MAX_BEACH_BYTES
                );
            }
            sendable
        })
        .map(|beach| beach.wire.clone())
        .unwrap_or_default()
}

/// The beach those bytes describe, if they describe one.
pub fn beach_from(bytes: &[u8]) -> Option<crate::sim::Level> {
    let text = String::from_utf8(crate::lzw::decompress(bytes, 8)?).ok()?;
    crate::sim::Level::parse(&text).ok()
}

/// The board a set of terms describes, with the host's handmade beach if
/// one came with them. Falls back to the terms alone when the bytes are
/// missing or unreadable: a round on the wrong beach is a desync, but a
/// round that never starts is worse, and the hash check will say so.
pub fn board_from(terms: &MatchTerms, seats: u8, beach: &[u8]) -> crate::sim::Board {
    let Some(level) = beach_from(beach) else {
        return board_for(terms, seats);
    };
    let mut board = level.board();
    board.set_gull_period(GullPressure::from_index(usize::from(terms.gulls)).period());
    board.set_round_length(Some(
        RoundLength::from_index(usize::from(terms.round)).ticks(),
    ));
    board
}

pub fn board_for(terms: &MatchTerms, seats: u8) -> crate::sim::Board {
    let map = MapChoice::from_index(usize::from(terms.map));
    let (w, h) = map.size();
    let mut board = if map == MapChoice::Classic {
        crate::sim::classic_arena_seeded(terms.seed, false, seats)
    } else {
        crate::sim::generate_arena(terms.seed, seats, w, h)
    };
    board.set_wrap(map.wraps());
    board.set_gull_period(GullPressure::from_index(usize::from(terms.gulls)).period());
    board.set_round_length(Some(
        RoundLength::from_index(usize::from(terms.round)).ticks(),
    ));
    board
}

/// Which seats the AI holds under these terms: the top `bots` of `seats`.
pub fn bot_seats_from(terms: &MatchTerms, seats: u8) -> [Option<BotLevel>; MAX_PLAYERS] {
    let level = BotLevel::from_index(usize::from(terms.bot_level));
    let mut out = [None; MAX_PLAYERS];
    for seat in seats.saturating_sub(terms.bots)..seats {
        if let Some(slot) = out.get_mut(usize::from(seat)) {
            *slot = Some(level);
        }
    }
    out
}

mod screen;
pub use screen::*;
#[cfg(test)]
use screen::{LABEL_W, ROW_FONT, VALUE_W, ai_seat, cycle_ai_level, live_rows, row_text};

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

    /// Every row fits the two cells that hold it, in every language, on
    /// every stop of every dial.
    ///
    /// The card used to be one cell per row with the label padded out by
    /// `{:<15}`, and Rust counts that width in `char`s, which is not what
    /// either shipped face draws. Four languages ran past fifteen and
    /// pushed the dial right on those rows alone; Japanese fell short of
    /// fifteen and still came out wider, because its face draws a full em
    /// where DejaVu draws 0.602. Two cells of a fixed pixel width have no
    /// opinion about any of that, and this measures in the same pixels
    /// they are declared in.
    #[test]
    fn every_row_fits_its_cell_in_every_language() {
        use crate::app::i18n::metrics::text_px;
        use crate::app::settings::{GameSettings, NAME_MAX};
        for lang in crate::app::i18n::ALL_LANGS {
            let mut settings = GameSettings {
                language: lang,
                ..GameSettings::default()
            };
            // A seat named to the hilt: the naming row shows the name, a
            // caret and the hint, and all three have to share the cell.
            settings.names[0] = "M".repeat(NAME_MAX);
            let tr = settings.tr();
            for seats in 2..=MAX_PLAYERS as u8 {
                for bots in 0..seats {
                    for map in MapChoice::ALL {
                        // A handmade beach's name is the player's, up to
                        // twenty-eight characters of it, and no cell on
                        // any screen is built to hold that. It clips, the
                        // way a typed name clips on the settings card.
                        if map == MapChoice::Custom {
                            continue;
                        }
                        let config = MatchConfig {
                            seats,
                            bots,
                            bot_levels: [BotLevel::Normal; MAX_PLAYERS],
                            map,
                            gulls: GullPressure::Frenzy,
                            round: RoundLength::Long,
                            series: true,
                            ..MatchConfig::default()
                        };
                        for row in Row::ALL {
                            // Both states of the one row that is typed
                            // into rather than stepped through.
                            for naming in [None, Some(0)] {
                                let (label, value) = row_text(
                                    tr,
                                    &config,
                                    &settings,
                                    &CustomBeaches::default(),
                                    naming,
                                    row,
                                );
                                let label_w = text_px(&label, ROW_FONT);
                                assert!(
                                    label_w <= LABEL_W,
                                    "{row:?} in {lang:?}: label {label:?} is \
                                     {label_w:.1}px, and the cell holds {LABEL_W}"
                                );
                                let value_w = text_px(&value, ROW_FONT);
                                assert!(
                                    value_w <= VALUE_W,
                                    "{row:?} in {lang:?}: value {value:?} is \
                                     {value_w:.1}px, and the cell holds {VALUE_W}"
                                );
                            }
                        }
                    }
                }
            }
        }
    }

    /// The card has to fit the window the interface was drawn for, the
    /// same as the settings card does. One column here rather than two, so
    /// there is room, but not so much that a cell can be widened without
    /// looking.
    #[test]
    fn the_card_fits_the_window_it_was_drawn_for() {
        let card = LABEL_W + VALUE_W + 2.0 * 10.0 + 2.0 * 22.0;
        assert!(
            card <= crate::app::settings::DESIGN_W,
            "the match card is {card}px of the {}px it is allowed",
            crate::app::settings::DESIGN_W
        );
    }

    /// The point of sending the beach at all: a level the joiner has never
    /// seen has to arrive whole, and arrive as the same board the host is
    /// playing on. A seed cannot describe a beach somebody drew.
    #[test]
    fn a_handmade_beach_survives_the_wire() {
        let text = "name: Sent Beach\nposts: 2\ncrab: 0,1 R R common\nmap:\n\
                    +-+-+-+-+-+\n|. . . . .|\n+ + + + + +\n|. . . . 0|\n\
                    + + + + + +\n|. . . . .|\n+-+-+-+-+-+\n";
        let level = crate::sim::Level::parse(text).expect("a level");
        let packed = crate::lzw::compress(level.to_text().as_bytes(), 8);
        // Small enough to ride in a datagram, which is the whole reason it
        // is compressed rather than sent as the text it came from.
        assert!(packed.len() < 512, "{} bytes", packed.len());
        let back = beach_from(&packed).expect("reads back");
        assert_eq!(back.name, "Sent Beach");
        assert_eq!(back.to_text(), level.to_text(), "byte for byte");
    }

    /// The two beaches at the ends of what the editor can build: the
    /// biggest sensible one has to travel, and the biggest possible one has
    /// to be refused rather than truncated on arrival.
    ///
    /// The wire test can only check the number [`MAX_BEACH_BYTES`] promises;
    /// this checks that the promise is about beaches a player can actually
    /// paint, which is what an assumed four hundred bytes never did.
    #[test]
    fn the_biggest_beaches_the_editor_builds_are_sent_or_refused() {
        use crate::sim::{Board, CrabKind, Direction, Handedness, LevelKind, Spawner, TileKind};
        let full_size = || Board::new(20, 13, 0xBEEF);
        let seat_it = |board: &mut Board| {
            for owner in 0..MAX_PLAYERS as u8 {
                board.set_tile(owner, 0, TileKind::Castle(owner));
            }
        };
        let as_beach = |board: Board| {
            Beach::new(
                crate::sim::Level::from_board("A Beach With A Long Name", 3, board)
                    .with_kind(LevelKind::Arena),
            )
        };

        // A busy beach: every seat, rocks, holes and walls all over it.
        let mut busy = full_size();
        seat_it(&mut busy);
        for x in 0..20u8 {
            for y in 1..13u8 {
                if (x + y).is_multiple_of(3) {
                    busy.set_tile(x, y, TileKind::Rock);
                }
                if (x + y).is_multiple_of(7) {
                    busy.set_tile(
                        x,
                        y,
                        TileKind::Spawner(Spawner {
                            dir: Direction::Right,
                            period: 60,
                        }),
                    );
                }
                if (x * y).is_multiple_of(5) {
                    busy.set_wall(x, y, Direction::Up, true);
                }
            }
        }
        let busy = as_beach(busy);
        assert!(
            !busy.too_big_to_send(),
            "a beach anyone would build must travel: {} bytes",
            busy.wire.len()
        );

        // And the worst case: a crab on every free tile, which the editor
        // will happily let an author paint. Each one is a header line of
        // its own, so the text runs to thousands of characters.
        let mut soup = full_size();
        seat_it(&mut soup);
        for x in 0..20u8 {
            for y in 0..13u8 {
                if soup.tile_at(x, y) == TileKind::Empty {
                    soup.spawn_crab(
                        x,
                        y,
                        Direction::Right,
                        Handedness::Left,
                        CrabKind::Sparkling,
                    );
                }
            }
        }
        let soup = as_beach(soup);
        assert!(
            soup.too_big_to_send(),
            "{} bytes was expected to be over the line",
            soup.wire.len()
        );
        let config = MatchConfig {
            map: MapChoice::Custom,
            seats: 2,
            custom: 0,
            ..MatchConfig::default()
        };
        assert!(
            beach_bytes(&config, 2, &CustomBeaches(vec![soup])).is_empty(),
            "an oversized beach is dropped, not sent in pieces"
        );
    }

    /// A beach the host picked for two cannot hold the five who turned up:
    /// three seats would have no castle and could never score. It is
    /// dropped at launch and the round falls back to the terms.
    #[test]
    fn a_beach_too_small_for_the_table_is_not_sent() {
        let two = crate::sim::Level::parse(
            "name: Two\nposts: 1\ncrab: 0,1 R R common\nmap:\n\
             +-+-+-+\n|0 . .|\n+ + + +\n|. . 1|\n+ + + +\n|. . .|\n+-+-+-+\n",
        )
        .expect("a level");
        let shelf = CustomBeaches(vec![Beach::new(two)]);
        let config = MatchConfig {
            map: MapChoice::Custom,
            seats: 2,
            custom: 0,
            ..MatchConfig::default()
        };
        assert!(!beach_bytes(&config, 2, &shelf).is_empty(), "fits a pair");
        assert!(
            beach_bytes(&config, 5, &shelf).is_empty(),
            "five turned up and it has two castles"
        );
    }

    /// Nonsense on the wire must not stop the round: the beach falls back
    /// to the terms, and the hash check is what says the peers disagree.
    #[test]
    fn a_beach_that_will_not_read_is_not_fatal() {
        assert!(beach_from(&[]).is_none());
        assert!(beach_from(&[0xFF; 40]).is_none());
        let terms = MatchTerms::default();
        let board = board_from(&terms, 2, &[0xFF; 40]);
        assert_eq!(board.width(), board_for(&terms, 2).width());
    }

    /// A versus arena wants a castle each, so a puzzle built for one crab
    /// and one castle is not offered as a two-seat beach.
    #[test]
    fn a_beach_is_offered_only_when_it_has_the_castles() {
        let one = crate::sim::Level::parse(
            "name: One\nposts: 1\ncrab: 0,1 R R common\nmap:\n\
             +-+-+-+\n|. . .|\n+ + + +\n|. . 0|\n+ + + +\n|. . .|\n+-+-+-+\n",
        )
        .expect("a level");
        assert_eq!(one.seats(), 1);
        let two = crate::sim::Level::parse(
            "name: Two\nposts: 1\ncrab: 0,1 R R common\nmap:\n\
             +-+-+-+\n|0 . .|\n+ + + +\n|. . 1|\n+ + + +\n|. . .|\n+-+-+-+\n",
        )
        .expect("a level");
        assert_eq!(two.seats(), 2);
    }

    /// A beach that fits nobody at this table is not silently absent: the
    /// dial skips its stop, and the row beside it says why. Two castles
    /// stop being offered the moment a third player sits down, and that
    /// used to read as a beach the game had lost.
    #[test]
    fn the_map_row_says_why_a_beach_is_not_on_offer() {
        use crate::app::i18n::EN;
        let two = crate::sim::Level::parse(
            "name: Two\nposts: 1\nkind: arena\ncrab: 0,1 R R common\nmap:\n\
             +-+-+-+\n|0 . .|\n+ + + +\n|. . 1|\n+ + + +\n|. . .|\n+-+-+-+\n",
        )
        .expect("a level");
        let shelf = CustomBeaches(vec![Beach::new(two)]);
        let at = |seats| MatchConfig {
            seats,
            ..MatchConfig::default()
        };

        assert_eq!(beaches_note(&at(2), &EN, &shelf), None, "it is on the dial");
        let note = beaches_note(&at(4), &EN, &shelf).expect("four cannot sit at it");
        assert!(note.contains('4'), "{note}");

        // With nothing saved there is nothing to explain: an empty shelf is
        // not a shelf whose beaches are the wrong size.
        assert_eq!(beaches_note(&at(4), &EN, &CustomBeaches::default()), None);
    }

    /// The dial walks the built-ins, then every handmade beach, and steps
    /// off the end rather than sticking. With none saved it never lands on
    /// the custom stop at all, because an empty stop is a dead press.
    #[test]
    fn the_map_dial_skips_a_stop_with_nothing_on_it() {
        let mut config = MatchConfig {
            map: MapChoice::GenOcean,
            ..MatchConfig::default()
        };
        // An empty shelf is the case that matters: the dial must not stop
        // on a beach that is not there.
        let shelf = CustomBeaches::default();
        cycle_map(&mut config, true, &shelf);
        assert_ne!(config.map, MapChoice::Custom, "an empty stop is skipped");
    }

    /// A series steps the map under the dial's guards, keeping the table:
    /// five seated skip the empty shelf and the four-castle beaches rather
    /// than losing two castles on the classic arena. Locally and on the
    /// wire alike, since the wire form goes through the same stepper.
    #[test]
    fn a_series_steps_past_beaches_the_table_does_not_fit() {
        let mut config = MatchConfig {
            map: MapChoice::GenOcean,
            seats: 5,
            ..MatchConfig::default()
        };
        let shelf = CustomBeaches::default();
        next_map(&mut config, &shelf);
        assert_eq!(
            config.map,
            MapChoice::GenLarge,
            "past Custom, Classic, Small, 12x9"
        );
        assert_eq!(config.seats, 5, "nobody left the table");
        next_map(&mut config, &shelf);
        assert_eq!(config.map, MapChoice::GenXl);

        // Four seated walk every built-in beach in order.
        let mut four = MatchConfig {
            map: MapChoice::GenOcean,
            seats: 4,
            ..MatchConfig::default()
        };
        next_map(&mut four, &shelf);
        assert_eq!(four.map, MapChoice::Classic);

        let terms = MatchTerms {
            map: MapChoice::GenOcean.index() as u8,
            seed: 1,
            ..MatchTerms::default()
        };
        let next = next_round_terms(terms, 5, 2);
        assert_eq!(
            MapChoice::from_index(usize::from(next.map)),
            MapChoice::GenLarge
        );
        assert_eq!(next.seed, 2);
        let next = next_round_terms(terms, 2, 3);
        assert_eq!(
            MapChoice::from_index(usize::from(next.map)),
            MapChoice::Classic
        );
    }

    /// The seat count moving under the map: `Custom` with no beach seating
    /// the table steps off the shelf, and the label agrees with the launch
    /// in the meantime, naming the XL arena the match would generate.
    #[test]
    fn a_table_the_shelf_cannot_seat_moves_the_map_along() {
        use crate::app::i18n::EN;
        let two = crate::sim::Level::parse(
            "name: Two\nposts: 1\nkind: arena\ncrab: 0,1 R R common\nmap:\n\
             +-+-+-+\n|0 . .|\n+ + + +\n|. . 1|\n+ + + +\n|. . .|\n+-+-+-+\n",
        )
        .expect("a level");
        let shelf = CustomBeaches(vec![Beach::new(two)]);
        let mut config = MatchConfig {
            map: MapChoice::Custom,
            seats: 2,
            ..MatchConfig::default()
        };
        settle_map(&mut config, &shelf);
        assert_eq!(config.map, MapChoice::Custom, "two fit; nothing moves");
        assert!(map_label(&config, &EN, &shelf).contains("Two"));

        config.seats = 3;
        assert_eq!(
            map_label(&config, &EN, &shelf),
            EN.map_names[MapChoice::GenXl.index()],
            "the label names what would launch"
        );
        settle_map(&mut config, &shelf);
        assert_eq!(config.map, MapChoice::Classic, "the stop after Custom");

        config.map = MapChoice::Custom;
        config.seats = 5;
        settle_map(&mut config, &shelf);
        assert_eq!(config.map, MapChoice::GenXl, "and wide enough for five");
    }

    use crate::app::settings::GameSettings;

    /// Open ocean is the one beach with no edges. The sim has supported
    /// wrapping since the campaign started teaching it (level 26), but
    /// nothing in versus ever turned it on, and every other map choice has
    /// to stay walled, or a beach changes shape under everyone.
    #[test]
    fn only_the_open_ocean_has_no_edges() {
        for map in MapChoice::ALL {
            let terms = MatchTerms {
                map: map.index() as u8,
                seed: 99,
                ..MatchTerms::default()
            };
            let board = board_for(&terms, 4);
            assert_eq!(
                board.wrap(),
                map == MapChoice::GenOcean,
                "{map:?} wraps: {}",
                board.wrap()
            );
        }
        // And it is appended, so an older settings file or a `Start` from
        // another machine still names the beach it meant.
        for (index, map) in MapChoice::ALL.iter().enumerate() {
            assert_eq!(MapChoice::from_index(index), *map);
        }
        assert_eq!(MapChoice::from_index(4), MapChoice::GenXl, "xl stayed put");
    }

    /// Naming a seat, end to end in a headless App: Enter on a name row
    /// takes the keyboard instead of starting the match, what is typed lands
    /// in the name, and Enter hands the keyboard back.
    #[test]
    fn typing_renames_a_seat_without_starting_the_match() {
        use bevy::input::ButtonState;
        use bevy::input::keyboard::{Key, KeyboardInput};

        let mut app = App::new();
        app.add_plugins(bevy::state::app::StatesPlugin);
        app.init_state::<Screen>();
        app.add_message::<KeyboardInput>();
        app.init_resource::<ButtonInput<KeyCode>>();
        app.init_resource::<MatchMenu>();
        app.init_resource::<MatchConfig>();
        app.init_resource::<crate::app::match_setup::CustomBeaches>();
        app.init_resource::<crate::app::tournament::Tournament>();
        app.insert_resource(GameSettings::default());
        app.add_systems(Update, match_setup_input);

        let name_row = Row::ALL
            .iter()
            .position(|row| matches!(row, Row::Name(0)))
            .expect("a name row for seat 1");
        app.world_mut().resource_mut::<MatchMenu>().selected = name_row;

        let tap = |app: &mut App, key: KeyCode| {
            let mut keys = app.world_mut().resource_mut::<ButtonInput<KeyCode>>();
            keys.reset_all();
            keys.press(key);
            app.update();
        };
        let type_char = |app: &mut App, ch: &str| {
            app.world_mut()
                .resource_mut::<ButtonInput<KeyCode>>()
                .reset_all();
            app.world_mut().write_message(KeyboardInput {
                key_code: KeyCode::KeyB,
                logical_key: Key::Character(ch.into()),
                state: ButtonState::Pressed,
                text: Some(ch.into()),
                repeat: false,
                window: Entity::PLACEHOLDER,
            });
            app.update();
        };

        // Tab opens the name box. Enter must not, or the name rows become
        // a room with no door: they are last on the list, so a player who
        // has just named everybody presses Enter to start and gets the
        // name box again, and again.
        tap(&mut app, KeyCode::Tab);
        assert_eq!(app.world().resource::<MatchMenu>().naming, Some(0));
        assert!(
            !app.world().resource::<MatchConfig>().armed,
            "Tab named the seat instead of launching"
        );

        type_char(&mut app, "B");
        type_char(&mut app, "o");
        assert_eq!(app.world().resource::<GameSettings>().names[0], "Bo");
        assert_eq!(app.world().resource::<GameSettings>().seat_name(0), "Bo");

        tap(&mut app, KeyCode::Enter);
        assert_eq!(app.world().resource::<MatchMenu>().naming, None);
        assert!(
            !app.world().resource::<MatchConfig>().armed,
            "the Enter that finished the name did not launch either"
        );

        // And now Enter starts the match from that very row, rather than
        // reopening the box it just closed.
        assert!(
            matches!(Row::ALL[name_row], Row::Name(0)),
            "still on a name row"
        );
        tap(&mut app, KeyCode::Enter);
        assert!(
            app.world().resource::<MatchConfig>().armed,
            "Enter on a name row has to start the match"
        );
    }

    /// A name row per seat in the match, and none for the seats that are
    /// not playing.
    #[test]
    fn name_rows_follow_the_seat_count() {
        let config = MatchConfig {
            seats: 3,
            ..MatchConfig::default()
        };
        let live = live_rows(&config);
        let named: Vec<u8> = Row::ALL
            .iter()
            .enumerate()
            .filter(|&(row, _)| live[row])
            .filter_map(|(_, kind)| {
                if let Row::Name(seat) = kind {
                    Some(*seat)
                } else {
                    None
                }
            })
            .collect();
        assert_eq!(named, vec![0, 1, 2], "one row per seat, seat 4 sits out");
    }

    /// AI seats fill from the top down, one difficulty row each, and the
    /// unused rows stay hidden.
    #[test]
    fn ai_rows_track_the_seats_the_ai_holds() {
        let mut config = MatchConfig {
            seats: 4,
            bots: 2,
            ..MatchConfig::default()
        };
        assert_eq!(ai_seat(&config, 0), Some(3));
        assert_eq!(ai_seat(&config, 1), Some(2));
        assert_eq!(ai_seat(&config, 2), None, "only two AI seats are taken");

        let live = live_rows(&config);
        let hidden: Vec<bool> = Row::ALL
            .iter()
            .zip(live)
            .filter_map(|(row, live)| matches!(row, Row::BotLevel(_)).then_some(live))
            .collect();
        let mut want = vec![false; MAX_BOTS];
        want[0] = true;
        want[1] = true;
        assert_eq!(hidden, want, "one live row per AI seat, the rest folded");
        // An all-human match hides every AI row, and a table of four hides
        // the name rows of the two seats nobody is sitting in.
        config.bots = 0;
        let empty_seats = MAX_PLAYERS - usize::from(config.seats);
        assert_eq!(
            live_rows(&config).iter().filter(|live| **live).count(),
            ROWS - MAX_BOTS - empty_seats
        );
    }

    /// Each AI seat carries its own difficulty: turning one row must not
    /// drag the other seats with it.
    #[test]
    fn difficulties_are_per_seat() {
        let mut config = MatchConfig {
            seats: 4,
            bots: 3,
            ..MatchConfig::default()
        };
        cycle_ai_level(&mut config, 0, true); // seat 4: normal -> fierce
        cycle_ai_level(&mut config, 2, false); // seat 2: normal -> easy
        assert_eq!(config.bot_levels, {
            let mut want = [BotLevel::Normal; MAX_PLAYERS];
            want[1] = BotLevel::Easy; // seat 2, stepped down
            want[3] = BotLevel::Hard; // seat 4, stepped up
            want
        });
        // A slot with no AI behind it is inert.
        config.bots = 1;
        cycle_ai_level(&mut config, 2, true);
        assert_eq!(config.bot_levels[1], BotLevel::Easy);
    }
}