pinch-points 0.8.0

A fast, kid-friendly crab-routing game: route streams of crabs into your sandcastle before time runs out
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
//! What the header and the prompt line say, per screen.
//!
//! Pure functions of game state and the string table: no ECS, no spawning,
//! which makes them testable, and they are every player-facing line in
//! the game, so they are worth testing.

use crate::app::editor::EditorState;
use crate::app::i18n::{Tr, fill};
use crate::app::lobby::LobbyState;
use crate::app::net::Online;
use crate::app::settings::GameSettings;
use crate::app::teams::TeamMode;
use crate::app::{
    Campaign, CampaignKind, Controllers, Phase, Playback, Screen, Seats, Sim, VersusPhase,
};
use crate::sim::{Goal, LURE_TICKS, TICKS_PER_SECOND, TideEvent};
use bevy::prelude::*;

use crate::app::palette::{CLOCK_CALM, CLOCK_RED, CLOCK_RED_BRIGHT};

/// mm:ss for a remaining-tick count, written into a buffer the caller
/// keeps: the clocks repaint every frame and change once a second.
pub(crate) fn clock_into(out: &mut String, ticks: u64) {
    use std::fmt::Write;
    let secs = ticks / u64::from(TICKS_PER_SECOND);
    out.clear();
    let _ = write!(out, "{}:{:02}", secs / 60, secs % 60);
}

/// mm:ss for a remaining-tick count.
#[cfg(test)]
pub(crate) fn clock_text(ticks: u64) -> String {
    let mut out = String::new();
    clock_into(&mut out, ticks);
    out
}

/// How much of a round the screen draws as its closing emergency.
///
/// `band` is what that stretch is worth on a round with a middle to it:
/// 30 s of red, the last 10 s of it blinking. A round shorter than the
/// band has no middle, and the fixed figure then covers the whole of it:
/// the longest round any level file asks for is 900 ticks, exactly
/// [`crate::sim::SURGE_TICKS`], so no shipped level ever left the red, and
/// Dry Feet ran all eight of its seconds under a blinking clock.
///
/// Below the band the last third stands in for it. Versus rounds are two
/// minutes and up and keep the fixed 30 s.
///
/// This is the *drawn* scramble only. [`crate::sim::Board::in_surge`] is
/// the sim's own 30 s rule, which doubles the gull spawn rate and gates
/// tide events, and it stays where it is: moving it would move every
/// replay.
pub(crate) fn urgency_band(round: Option<u32>, band: u32) -> u64 {
    match round {
        Some(round) if round <= band => u64::from(round) / 3,
        _ => u64::from(band),
    }
}

/// The clock colour ramp: calm, red inside the closing band, blinking
/// half-seconds for the last third of that. `blink` is off under reduced
/// motion, where the final stretch simply holds the bright red instead of
/// flashing. `round` is the board's round length, absent on an untimed
/// puzzle counting down the campaign tick limit.
pub(crate) fn clock_color(ticks: u64, round: Option<u32>, elapsed: f32, blink: bool) -> Color {
    const BLINK_TICKS: u64 = 10 * TICKS_PER_SECOND as u64;
    let red = urgency_band(round, crate::sim::SURGE_TICKS);
    // The blink is the last third of the red, and never more than the ten
    // seconds it is worth on a long round: the two have to stay in that
    // order, or a short round starts blinking the instant it turns red.
    if ticks <= BLINK_TICKS.min(red / 3) {
        if !blink || ((elapsed * 2.0) as u32).is_multiple_of(2) {
            CLOCK_RED
        } else {
            CLOCK_RED_BRIGHT
        }
    } else if ticks <= red {
        CLOCK_RED
    } else {
        CLOCK_CALM
    }
}

/// What the three shared HUD slots say on a screen: the header's left
/// side, its right side, and the prompt pill along the bottom.
///
/// A struct and not a `(String, String, String)`: with nothing but
/// position to say which is which, a screen that swapped its status and
/// its prompt would compile and run.
pub(super) struct HudText {
    /// Left of the header bar: where you are.
    pub title: String,
    /// Right of the header bar: how the round stands.
    pub status: String,
    /// The pill along the bottom: which keys do what, here, now.
    pub prompt: String,
}

impl HudText {
    fn new(
        title: impl Into<String>,
        status: impl Into<String>,
        prompt: impl Into<String>,
    ) -> HudText {
        HudText {
            title: title.into(),
            status: status.into(),
            prompt: prompt.into(),
        }
    }
}

pub(super) fn lobby_text(tr: &Tr, lobby: &LobbyState) -> HudText {
    let title = tr.title_lobby.to_string();
    let status = lobby.feedback.clone();
    use crate::app::lobby::Standing;
    let prompt = match lobby.standing() {
        // W armed is the one bit of lobby state a player has to be told
        // about, since it changes what picking a beach does.
        Standing::Choosing { watching: true } => tr.lobby_watch_armed.to_string(),
        // A peer in line is not waiting for a launch either: the round it
        // is queued for is the one already being played without it. And
        // one that came to watch is not in line for a chair, so it is not
        // told it will be sitting in one.
        Standing::Joining(joined) if joined.queued.is_some() => match joined.watching {
            true => tr.lobby_queued_watch_prompt.to_string(),
            false => tr.lobby_queued_prompt.to_string(),
        },
        // "Aboard" is the joiner's word, and a spectator is not: the
        // status line right above this one says "watching", and the two
        // of them describing the same peer differently is the whole of
        // what a player has to go on before the round starts.
        Standing::Joining(joined) if joined.watching => tr.lobby_watching_prompt.to_string(),
        Standing::Joining(_) => tr.lobby_aboard_prompt.to_string(),
        // Picking whom to ask to leave: the prompt says how.
        Standing::Hosting(_) if lobby.kicking => tr.lobby_kick_ask.to_string(),
        Standing::Hosting(_) => tr.lobby_broadcasting.to_string(),
        Standing::Choosing { watching: false } if lobby.hosts.is_empty() => {
            tr.lobby_none_yet.to_string()
        }
        Standing::Choosing { watching: false } => {
            // The beaches themselves are a list of their own now, spawned by
            // the lobby: this line says what to do with it, and how many there
            // are, which the visible rows may not show all of.
            match lobby.hosts.len() {
                1 => tr.lobby_join_list_one.to_string(),
                n => fill(tr.lobby_join_list, &[("n", &n.to_string())]),
            }
        }
    };
    HudText::new(title, status, prompt)
}

pub(super) fn editor_text(tr: &Tr, editor: &EditorState, sim: &Sim) -> HudText {
    let testing = editor.is_testing();
    // The title carries the level's name, which is the file it saves to
    // and the caption the stage list shows, so it has to be visible before
    // F2. What is being built belongs there too: the two kinds save to
    // different lists, and finding that out at the map dial is too late.
    let kind = match editor.kind {
        crate::sim::LevelKind::Puzzle => tr.ed_kind_puzzle,
        crate::sim::LevelKind::Arena => tr.ed_kind_arena,
    };
    let title = if testing {
        tr.title_playtest.to_string()
    } else {
        // The kind sits in front of the name, not after it: the caret that
        // shows the keyboard is spelling a name has to stay on the end of
        // the thing being spelled.
        format!(
            "{} [{kind}] - {}{}",
            tr.title_editor,
            editor.name,
            if editor.is_naming() { "_" } else { "" }
        )
    };
    // A beach is not played with a granted inventory, so the number beside
    // the feedback is the one that decides whether it can be played at all:
    // how many seats it has castles for.
    let counted = match editor.kind {
        crate::sim::LevelKind::Puzzle => fill(tr.ed_posts, &[("n", &editor.posts.to_string())]),
        crate::sim::LevelKind::Arena => {
            fill(tr.ed_seats, &[("n", &sim.0.castle_seats().to_string())])
        }
    };
    let status = fill(&counted, &[("msg", &editor.feedback)]);
    let prompt = if testing {
        tr.ed_playtest_prompt.to_string()
    } else {
        tr.ed_prompt.to_string()
    };
    HudText::new(title, status, prompt)
}

