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
//! 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::{Bots, Campaign, CampaignKind, Phase, Playback, Screen, Seats, Sim, VersusPhase};
use crate::sim::{Goal, LURE_TICKS, TideEvent};
use bevy::prelude::*;

pub(super) const CLOCK_CALM: Color = Color::srgb(0.95, 0.93, 0.84);
pub(super) const CLOCK_RED: Color = Color::srgb(0.96, 0.25, 0.18);
pub(super) const CLOCK_RED_BRIGHT: Color = Color::srgb(1.0, 0.55, 0.25);

/// mm:ss for a remaining-tick count.
pub(crate) fn clock_text(ticks: u64) -> String {
    let secs = ticks / u64::from(crate::sim::TICKS_PER_SECOND);
    format!("{}:{:02}", secs / 60, secs % 60)
}

/// The clock colour ramp: calm, red inside 30 s, blinking half-seconds
/// for the last 10. `blink` is off under reduced motion, where the final
/// ten seconds simply hold the bright red instead of flashing.
pub(crate) fn clock_color(ticks: u64, elapsed: f32, blink: bool) -> Color {
    let secs = ticks / u64::from(crate::sim::TICKS_PER_SECOND);
    if secs <= 10 {
        if !blink || ((elapsed * 2.0) as u32).is_multiple_of(2) {
            CLOCK_RED
        } else {
            CLOCK_RED_BRIGHT
        }
    } else if secs <= 30 {
        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)`, which is what six
/// functions here used to hand back. Every one of them built the three in
/// a different order internally, and nothing but position said which was
/// which: a screen that swapped its status and its prompt would compile,
/// run, and read as a screen whose header had gone strange.
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::ChoosingToWatch => tr.lobby_watch_armed.to_string(),
        Standing::Joining => tr.lobby_aboard_prompt.to_string(),
        Standing::Hosting => tr.lobby_broadcasting.to_string(),
        Standing::Choosing if lobby.hosts.is_empty() => tr.lobby_none_yet.to_string(),
        Standing::Choosing => {
            // 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.testing.is_some();
    // The title carries the level's name, because the name is now the file
    // it saves to and the caption the stage list will show: it has to be
    // somewhere a player can see it before pressing F2.
    // What is being built is as much a part of the title as what it is
    // called: the two kinds save to different lists, and an author who
    // finds that out at the map dial found out 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.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,
    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,
    };
    let title = format!(
        "{} {}/{} - {}",
        campaign_title,
        campaign.index + 1,
        campaign.levels.len(),
        lang.level_name(&level.name)
    );
    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(),
            ),
        ],
    );
    let status = match level.goal {
        Goal::AllCrabs => format!(
            "{} | {saved}",
            fill(
                tr.signposts_count,
                &[("a", &used.to_string()), ("b", &level.posts.to_string())]
            )
        ),
        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", "")]),
    };
    let prompt = match phase.get() {
        Phase::Setup if level.posts == 0 => tr.prompt_setup_no_posts.to_string(),
        Phase::Setup if used >= level.posts as usize => tr.prompt_setup_full.to_string(),
        Phase::Setup if custom_keys => tr.prompt_setup_custom.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.index + 1 == campaign.levels.len() => tr.last_level.to_string(),
        Phase::Won => tr.prompt_won.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, which had
/// grown past the point where the order of two `&Res`es of the same shape
/// was checked by anything but eyesight.
pub(super) fn versus_text(r: &Readout) -> HudText {
    let Readout {
        tr,
        sim,
        seats,
        settings,
        names,
        playback,
        online,
        bots,
        vphase,
        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 bots.0.iter().any(Option::is_some) {
        let count = bots.0.iter().filter(|b| b.is_some()).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()
    };
    if let Some((event, at)) = sim.0.last_event()
        && sim.0.ticks().saturating_sub(at) < 90
    {
        status = fill(tr.tide_event, &[("e", event_name(tr, event))]);
    }
    if let Some((owner, remaining)) = sim.0.lure() {
        let seat = names.label(tr, owner);
        // First moments name the trigger; then a live countdown.
        status = if remaining > LURE_TICKS - 60 {
            fill(tr.lure_started, &[("p", &seat)])
        } else {
            fill(
                tr.lure_banner,
                &[("s", &remaining.div_ceil(30).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 of the thing, and a line that
            // came and went with each of them was a strobe in the corner
            // of the eye.
            status = fill(tr.waiting_for, &[("p", &names.label(tr, seat))]);
        }
    }
    let prompt = match vphase.get() {
        // A replay - or someone else's match - is watched, not played: no
        // control legend for a seat you do not have.
        VersusPhase::Running
            if playback.0.is_some() || online.0.as_ref().is_some_and(|s| s.session.watching()) =>
        {
            tr.prompt_enter_menu.to_string()
        }
        VersusPhase::Running if online.0.is_some() || bots.0.iter().any(Option::is_some) => {
            tr.prompt_versus_short.to_string()
        }
        VersusPhase::Running if settings.custom_binds() => tr.prompt_versus_custom.to_string(),
        VersusPhase::Running => tr.prompt_versus_local.to_string(),
        VersusPhase::Over => tr.prompt_enter_menu.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,
    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,
    pub seats: &'a Seats,
    pub settings: &'a GameSettings,
    pub names: &'a crate::app::SeatNames,
    pub bots: &'a Bots,
    pub library: &'a crate::app::replays::Library,
    /// What the menu has to say about a round put down, 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,
    pub speed: u8,
}

/// What the header, the status slot and the prompt line say on `screen`.
/// 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) {
        said.prompt = format!("{} | {}", said.prompt, r.tr.prompt_mute);
    }
    said
}

pub(super) fn screen_text_for(screen: Screen, r: &Readout) -> HudText {
    match screen {
        // The menu's status slot carries word of a round just put down, or
        // 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_esc_menu.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
            ),
            String::new(),
            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.sim,
            r.phase,
            !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 are the
        // preview of whatever is highlighted. The status slot stays empty
        // - the note that belongs there sits under the card instead,
        // beside the list rather than in the far corner of the header.
        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. A screen
    /// added without a HUD arm would otherwise show the last screen's
    /// header, which is the kind of thing nobody notices until a player
    /// does.
    #[test]
    fn every_screen_names_itself_and_its_keys() {
        use crate::app::{Bots, Campaign, CampaignKind, 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 readout = Readout {
            tr: &EN,
            lang: Lang::En,
            sim: &Sim(Board::new(9, 7, 1)),
            campaign: &campaign,
            phase: &State::new(Phase::Setup),
            vphase: &State::new(VersusPhase::Running),
            editor: &EditorState::default(),
            online: &Online::default(),
            playback: &Playback::default(),
            lobby: &LobbyState::default(),
            seats: &Seats(2),
            settings: &settings,
            names: &crate::app::SeatNames::default(),
            bots: &Bots::default(),
            library: &crate::app::replays::Library::default(),
            notice: &crate::app::RoundNotice::default(),
            match_menu: &crate::app::match_setup::MatchMenu::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");
            }
        }
    }

    /// 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.naming = true;
        let typing = editor_text(&EN, &editor, &sim).title;
        assert!(typing.ends_with('_'), "{typing}");
        editor.naming = false;

        editor.testing = Some(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,
                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");
    }

    /// 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, &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, &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, &Sim(level.board()), &phase, true).prompt;
        assert_eq!(prompt, 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 = crate::app::settings::GameSettings {
            ijkl_commits: true,
            ..crate::app::settings::GameSettings::default()
        };
        assert!(!one_hand.stock_legend());
        assert!(crate::app::settings::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(crate::sim::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.
    #[test]
    fn the_clock_reddens_then_blinks() {
        let tps = u64::from(crate::sim::TICKS_PER_SECOND);
        assert_eq!(clock_color(60 * tps, 0.0, true), CLOCK_CALM);
        assert_eq!(clock_color(20 * tps, 0.0, true), CLOCK_RED);
        // Inside ten seconds the colour alternates with the wall clock.
        assert_eq!(clock_color(5 * tps, 0.0, true), CLOCK_RED);
        assert_eq!(clock_color(5 * tps, 0.5, true), CLOCK_RED_BRIGHT);
        // Reduced motion: red, but steady.
        assert_eq!(clock_color(5 * tps, 0.5, false), CLOCK_RED);
    }
}