pub(super) fn puzzle_text(
    tr: &Tr,
    lang: crate::app::i18n::Lang,
    campaign: &Campaign,
    coop: bool,
    sim: &Sim,
    phase: &State<Phase>,
    custom_keys: bool,
) -> HudText {
    let level = campaign.current();
    let campaign_title = match campaign.kind {
        CampaignKind::TidePool => tr.title_tide_pool,
        CampaignKind::BeachDay => tr.title_beach_day,
    };
    // The player's own levels take the stage list's own label for them in
    // place of the list's name, so driftwood three is never read as stage
    // three. In place of, and not as well as: the header bar runs from the
    // window's edge to the clock in its middle, and the longest shipped
    // level name already reaches most of the way there.
    let (place, of, custom) = campaign.place();
    let section = match custom {
        true => tr.stage_custom,
        false => campaign_title,
    };
    let title = format!(
        "{section} {place}/{of} - {}",
        campaign.shown_name(campaign.index, lang)
    );
    let used = sim.0.signpost_count(0);
    let saved = fill(
        tr.saved_count,
        &[
            ("a", &sim.0.crabs_banked().to_string()),
            (
                "b",
                &sim.0.crabs_spawned().max(level.crab_count()).to_string(),
            ),
        ],
    );
    // What the level asks for. The default goal has nothing to state beyond
    // the tally of crabs already home; the rest name their own target.
    let goal = match level.goal {
        Goal::AllCrabs => saved,
        Goal::Bank(n) => fill(
            tr.goal_bank,
            &[
                ("a", &sim.0.crabs_banked().to_string()),
                ("b", &n.to_string()),
                ("t", ""),
            ],
        ),
        Goal::Survive => fill(tr.goal_survive, &[("t", "")]),
        Goal::Golden => fill(tr.goal_golden, &[("t", "")]),
    };
    // The inventory goes in front of it, on every goal. Printed only under
    // `AllCrabs`, nine campaign levels and all eight Beach Day stages named
    // a target without saying how many signposts paid for it, which reads
    // as "as many as I like". A level that hands out none says so in the
    // prompt instead.
    let status = match level.posts {
        0 => goal,
        posts => format!(
            "{} | {goal}",
            fill(
                tr.signposts_count,
                &[("a", &used.to_string()), ("b", &posts.to_string())]
            )
        ),
    };
    let prompt = match phase.get() {
        Phase::Setup if level.posts == 0 => tr.prompt_setup_no_posts.to_string(),
        Phase::Setup if custom_keys => tr.prompt_setup_custom.to_string(),
        // Two sets of hands, so both sets of keys: the solo line names one.
        Phase::Setup if coop => tr.prompt_setup_coop.to_string(),
        // Full is only full under a fixed inventory. A Beach Day stage
        // evicts: its fourth arrow replaces the oldest, as its own hint
        // says, so "remove one first" would be wrong there. After the two
        // above, because this line names the stock key, and neither a
        // rebound key nor the second pair of hands is Space.
        Phase::Setup
            if used >= level.posts as usize
                && sim.0.signpost_rule().1 == crate::sim::CapPolicy::Reject =>
        {
            tr.prompt_setup_full.to_string()
        }
        Phase::Setup => tr.prompt_setup.to_string(),
        Phase::Running => tr.prompt_running.to_string(),
        // On the last level the card says the run is over and Enter goes
        // home; a prompt line still offering "next level" under it is the
        // game arguing with itself.
        Phase::Won if campaign.is_last() => tr.last_level.to_string(),
        Phase::Won if level.goal.saves_every_crab() => tr.prompt_won.to_string(),
        Phase::Won => tr.prompt_won_goal.to_string(),
        Phase::Lost => tr.prompt_lost.to_string(),
    };
    HudText::new(title, status, prompt)
}

/// The busiest screen there is, and the one that reads off the most: it
/// takes the whole [`Readout`] rather than ten of its fields, where the
/// order of two `&Res`es of the same shape was checked by eyesight.
pub(super) fn versus_text(r: &Readout) -> HudText {
    let Readout {
        tr,
        sim,
        seats,
        settings,
        names,
        playback,
        online,
        controllers,
        vphase,
        tournament,
        speed,
        ..
    } = *r;
    let scores = sim.0.scores();
    let team_mode = crate::app::teams::in_play(settings, online, seats.0);
    let mut mode = if playback.0.is_some() {
        tr.title_replay.to_string()
    } else if let Some(session) = &online.0 {
        match session.session.seat() {
            Some(seat) => fill(tr.title_online, &[("p", &names.label(tr, seat))]),
            None => tr.title_watching.to_string(),
        }
    } else if controllers.ai_count() > 0 {
        let count = controllers.ai_count();
        fill(
            tr.title_vs_ai,
            &[("n", &count.to_string()), ("p", &names.label(tr, 0))],
        )
    } else {
        tr.title_turf_war.to_string()
    };
    if team_mode != TeamMode::Solo {
        // Every team's total, in team order, so a 2v2v2 reads as three
        // numbers rather than two.
        let totals = crate::app::teams::team_scores(scores, seats.0, team_mode)
            .iter()
            .map(u32::to_string)
            .collect::<Vec<_>>()
            .join("  vs  ");
        mode = fill(tr.team_banner, &[("mode", &mode), ("s", &totals)]);
    }
    // The clock itself lives in the big top-centre element; the
    // status slot carries only banners.
    let mut status = if playback.0.is_some() && speed > 1 {
        fill(tr.replay_speed, &[("n", &speed.to_string())])
    } else if sim.0.in_surge() && !sim.0.round_over() {
        tr.the_gulls.to_string()
    } else {
        String::new()
    };
    // Three seconds of the event's name, then the status slot is free.
    if let Some((event, at)) = sim.0.last_event()
        && sim.0.ticks().saturating_sub(at) < u64::from(3 * TICKS_PER_SECOND)
    {
        status = fill(tr.tide_event, &[("e", event_name(tr, event))]);
    }
    if let Some((owner, remaining)) = sim.0.lure() {
        let seat = names.label(tr, owner);
        // The first two seconds name the trigger; then a live countdown.
        status = if remaining > LURE_TICKS - 2 * TICKS_PER_SECOND {
            fill(tr.lure_started, &[("p", &seat)])
        } else {
            fill(
                tr.lure_banner,
                &[
                    ("s", &remaining.div_ceil(TICKS_PER_SECOND).to_string()),
                    ("p", &seat),
                ],
            )
        };
    }
    if let Some(session) = &online.0 {
        // Whose fault the still picture is, in the order the answer is
        // worth having: a desync is the round being wrong, an empty socket
        // is nobody there yet, and a stall is somebody in particular.
        if let Some(frame) = session.desync_at() {
            status = fill(tr.desync, &[("f", &frame.to_string())]);
        } else if !session.transport.connected() {
            status = tr.waiting_peer.to_string();
        } else if let Some(seat) = session.waiting_on() {
            // Decided once a frame by the session rather than read off the
            // stall clock here: at three frames of input delay a moment's
            // wait is the ordinary rhythm, and a line that came and went
            // with each of them is a strobe.
            status = fill(tr.waiting_for, &[("p", &names.label(tr, seat))]);
        }
    }
    // The crowd, in whatever room the banners leave: a table that never
    // hears anyone is watching learns it has an audience from the moment
    // that audience calls a tide event down on it. Last, so a gull, a tide
    // event or a desync always has the slot instead.
    if status.is_empty() && r.crowd.watching > 0 {
        status = fill(tr.spectator_count, &[("n", &r.crowd.watching.to_string())]);
    }
    // The count before a round shows the round's own keys: three seconds
    // of a still beach is when a table reads them.
    let prompt = match vphase.get() {
        // A recording is watched, not played, but it *is* driven: the
        // transport bar at the foot of the board takes a pause and a
        // speed, and keys nobody is told about are keys nobody presses.
        VersusPhase::Countdown | VersusPhase::Running if playback.0.is_some() => {
            tr.prompt_replay_transport.to_string()
        }
        // Someone else's live match has no seat here, so no control
        // legend: a spectator holds nothing and places nothing. What they
        // do have is free hands, which is why they are the ones who talk.
        VersusPhase::Countdown | VersusPhase::Running
            if online.0.as_ref().is_some_and(|s| s.session.watching()) =>
        {
            match r.spectator_typing {
                Some(line) => format!("> {line}_"),
                // What the key does right now, in the crowd's own terms: a
                // vote open to join, a wait to sit out, or the offer. A
                // spectator pressing into silence could not tell which.
                None => {
                    let call = match (r.crowd.open, r.crowd.wait) {
                        (0, 0) => tr.spectator_call_hint.to_string(),
                        (0, wait) => fill(tr.spectator_wait, &[("n", &wait.to_string())]),
                        (open, _) => fill(tr.spectator_vote_open, &[("n", &open.to_string())]),
                    };
                    // While the winner can still be called, that is the
                    // offer instead: the round's first half minute, and the
                    // one thing a spectator cannot do later. The tide's
                    // key works all the same, and is named again after.
                    let session = online.0.as_ref();
                    let open = session.map_or(0, |s| s.stands.picks.open);
                    let call = match (open, session.and_then(|s| s.stands.my_pick)) {
                        (0, _) => call,
                        (n, None) => fill(tr.spectator_pick_hint, &[("n", &n.to_string())]),
                        (n, Some(seat)) => fill(
                            tr.spectator_picked,
                            &[("p", &names.label(tr, seat)), ("n", &n.to_string())],
                        ),
                    };
                    format!("{call} | {} | {}", tr.lobby_chat_hint, tr.prompt_esc_menu)
                }
            }
        }
        // The tide is in: the board is frozen and there is nothing to call
        // onto it, but the table is still talking, and this is where it
        // talks most.
        VersusPhase::Over if online.0.as_ref().is_some_and(|s| s.session.watching()) => {
            match r.spectator_typing {
                Some(line) => format!("> {line}_"),
                None => format!(
                    "{} | {}",
                    tr.lobby_chat_hint,
                    crate::app::play_input::enter_door(tr, online, tournament.is_running())
                ),
            }
        }
        // Rebound keys first: the short legend against the AI or online
        // names the stock keys too, and input reads the player's own. The
        // bindings and not `stock_legend`: versus plays the arrows whatever
        // the one-hand preset says (`versus_input`), so the stock legend
        // is the true one under the preset.
        VersusPhase::Countdown | VersusPhase::Running if settings.custom_binds() => {
            tr.prompt_versus_custom.to_string()
        }
        VersusPhase::Countdown | VersusPhase::Running
            if online.0.is_some() || controllers.machine_count() > 0 =>
        {
            tr.prompt_versus_short.to_string()
        }
        VersusPhase::Countdown | VersusPhase::Running => tr.prompt_versus_local.to_string(),
        // Whatever Enter actually does here, named by the one function the
        // key itself reads: a finished lobby match goes back to the lobby
        // together, a series plays on, and the prompt must not promise a
        // door the key does not open.
        VersusPhase::Over => {
            crate::app::play_input::enter_door(tr, online, tournament.is_running()).to_string()
        }
    };
    HudText::new(mode, status, prompt)
}

pub(crate) fn event_name(tr: &Tr, event: TideEvent) -> &'static str {
    tr.events[event.index()]
}

/// Everything the header and prompt line can draw on. Bundled so the
/// per-screen text is a pure function rather than a match inside a system
/// with fourteen resources - and so a test can ask every screen what it says.
pub(super) struct Readout<'a> {
    pub tr: &'static Tr,
    pub lang: crate::app::i18n::Lang,
    pub sim: &'a Sim,
    pub campaign: &'a Campaign,
    /// Two players at the Tide Pool (`app::Coop`), which changes what the
    /// setup prompt and the stage list say.
    pub coop: bool,
    pub phase: &'a State<Phase>,
    pub vphase: &'a State<VersusPhase>,
    pub editor: &'a EditorState,
    pub online: &'a Online,
    pub playback: &'a Playback,
    pub lobby: &'a LobbyState,
    /// Whether a series is mid-flight, which changes what the results
    /// card's Enter does and so what the prompt may promise.
    pub tournament: &'a crate::app::tournament::Tournament,
    pub seats: &'a Seats,
    pub settings: &'a GameSettings,
    /// What this keyboard's caps say: a resource of its own, since it is
    /// learned state rather than a preference.
    pub keycaps: &'a crate::app::keycaps::KeyCaps,
    pub names: &'a crate::app::SeatNames,
    pub controllers: &'a Controllers,
    pub library: &'a crate::app::replays::Library,
    /// What the menu has to say about a round code copied or pasted.
    pub notice: &'a crate::app::RoundNotice,
    /// Which row the match setup is on: Enter means something else on the
    /// name rows, and the prompt line has to say so.
    pub match_menu: &'a crate::app::match_setup::MatchMenu,
    /// Whether the pause card is up and holding the keyboard.
    pub paused: bool,
    /// The line a spectator is saying to the table, while one is open.
    pub spectator_typing: Option<&'a str>,
    /// The host's word on the crowd.
    pub crowd: crate::app::spectators::Crowd,
    pub speed: u8,
}

/// What the header, the status slot and the prompt say on `screen`.
///
/// The music toggle is added here rather than written into each play
/// screen's prompt: there are eight of those in every language, and a key
/// that works everywhere should not be a line eight strings have to
/// remember to carry.
pub(super) fn screen_text(screen: Screen, r: &Readout) -> HudText {
    let mut said = screen_text_for(screen, r);
    if matches!(screen, Screen::Versus | Screen::Puzzle) {
        // The pause card has the keyboard while it is up, so the line
        // names its keys rather than the beach's: Escape is the way on
        // there, not the way to a pause the player is already in. The
        // card is an overlay and not a screen of its own, which is why
        // this is a coat of paint over the screen's own answer.
        if r.paused {
            said.prompt = r.tr.prompt_paused.to_string();
        }
        said.prompt = format!("{} | {}", said.prompt, r.tr.prompt_mute);
    }
    // Spelled in this keyboard's caps here, once, rather than in each of
    // the legends that name the move keys.
    said.prompt = r.keycaps.legend(&said.prompt);
    said
}

pub(super) fn screen_text_for(screen: Screen, r: &Readout) -> HudText {
    match screen {
        // The menu's status slot carries word of a code that would not
        // load: the only news the menu ever has.
        Screen::Menu => HudText::new(
            String::new(),
            r.notice.0.clone(),
            r.tr.menu_prompt.to_string(),
        ),
        Screen::Settings => HudText::new(
            r.tr.title_settings.to_string(),
            String::new(),
            r.tr.prompt_settings.to_string(),
        ),
        Screen::Controls => HudText::new(
            r.tr.title_controls.to_string(),
            String::new(),
            r.tr.prompt_controls.to_string(),
        ),
        Screen::MatchSetup => HudText::new(
            r.tr.title_match_setup.to_string(),
            String::new(),
            if matches!(
                crate::app::match_setup::Row::ALL[r.match_menu.selected],
                crate::app::match_setup::Row::Name(_)
            ) {
                r.tr.prompt_match_name.to_string()
            } else {
                r.tr.prompt_match_setup.to_string()
            },
        ),
        Screen::Achievements => HudText::new(
            r.tr.title_achievements.to_string(),
            String::new(),
            r.tr.prompt_achievements.to_string(),
        ),
        Screen::Replays => HudText::new(
            r.tr.title_replays.to_string(),
            r.library.feedback.clone(),
            r.tr.prompt_replays.to_string(),
        ),
        Screen::StageSelect => HudText::new(
            format!(
                "{} - {}",
                match r.campaign.kind {
                    CampaignKind::TidePool => r.tr.title_tide_pool,
                    CampaignKind::BeachDay => r.tr.title_beach_day,
                },
                r.tr.title_stages
            ),
            match r.coop {
                true => r.tr.stage_coop_on.to_string(),
                false => String::new(),
            },
            // Co-op is the Tide Pool's alone (see `app::Coop`), so only its
            // list offers the key.
            match r.campaign.kind {
                CampaignKind::TidePool => r.tr.prompt_stages_tide.to_string(),
                CampaignKind::BeachDay => r.tr.prompt_stages.to_string(),
            },
        ),
        Screen::Interlude => HudText::new(
            r.tr.title_turf_war.to_string(),
            String::new(),
            String::new(),
        ),
        Screen::Lobby => lobby_text(r.tr, r.lobby),
        Screen::Editor => editor_text(r.tr, r.editor, r.sim),
        Screen::Puzzle => puzzle_text(
            r.tr,
            r.lang,
            r.campaign,
            r.coop,
            r.sim,
            r.phase,
            // Co-op sets the one-hand preset aside (the partner has IJKL),
            // so there only a rebinding makes the keys the player's own.
            match r.coop {
                true => r.settings.custom_binds(),
                false => !r.settings.stock_legend(),
            },
        ),
        // Both lines are already in the language under the cursor: moving
        // it sets the language, so the header and the prompt preview
        // whatever is highlighted. The status slot stays empty, its note
        // sitting under the card beside the list instead.
        Screen::Language => HudText::new(
            r.tr.title_pick_language.to_string(),
            String::new(),
            r.tr.prompt_pick_language.to_string(),
        ),
        Screen::NewVersion => HudText::new(
            r.tr.title_new_version.to_string(),
            String::new(),
            r.tr.prompt_new_version.to_string(),
        ),
        Screen::Versus => versus_text(r),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::app::i18n::{EN, Lang};
    use crate::sim::{Board, Level, campaign_levels};

    /// Every screen has to say what it is and what the keys do: one added
    /// without a HUD arm shows the last screen's header.
    #[test]
    fn every_screen_names_itself_and_its_keys() {
        use crate::app::{Campaign, CampaignKind, Controllers, Playback, Seats};
        use crate::sim::{Board, campaign_levels};

        let levels = campaign_levels();
        let builtins = levels.len();
        let campaign = Campaign {
            kind: CampaignKind::TidePool,
            levels,
            index: 0,
            builtins,
        };
        let settings = GameSettings::default();
        let keycaps = crate::app::keycaps::KeyCaps::default();
        let readout = Readout {
            tr: &EN,
            lang: Lang::En,
            sim: &Sim(Board::new(9, 7, 1)),
            campaign: &campaign,
            coop: false,
            phase: &State::new(Phase::Setup),
            vphase: &State::new(VersusPhase::Running),
            editor: &EditorState::default(),
            online: &Online::default(),
            playback: &Playback::default(),
            lobby: &LobbyState::default(),
            tournament: &crate::app::tournament::Tournament::default(),
            seats: &Seats(2),
            settings: &settings,
            keycaps: &keycaps,
            names: &crate::app::SeatNames::default(),
            controllers: &Controllers::default(),
            library: &crate::app::replays::Library::default(),
            notice: &crate::app::RoundNotice::default(),
            match_menu: &crate::app::match_setup::MatchMenu::default(),
            paused: false,
            spectator_typing: None,
            crowd: Default::default(),
            speed: 1,
        };
        for screen in Screen::ALL {
            let said = screen_text(screen, &readout);
            let (title, prompt) = (&said.title, &said.prompt);
            // The menu is the one screen with no header: it is a postcard,
            // and its own art says where you are.
            if screen != Screen::Menu {
                assert!(!title.is_empty(), "{screen:?} has no header");
            }
            // The interlude is a between-rounds breather with nothing to
            // press; everything else tells you a key.
            if screen != Screen::Interlude {
                assert!(!prompt.is_empty(), "{screen:?} offers no keys");
            }
        }
    }

    /// No prompt names a key twice. `screen_text` appends the mute legend
    /// to every board prompt itself, so a string that carries one anyway
    /// reads "M: mute | M: mute", in two wordings where a translation
    /// picked different words.
    ///
    /// Checked with a recording playing, because that arm is the one the
    /// screen census above cannot reach: it builds its readout with
    /// `Playback::default()`, so the transport prompt never ran there.
    #[test]
    fn no_prompt_names_the_mute_key_twice() {
        use crate::app::{Campaign, CampaignKind, Controllers, Playback, Seats};
        use crate::sim::{Replay, campaign_levels};

        let levels = campaign_levels();
        let builtins = levels.len();
        let watching = Playback(Some((
            Replay::new(levels.first().expect("a campaign level").clone()),
            0,
        )));
        for lang in crate::app::i18n::ALL_LANGS {
            let settings = GameSettings {
                language: lang,
                ..GameSettings::default()
            };
            let tr = settings.tr();
            let readout = Readout {
                tr,
                lang,
                sim: &Sim(Board::new(9, 7, 1)),
                campaign: &Campaign {
                    kind: CampaignKind::TidePool,
                    levels: campaign_levels(),
                    index: 0,
                    builtins,
                },
                coop: false,
                phase: &State::new(Phase::Running),
                vphase: &State::new(VersusPhase::Running),
                editor: &EditorState::default(),
                online: &Online::default(),
                playback: &watching,
                lobby: &LobbyState::default(),
                tournament: &crate::app::tournament::Tournament::default(),
                seats: &Seats::default(),
                settings: &settings,
                keycaps: &crate::app::keycaps::KeyCaps::default(),
                names: &crate::app::SeatNames::default(),
                controllers: &Controllers::default(),
                library: &crate::app::replays::Library::default(),
                notice: &crate::app::RoundNotice::default(),
                match_menu: &crate::app::match_setup::MatchMenu::default(),
                paused: false,
                spectator_typing: None,
                crowd: Default::default(),
                speed: 1,
            };
            let prompt = screen_text(Screen::Versus, &readout).prompt;
            let mute = tr.prompt_mute;
            assert_eq!(
                prompt.matches(mute).count(),
                1,
                "{lang:?} names the mute key more than once: {prompt}"
            );
        }
    }

    /// The editor header names the mode it is in and carries the solver's
    /// last word; playtesting swaps both the title and the key legend.
    #[test]
    fn the_editor_header_follows_the_playtest_toggle() {
        let mut editor = EditorState::default();
        editor.posts = 3;
        editor.name = "Gull Alley".into();
        editor.feedback = "solvable: 2".into();
        // Two castles on the sand, so the beach reading has something to
        // count when the kind is flipped.
        let mut board = Board::new(9, 7, 1);
        board.set_tile(0, 0, crate::sim::TileKind::Castle(0));
        board.set_tile(8, 6, crate::sim::TileKind::Castle(1));
        let sim = Sim(board);
        let HudText {
            title,
            status,
            prompt,
        } = editor_text(&EN, &editor, &sim);
        assert!(title.starts_with(EN.title_editor), "{title}");
        assert!(title.contains("Gull Alley"), "the name is on the header");
        // And what is being built, which decides which list it saves to.
        assert!(title.contains(EN.ed_kind_puzzle), "{title}");
        assert!(status.contains('3') && status.contains("solvable: 2"));
        assert_eq!(prompt, EN.ed_prompt);

        // As a beach the status counts seats instead of an inventory the
        // match will never read.
        editor.kind = crate::sim::LevelKind::Arena;
        let beach = editor_text(&EN, &editor, &sim);
        assert!(beach.title.contains(EN.ed_kind_arena), "{}", beach.title);
        assert_eq!(beach.status, "seats: 2 | solvable: 2", "{}", beach.status);
        editor.kind = crate::sim::LevelKind::Puzzle;

        // Typing shows a caret, so it is obvious the keyboard is spelling a
        // name rather than picking brushes.
        editor.mode = crate::app::editor::Mode::Naming;
        let typing = editor_text(&EN, &editor, &sim).title;
        assert!(typing.ends_with('_'), "{typing}");
        editor.mode = crate::app::editor::Mode::Painting;

        editor.mode = crate::app::editor::Mode::Testing(Box::new(Board::new(4, 4, 0)));
        let HudText { title, prompt, .. } = editor_text(&EN, &editor, &sim);
        assert_eq!(title, EN.title_playtest);
        assert_eq!(prompt, EN.ed_playtest_prompt);
    }

    /// The lobby prompt is a small state machine: aboard, broadcasting,
    /// nothing found yet, or how to work the list of beaches. The beaches
    /// themselves are rows of their own; see `HostEntry::label`.
    #[test]
    fn the_lobby_prompt_tracks_the_connection_state() {
        let mut lobby = LobbyState::default();
        assert_eq!(lobby_text(&EN, &lobby).prompt, EN.lobby_none_yet);

        for at in 1..=3u8 {
            lobby.hosts.push(crate::app::lobby::HostEntry {
                addr: format!("10.0.0.{at}:47777").parse().expect("addr"),
                id: u64::from(at),
                name: String::new(),
                host: String::new(),
                taken: 1,
                seats: 6,
                running: false,
                bots: false,
                full: false,
                age: 0.0,
            });
        }
        // The count is the part that matters: a hall with more games than
        // rows should not look like it has only as many as fit.
        let prompt = lobby_text(&EN, &lobby).prompt;
        assert!(prompt.contains('3'), "how many are out there: {prompt}");

        lobby.feedback = "hosting on port 47777".into();
        assert_eq!(lobby_text(&EN, &lobby).status, "hosting on port 47777");
    }

    /// Three ways to be at somebody else's beach, and three lines.
    ///
    /// Aboard is the joiner's word. A spectator is not aboard, and a peer
    /// in line is not waiting for a launch: the round it is queued for
    /// started without it. The prompt matched on `Joining` alone and told
    /// all three they were aboard and the match would start when the host
    /// launched, while the status line an inch above said "watching" or
    /// "Round in progress". Found by putting each of them on a real beach.
    #[test]
    fn each_way_of_being_at_a_beach_gets_its_own_prompt() {
        use crate::app::lobby::{Joined, Standing};
        use crate::transport::UdpTransport;

        let joined = |watching, queued| {
            let mut lobby = LobbyState::default();
            let mut aboard =
                Joined::returned(UdpTransport::host(0).expect("socket"), watching, 0, None);
            aboard.queued = queued;
            lobby.standing = Standing::Joining(aboard);
            lobby_text(&EN, &lobby).prompt
        };
        assert_eq!(joined(false, None), EN.lobby_aboard_prompt);
        assert_eq!(joined(true, None), EN.lobby_watching_prompt);
        // And a peer in line is waiting for a round that has already
        // started, which is not what either of the other two say. Two of
        // those as well: somebody who armed W and dialled in mid-round is
        // queued like anybody else, and is not in line for a chair.
        assert_eq!(joined(false, Some(0)), EN.lobby_queued_prompt);
        assert_eq!(joined(true, Some(2)), EN.lobby_queued_watch_prompt);
        let all = [
            EN.lobby_aboard_prompt,
            EN.lobby_watching_prompt,
            EN.lobby_queued_prompt,
            EN.lobby_queued_watch_prompt,
        ];
        for (at, line) in all.iter().enumerate() {
            assert!(
                !all[at + 1..].contains(line),
                "four standings want four lines: {line}"
            );
        }
    }

    /// What the key does right now, in the crowd's own terms. A spectator
    /// pressing E into silence could not tell whether a vote was open, how
    /// long was left to join it, or why nothing happened while the crowd
    /// was waiting; all three read the same.
    #[test]
    fn a_spectators_prompt_says_what_the_tide_key_will_do() {
        use crate::app::spectators::Crowd;
        use crate::app::{Campaign, CampaignKind, Controllers, Playback, Seats};

        let levels = campaign_levels();
        let builtins = levels.len();
        let campaign = Campaign {
            kind: CampaignKind::TidePool,
            levels,
            index: 0,
            builtins,
        };
        let settings = GameSettings::default();
        // A watching session: no seat, so the spectator's arm is the one
        // the prompt takes.
        let watching = Online(Some(crate::app::net::OnlineSession::new(
            crate::transport::UdpTransport::host(0).expect("socket"),
            crate::sim::Lockstep::observer(vec![0, 1], crate::sim::DEFAULT_DELAY),
            2,
            crate::transport::MatchTerms::default(),
        )));
        let said = |crowd: Crowd| {
            versus_text(&Readout {
                tr: &EN,
                lang: Lang::En,
                sim: &Sim(Board::new(9, 7, 1)),
                campaign: &campaign,
                coop: false,
                phase: &State::new(Phase::Setup),
                vphase: &State::new(VersusPhase::Running),
                editor: &EditorState::default(),
                online: &watching,
                playback: &Playback::default(),
                lobby: &LobbyState::default(),
                tournament: &crate::app::tournament::Tournament::default(),
                seats: &Seats(2),
                settings: &settings,
                keycaps: &crate::app::keycaps::KeyCaps::default(),
                names: &crate::app::SeatNames::default(),
                controllers: &Controllers::default(),
                library: &crate::app::replays::Library::default(),
                notice: &crate::app::RoundNotice::default(),
                match_menu: &crate::app::match_setup::MatchMenu::default(),
                paused: false,
                spectator_typing: None,
                crowd,
                speed: 1,
            })
            .prompt
        };

        let idle = said(Crowd::default());
        assert!(
            idle.starts_with(EN.spectator_call_hint),
            "the offer: {idle}"
        );

        let open = said(Crowd {
            open: 2,
            ..Default::default()
        });
        assert!(
            open.starts_with(&fill(EN.spectator_vote_open, &[("n", "2")])),
            "a vote to join: {open}"
        );

        let wait = said(Crowd {
            wait: 9,
            ..Default::default()
        });
        assert!(
            wait.starts_with(&fill(EN.spectator_wait, &[("n", "9")])),
            "a wait to sit out: {wait}"
        );

        // An open vote wins over a wait, since one is running right now.
        let both = said(Crowd {
            open: 2,
            wait: 9,
            watching: 3,
        });
        assert!(
            both.starts_with(&fill(EN.spectator_vote_open, &[("n", "2")])),
            "the open one: {both}"
        );

        for state in [idle, open, wait, both] {
            assert!(state.contains(EN.lobby_chat_hint), "and T is always there");
        }
    }

    /// A spectator is told which key gets it out, and it is not the key
    /// the line used to name.
    ///
    /// Two of them, both found by watching a real round end. Mid-round the
    /// line said "Enter: menu", but Enter does nothing while watching: it
    /// is Escape that opens the card, since a spectator cannot pause a
    /// table it is not playing at. And on the results card it still said
    /// "Enter: menu" while `versus_over_input` walked that spectator back
    /// to the lobby with the rest of the table, which is the one thing
    /// `after_round` exists to keep every reader agreeing on.
    #[test]
    fn a_spectator_is_told_the_key_that_actually_lets_it_out() {
        use crate::app::{Campaign, CampaignKind, Controllers, Playback, Seats};

        let levels = campaign_levels();
        let builtins = levels.len();
        let campaign = Campaign {
            kind: CampaignKind::TidePool,
            levels,
            index: 0,
            builtins,
        };
        let settings = GameSettings::default();
        let mut session = crate::app::net::OnlineSession::new(
            crate::transport::UdpTransport::host(0).expect("socket"),
            crate::sim::Lockstep::observer(vec![0, 1], crate::sim::DEFAULT_DELAY),
            2,
            crate::transport::MatchTerms::default(),
        );
        // Came in through a lobby, which is where Enter sends it back to.
        session.home.from_lobby = true;
        let watching = Online(Some(session));
        let said = |phase| {
            versus_text(&Readout {
                tr: &EN,
                lang: Lang::En,
                sim: &Sim(Board::new(9, 7, 1)),
                campaign: &campaign,
                coop: false,
                phase: &State::new(Phase::Setup),
                vphase: &State::new(phase),
                editor: &EditorState::default(),
                online: &watching,
                playback: &Playback::default(),
                lobby: &LobbyState::default(),
                tournament: &crate::app::tournament::Tournament::default(),
                seats: &Seats(2),
                settings: &settings,
                keycaps: &crate::app::keycaps::KeyCaps::default(),
                names: &crate::app::SeatNames::default(),
                controllers: &Controllers::default(),
                library: &crate::app::replays::Library::default(),
                notice: &crate::app::RoundNotice::default(),
                match_menu: &crate::app::match_setup::MatchMenu::default(),
                paused: false,
                spectator_typing: None,
                crowd: Default::default(),
                speed: 1,
            })
            .prompt
        };

        let running = said(VersusPhase::Running);
        assert!(
            running.contains(EN.prompt_esc_menu),
            "Escape is the way out of a round you are watching: {running}"
        );
        assert!(
            !running.contains(EN.prompt_enter_menu),
            "and Enter is not, so it must not be offered: {running}"
        );

        let over = said(VersusPhase::Over);
        assert!(
            over.contains(EN.prompt_enter_lobby),
            "and the card names the door the key opens: {over}"
        );
        assert_eq!(
            crate::app::play_input::after_round(&watching, false),
            crate::app::play_input::AfterRound::Lobby,
            "which is the lobby, as the key itself reads it"
        );
    }

    /// The table is told there is a crowd, in whatever room the banners
    /// leave. Without it a called tide event is the first anyone at the
    /// table hears that anyone is watching, and it arrives together with
    /// its own consequences.
    #[test]
    fn the_table_is_told_it_has_an_audience_when_nothing_louder_is_saying_anything() {
        use crate::app::{Campaign, CampaignKind, Controllers, Playback, Seats};

        let levels = campaign_levels();
        let builtins = levels.len();
        let campaign = Campaign {
            kind: CampaignKind::TidePool,
            levels,
            index: 0,
            builtins,
        };
        let settings = GameSettings::default();
        let status = |watching: u8, surging: bool| {
            let mut board = Board::new(9, 7, 1);
            if surging {
                board.set_round_length(Some(crate::sim::SURGE_TICKS));
            }
            versus_text(&Readout {
                tr: &EN,
                lang: Lang::En,
                sim: &Sim(board),
                campaign: &campaign,
                coop: false,
                phase: &State::new(Phase::Setup),
                vphase: &State::new(VersusPhase::Running),
                editor: &EditorState::default(),
                online: &Online::default(),
                playback: &Playback::default(),
                lobby: &LobbyState::default(),
                tournament: &crate::app::tournament::Tournament::default(),
                seats: &Seats(2),
                settings: &settings,
                keycaps: &crate::app::keycaps::KeyCaps::default(),
                names: &crate::app::SeatNames::default(),
                controllers: &Controllers::default(),
                library: &crate::app::replays::Library::default(),
                notice: &crate::app::RoundNotice::default(),
                match_menu: &crate::app::match_setup::MatchMenu::default(),
                paused: false,
                spectator_typing: None,
                crowd: crate::app::spectators::Crowd {
                    watching,
                    ..Default::default()
                },
                speed: 1,
            })
            .status
        };

        assert_eq!(status(0, false), "", "nobody watching, nothing said");
        assert_eq!(
            status(3, false),
            fill(EN.spectator_count, &[("n", "3")]),
            "three at the back, and room to say so"
        );
        assert_eq!(
            status(3, true),
            EN.the_gulls,
            "and the flock coming in always has the slot instead"
        );
    }

    /// While the pause card holds the keyboard, the prompt names the
    /// card's keys. It used to go on listing the beach's, offering "Esc
    /// pause" to a player already paused and saying nothing about the
    /// rows in front of them.
    #[test]
    fn the_prompt_names_the_pause_cards_keys_while_it_is_up() {
        use crate::app::{Campaign, CampaignKind, Controllers, Playback, Seats};

        let levels = campaign_levels();
        let builtins = levels.len();
        let campaign = Campaign {
            kind: CampaignKind::TidePool,
            levels,
            index: 0,
            builtins,
        };
        let settings = GameSettings::default();
        let said = |screen, paused| {
            screen_text(
                screen,
                &Readout {
                    tr: &EN,
                    lang: Lang::En,
                    sim: &Sim(Board::new(9, 7, 1)),
                    campaign: &campaign,
                    coop: false,
                    phase: &State::new(Phase::Setup),
                    vphase: &State::new(VersusPhase::Running),
                    editor: &EditorState::default(),
                    online: &Online::default(),
                    playback: &Playback::default(),
                    lobby: &LobbyState::default(),
                    tournament: &crate::app::tournament::Tournament::default(),
                    seats: &Seats(2),
                    settings: &settings,
                    keycaps: &crate::app::keycaps::KeyCaps::default(),
                    names: &crate::app::SeatNames::default(),
                    controllers: &Controllers::default(),
                    library: &crate::app::replays::Library::default(),
                    notice: &crate::app::RoundNotice::default(),
                    match_menu: &crate::app::match_setup::MatchMenu::default(),
                    paused,
                    spectator_typing: None,
                    crowd: Default::default(),
                    speed: 1,
                },
            )
            .prompt
        };

        for screen in [Screen::Puzzle, Screen::Versus] {
            let playing = said(screen, false);
            let paused = said(screen, true);
            assert_ne!(playing, paused, "{screen:?}");
            assert!(paused.starts_with(EN.prompt_paused), "{screen:?}: {paused}");
            // The mute key is global and still works, so it stays on the end.
            assert!(paused.ends_with(EN.prompt_mute), "{screen:?}: {paused}");
        }
    }

    /// P1 against a bot has one cursor, like P1 against the AI: the
    /// prompt names P1's keys alone, not a P2 whose keys drive nothing.
    #[test]
    fn a_match_against_a_bot_prompts_for_one_player() {
        use crate::app::{Campaign, CampaignKind, Controllers, Playback, SeatController, Seats};

        let levels = campaign_levels();
        let builtins = levels.len();
        let campaign = Campaign {
            kind: CampaignKind::TidePool,
            levels,
            index: 0,
            builtins,
        };
        let settings = GameSettings::default();
        let said = |controllers: &Controllers| {
            versus_text(&Readout {
                tr: &EN,
                lang: Lang::En,
                sim: &Sim(Board::new(9, 7, 1)),
                campaign: &campaign,
                coop: false,
                phase: &State::new(Phase::Setup),
                vphase: &State::new(VersusPhase::Running),
                editor: &EditorState::default(),
                online: &Online::default(),
                playback: &Playback::default(),
                lobby: &LobbyState::default(),
                tournament: &crate::app::tournament::Tournament::default(),
                seats: &Seats(2),
                settings: &settings,
                keycaps: &crate::app::keycaps::KeyCaps::default(),
                names: &crate::app::SeatNames::default(),
                controllers,
                library: &crate::app::replays::Library::default(),
                notice: &crate::app::RoundNotice::default(),
                match_menu: &crate::app::match_setup::MatchMenu::default(),
                paused: false,
                spectator_typing: None,
                crowd: Default::default(),
                speed: 1,
            })
            .prompt
        };
        let mut against_ai = Controllers::default();
        against_ai.0[1] = SeatController::Ai(crate::sim::BotLevel::Normal);
        let mut against_bot = Controllers::default();
        against_bot.0[1] = SeatController::Bot;
        assert_eq!(said(&against_ai), EN.prompt_versus_short);
        assert_eq!(said(&against_bot), EN.prompt_versus_short);
        assert_eq!(said(&Controllers::default()), EN.prompt_versus_local);
    }

    /// And the prompt line says so too. The screen census below builds its
    /// readout with a single round, so the mid-series arm is one it cannot
    /// reach.
    #[test]
    fn the_prompt_carries_a_local_series_on_rather_than_offering_the_menu() {
        use crate::app::tournament::{SeriesLength, Tournament};
        use crate::app::{Campaign, CampaignKind, Controllers, Playback, Seats};

        let levels = campaign_levels();
        let builtins = levels.len();
        let campaign = Campaign {
            kind: CampaignKind::TidePool,
            levels,
            index: 0,
            builtins,
        };
        let settings = GameSettings::default();
        let said = |tournament: &Tournament| {
            versus_text(&Readout {
                tr: &EN,
                lang: Lang::En,
                sim: &Sim(Board::new(9, 7, 1)),
                campaign: &campaign,
                coop: false,
                phase: &State::new(Phase::Setup),
                vphase: &State::new(VersusPhase::Over),
                editor: &EditorState::default(),
                online: &Online::default(),
                playback: &Playback::default(),
                lobby: &LobbyState::default(),
                tournament,
                seats: &Seats(2),
                settings: &settings,
                keycaps: &crate::app::keycaps::KeyCaps::default(),
                names: &crate::app::SeatNames::default(),
                controllers: &Controllers::default(),
                library: &crate::app::replays::Library::default(),
                notice: &crate::app::RoundNotice::default(),
                match_menu: &crate::app::match_setup::MatchMenu::default(),
                paused: false,
                spectator_typing: None,
                crowd: Default::default(),
                speed: 1,
            })
            .prompt
        };

        assert_eq!(
            said(&Tournament::start(SeriesLength::BestOfThree)),
            EN.tour_next
        );
        // A single round is done with, and a decided series too.
        assert_eq!(said(&Tournament::default()), EN.prompt_enter_menu);
        let mut decided = Tournament::start(SeriesLength::BestOfThree);
        decided.wins[0] = 2;
        decided.state = crate::app::tournament::SeriesState::Decided;
        assert_eq!(said(&decided), EN.prompt_enter_menu);
    }

    /// The player's own levels are a shelf behind the shipped list, not
    /// stages a hundred and one and up. The header counts them from one
    /// under the stage list's own label for them, and the shipped campaign
    /// ends at its last shipped stage even with driftwood saved behind it:
    /// the results card says the run is over and Enter goes home there, so
    /// a prompt still offering the next level is the game arguing with
    /// itself.
    #[test]
    fn driftwood_is_a_shelf_behind_the_campaign_not_more_of_it() {
        let shipped = campaign_levels();
        let builtins = shipped.len();
        let mut levels = shipped.clone();
        levels.extend([shipped[0].clone(), shipped[1].clone()]);
        let mut campaign = Campaign {
            kind: CampaignKind::TidePool,
            levels,
            index: 0,
            builtins,
        };
        let said = |campaign: &Campaign, phase| {
            let sim = Sim(campaign.current().board());
            puzzle_text(
                &EN,
                Lang::En,
                campaign,
                false,
                &sim,
                &State::new(phase),
                false,
            )
        };

        // A shipped stage counts against the shipped list, not against the
        // list plus whatever the player has built.
        let title = said(&campaign, Phase::Setup).title;
        assert!(title.contains(&format!("1/{builtins}")), "{title}");
        assert!(!title.contains(EN.stage_custom), "{title}");

        campaign.index = builtins - 1;
        assert_eq!(said(&campaign, Phase::Won).prompt, EN.last_level);

        // The first of the player's own is one of two, under its own label.
        campaign.index = builtins;
        let HudText { title, prompt, .. } = said(&campaign, Phase::Won);
        assert!(title.contains(EN.stage_custom), "{title}");
        assert!(title.contains("1/2"), "{title}");
        // The label stands in for the list's name rather than joining it:
        // the header bar ends at the clock in the middle of the window.
        assert!(!title.contains(EN.title_tide_pool), "{title}");
        assert_eq!(prompt, EN.prompt_won);

        // And the last of them ends the list.
        campaign.index = builtins + 1;
        let HudText { title, prompt, .. } = said(&campaign, Phase::Won);
        assert!(title.contains("2/2"), "{title}");
        assert_eq!(prompt, EN.last_level);
    }

    /// The puzzle header counts what the level asks for, and the prompt
    /// changes when the inventory runs out: the difference between "place
    /// your signposts" and "you have none left, press Enter".
    #[test]
    fn the_puzzle_prompt_reacts_to_a_spent_inventory() {
        let levels = campaign_levels();
        let builtins = levels.len();
        let campaign = Campaign {
            kind: CampaignKind::TidePool,
            levels,
            index: 0,
            builtins,
        };
        let level: &Level = campaign.current();
        let posts = level.posts;
        let mut sim = Sim(level.board());
        let phase = State::new(Phase::Setup);

        let HudText { title, prompt, .. } =
            puzzle_text(&EN, Lang::En, &campaign, false, &sim, &phase, false);
        assert!(title.starts_with(EN.title_tide_pool), "{title}");
        assert!(
            title.contains("1/"),
            "the level's place in the list: {title}"
        );
        assert_eq!(
            prompt,
            if posts == 0 {
                EN.prompt_setup_no_posts
            } else {
                EN.prompt_setup
            }
        );

        // Spend the inventory: the prompt switches to the "full" advice.
        if posts > 0 {
            let mut placed = 0;
            'fill: for y in 0..sim.0.height() {
                for x in 0..sim.0.width() {
                    if placed == posts {
                        break 'fill;
                    }
                    if sim.0.place_signpost(0, x, y, crate::sim::Direction::Up) {
                        placed += 1;
                    }
                }
            }
            let prompt = puzzle_text(&EN, Lang::En, &campaign, false, &sim, &phase, false).prompt;
            assert_eq!(prompt, EN.prompt_setup_full);
        }

        // Rebound keys retire the stock legend rather than teach wrong keys.
        let prompt = puzzle_text(
            &EN,
            Lang::En,
            &campaign,
            false,
            &Sim(level.board()),
            &phase,
            true,
        )
        .prompt;
        assert_eq!(prompt, EN.prompt_setup_custom);
        // In co-op the stock line names both players' keys, and rebound
        // keys still win: the pair's keys are the settings' then.
        let coop = |custom| {
            puzzle_text(
                &EN,
                Lang::En,
                &campaign,
                true,
                &Sim(level.board()),
                &phase,
                custom,
            )
            .prompt
        };
        if posts > 0 {
            assert_eq!(coop(false), EN.prompt_setup_coop);
        }
        assert_eq!(coop(true), EN.prompt_setup_custom);
        // And so does the one-hand preset: placement is on IJKL then, not
        // the arrows the stock legend names.
        let one_hand = GameSettings {
            commit: crate::app::settings::CommitScheme::Ijkl,
            ..GameSettings::default()
        };
        assert!(!one_hand.stock_legend());
        assert!(GameSettings::default().stock_legend());
    }

    /// Every tide event maps to a distinct, non-empty localized name; an
    /// off-by-one here mislabels every banner and log line.
    #[test]
    fn every_tide_event_has_a_distinct_name() {
        let names: Vec<&str> = TideEvent::ALL
            .iter()
            .map(|&event| event_name(&EN, event))
            .collect();
        for name in &names {
            assert!(!name.is_empty());
        }
        let mut unique = names.clone();
        unique.sort_unstable();
        unique.dedup();
        assert_eq!(
            unique.len(),
            names.len(),
            "duplicate event names: {names:?}"
        );
    }

    #[test]
    fn clock_formats_minutes_and_seconds() {
        let tps = u64::from(TICKS_PER_SECOND);
        assert_eq!(clock_text(0), "0:00");
        assert_eq!(clock_text(29 * tps), "0:29");
        assert_eq!(clock_text(90 * tps), "1:30");
        assert_eq!(clock_text(600 * tps), "10:00");
    }

    /// The clock reddens inside the last 30 seconds and blinks for the last
    /// 10, unless the player asked for less motion, where it holds. The
    /// flat figures are for a long round (versus, or the untimed puzzle
    /// backstop) and are unchanged on one.
    #[test]
    fn the_clock_reddens_then_blinks() {
        let tps = u64::from(TICKS_PER_SECOND);
        let long = Some(3 * 60 * TICKS_PER_SECOND);
        for round in [None, long] {
            assert_eq!(clock_color(60 * tps, round, 0.0, true), CLOCK_CALM);
            assert_eq!(clock_color(20 * tps, round, 0.0, true), CLOCK_RED);
            // Inside ten seconds the colour alternates with the wall clock.
            assert_eq!(clock_color(5 * tps, round, 0.0, true), CLOCK_RED);
            assert_eq!(clock_color(5 * tps, round, 0.5, true), CLOCK_RED_BRIGHT);
            // Reduced motion: red, but steady.
            assert_eq!(clock_color(5 * tps, round, 0.5, false), CLOCK_RED);
        }
    }

    /// A round shorter than the flat band still has a calm stretch.
    ///
    /// Every timed level in the game is shorter than [`SURGE_TICKS`] (the
    /// longest `round:` any file asks for is 900, that figure exactly), so
    /// under a flat rule not one of them shows a calm clock: Dry Feet, at
    /// 240 ticks, is red and blinking from its first frame to its last.
    #[test]
    fn a_short_round_is_not_one_long_emergency() {
        let dry_feet = Some(240);
        // Two thirds of the way in, still calm; the last third reddens and
        // the very end of that blinks.
        assert_eq!(clock_color(200, dry_feet, 0.0, true), CLOCK_CALM);
        assert_eq!(clock_color(100, dry_feet, 0.0, true), CLOCK_CALM);
        assert_eq!(clock_color(60, dry_feet, 0.0, true), CLOCK_RED);
        assert_eq!(clock_color(20, dry_feet, 0.5, true), CLOCK_RED_BRIGHT);
        // The red always arrives before the blink, on any round length.
        for round in [240u32, 300, 900, 1800, 3600] {
            let red = urgency_band(Some(round), crate::sim::SURGE_TICKS);
            let blink = (0..=round)
                .rev()
                .map(u64::from)
                .find(|&t| clock_color(t, Some(round), 0.5, true) == CLOCK_RED_BRIGHT);
            assert!(
                blink.is_some_and(|blink| blink < red),
                "round {round}: reddens at {red}, blinks at {blink:?}"
            );
        }
    }

    /// The flat band is what a round long enough to have a middle gets;
    /// a shorter one gets its last third instead.
    #[test]
    fn the_urgency_band_shrinks_only_for_short_rounds() {
        assert_eq!(urgency_band(None, 900), 900);
        assert_eq!(urgency_band(Some(3600), 900), 900);
        assert_eq!(urgency_band(Some(901), 900), 900);
        // At and below the band, the last third of the round.
        assert_eq!(urgency_band(Some(900), 900), 300);
        assert_eq!(urgency_band(Some(240), 900), 80);
    }
}