pinch-points 0.4.0

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

use super::*;
use crate::app::i18n::fill;

/// What a frame does about hosting.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum HostStep {
    /// Ask who is asking, before anything is put on the air.
    Ask,
    /// Everything is answered: put the beach up.
    Go,
    Nothing,
}

/// What a frame knows about hosting.
///
/// A struct rather than four bools in a row, because `host_step(false,
/// true, false, false)` says nothing at the call site and any two of them
/// could be swapped without the compiler noticing.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) struct HostAsk {
    /// The beach has a name, which is the last thing the asking waits on.
    pub answered: bool,
    /// H, this frame.
    pub pressed_h: bool,
    /// Already at a beach, one's own or somebody else's.
    pub busy: bool,
    /// The unattended dev hook, which must never be stopped to answer a
    /// question nobody is sitting there to answer.
    pub auto: bool,
}

/// A frame in which nothing is pressed, nowhere has been reached and
/// nobody is automating. Every field named once, in one place, so a field
/// added later cannot be silently defaulted into tests that never mention
/// it, and so the tests say only what they change.
///
/// Beside the struct rather than inside a test module, because two test
/// modules want it and each had grown its own identical copy.
#[cfg(test)]
pub(super) fn idle() -> HostAsk {
    HostAsk {
        answered: false,
        pressed_h: false,
        busy: false,
        auto: false,
    }
}

/// Peers as they stand on a socket: named, with the given ones watching.
#[cfg(test)]
pub(super) fn peers_named(names: &[&str], watchers: &[usize]) -> crate::app::net::PeerBook {
    let mut peers = crate::app::net::PeerBook::default();
    for (i, name) in names.iter().enumerate() {
        peers.row(i).name = name.to_string();
    }
    for watcher in watchers {
        peers.row(*watcher).watch = true;
    }
    peers
}

/// Where this beach is, written the way somebody else would have to type
/// it: `ip:port`.
///
/// `None` when the machine has no address worth reading out: no route off
/// itself, or a socket that will not say what port it took. The
/// beacon carries the address for everyone who can hear it; this is for
/// the friend who cannot.
pub(super) fn address_here(transport: &UdpTransport) -> Option<String> {
    let port = transport.local_addr().ok()?.port();
    let ip = crate::transport::local_ip()?;
    Some(SocketAddr::new(ip, port).to_string())
}

/// Whether this frame asks about hosting, does it, or neither.
pub(super) fn host_step(ask: HostAsk) -> HostStep {
    if ask.answered {
        return HostStep::Go;
    }
    if ask.busy {
        return HostStep::Nothing;
    }
    match (ask.pressed_h || ask.auto, ask.auto) {
        (true, true) => HostStep::Go,
        (true, false) => HostStep::Ask,
        (false, _) => HostStep::Nothing,
    }
}

/// Hosting: announce on a timer, gather joiners (up to five rivals, plus
/// onlookers), and launch on Enter (or once the auto-host quota fills).
#[allow(clippy::too_many_arguments)]
pub fn host_tick(
    time: Res<Time>,
    keys: Res<ButtonInput<KeyCode>>,
    settings: Res<GameSettings>,
    config: Res<crate::app::match_setup::MatchConfig>,
    beaches: Res<crate::app::match_setup::CustomBeaches>,
    mut state: ResMut<LobbyState>,
    mut online: ResMut<Online>,
    mut tournament: ResMut<crate::app::tournament::Tournament>,
    mut next_screen: ResMut<NextState<Screen>>,
    mut next_vphase: ResMut<NextState<VersusPhase>>,
) {
    let tr = settings.tr();
    let game_name = state.game_name.clone();
    let Some(hosted) = state.hosted_mut() else {
        return;
    };
    // The occupancy is a frame stale by the time the beacon goes out,
    // which costs nothing at one beacon a second. The host holds a seat
    // too, so the table is never empty; seats are the hard limit rather
    // than the configured count, since an AI seat gives way to a player
    // who turns up for it.
    let taken = 1 + hosted.players_aboard() as u8;
    let on_air = crate::transport::OnAir {
        name: &game_name,
        host: &settings.names[0],
        taken,
        seats: MAX_PLAYERS as u8,
    };
    let picked = work_the_socket(hosted, time.delta_secs(), on_air);
    let do_announce = picked.announced;
    for (_, name, text) in picked.said {
        state.hear(&name, &text);
    }
    note_arrivals_and_departures(&mut state, tr, picked.greeted);
    // Counted after the departures, so a table that just lost somebody is
    // not announced as still holding them.
    let joined = state.hosted().map_or(0, |hosted| hosted.peers.len());
    // The host's own view of the table, and the peers': the same list,
    // sent on every beacon tick so a lost one costs a second, not a screen
    // that stays wrong until somebody joins or leaves.
    state.table = state.roster(tr, &settings.names[0]);
    if do_announce && let Some(hosted) = state.hosted() {
        let names = crate::transport::wire_table(&state.table);
        // The dials travel with the roster so a joiner's terms card shows
        // the match it is joining. The seed is not one of them yet - it is
        // struck fresh at launch - so a placeholder rides along and the
        // card ignores it.
        let terms = crate::app::match_setup::terms(&config, settings.team_mode, 0);
        hosted.transport.send(NetMsg::Roster {
            seats: state.table.len().min(MAX_PLAYERS) as u8,
            names,
            terms,
        });
    }
    let (players_aboard, watchers_aboard, port) = state.hosted().map_or((0, 0, None), |hosted| {
        (
            hosted.players_aboard(),
            hosted.watchers_aboard(),
            hosted.transport.local_addr().ok().map(|addr| addr.port()),
        )
    });
    if joined > 0 {
        state.feedback = gathering_feedback(tr, &config, players_aboard, watchers_aboard);
    } else {
        // The last peer timed out: without this the line kept saying "1
        // rival aboard" over an empty table until somebody else turned up,
        // and Enter did nothing. Back to the waiting message it started on.
        state.feedback = match port {
            Some(port) => fill(tr.lobby_hosting, &[("p", &port.to_string())]),
            None => tr.lobby_hosting_noport.to_string(),
        };
    }
    let quota = crate::app::dev::auto_host_quota();
    let launch = should_launch(
        joined,
        state.typing.is_some(),
        crate::app::menu_ui::enter(&keys),
        quota,
    );
    if launch {
        launch_the_match(
            &mut state,
            &settings,
            &config,
            &beaches,
            joined,
            &mut online,
            &mut tournament,
            &mut next_screen,
            &mut next_vphase,
        );
    }
}

/// Put the match on: seat everyone who came to play, agree the terms, and
/// walk the whole table into the arena.
///
/// Lifted out of `host_tick`, which had grown to nine jobs and two hundred
/// and fifty lines by accretion, a feature at a time, each reasonable on
/// its own. This is the one of them with a beginning and an end.
#[allow(clippy::too_many_arguments)]
fn launch_the_match(
    state: &mut LobbyState,
    settings: &GameSettings,
    config: &MatchConfig,
    beaches: &crate::app::match_setup::CustomBeaches,
    joined: usize,
    online: &mut Online,
    tournament: &mut crate::app::tournament::Tournament,
    next_screen: &mut NextState<Screen>,
    next_vphase: &mut NextState<VersusPhase>,
) {
    // The beacon does not stop at launch, it changes what it says: a
    // running beach cannot be joined, since lockstep has nothing to
    // catch a latecomer up with, but it can be queued for. The
    // announcer rides along into the session to keep saying so, and the
    // peers ride along to be dealt their chairs.
    let Standing::Hosting(Hosted {
        announcer,
        transport,
        peers,
        announce_in: _,
    }) = std::mem::take(&mut state.standing)
    else {
        unreachable!("launching a match from a lobby that is not hosting");
    };
    debug_assert_eq!(joined, peers.len());
    let plan = seat_plan(&peers);
    let humans = 1 + plan.iter().filter(|seat| seat.is_some()).count() as u8;
    // AI seats come from the host's match setup, and sit behind the
    // humans. The host's dials and its team-scoring setting travel with
    // them: a match is played on one set of terms, not four.
    //
    // A beach needs two castles, so the AI floor is raised to reach two
    // seats when only onlookers turned up (every peer a watcher, or a lone
    // watcher aboard): a one-seat `Start` is refused by every joiner's
    // decoder and would leave the host playing an empty beach. The same
    // floor `call_next_round` keeps between rounds.
    let bots = config
        .bots
        .min(MAX_PLAYERS as u8 - humans)
        .max(2u8.saturating_sub(humans));
    let seats = humans + bots;
    let seed = crate::app::clock::fresh_seed();
    // A beach the host built travels with the invitation; a generated one
    // is already described by the seed in the terms.
    let beach = crate::app::match_setup::beach_bytes(config, seats, beaches);
    let terms = MatchTerms {
        bots,
        // The beach has to hold everyone who turned up, which the host
        // could not have known when it picked one.
        map: map_for(config, seats).index() as u8,
        ..crate::app::match_setup::terms(config, settings.team_mode, seed)
    };
    // The table's names: the host is seat 0 under its own P1 name, and
    // each seated peer under the name its greeting carried. Empty slots
    // (AI seats, the nameless) fall back to seat labels on every screen.
    let mut names: [String; MAX_PLAYERS] = Default::default();
    names[0].clone_from(&settings.names[0]);
    for (peer, slot) in plan.iter().enumerate() {
        if let Some(seat) = slot
            && let Some(peer) = peers.get(peer)
        {
            names[usize::from(*seat)].clone_from(&peer.name);
        }
    }
    let wire_names = crate::transport::wire_table(&names);
    // Seats go to the peers that came to play, in peer order; the
    // onlookers - and anyone the table ran out of chairs for - are told
    // they are watching.
    // A series begins at round one with an empty tally; a single round
    // carries no standing at all.
    let standing = terms
        .is_series()
        .then(crate::transport::SeriesStanding::opening);
    for (peer, slot) in plan.iter().enumerate() {
        transport.send_to(
            peer,
            NetMsg::Start {
                seats,
                seat: *slot,
                terms,
                names: wire_names,
                standing,
                beach: beach.clone(),
            },
        );
    }
    let mut session = OnlineSession::new(
        transport,
        crate::app::net::lockstep_for(Some(0), humans),
        seats,
        terms,
    );
    // The host plays on the same bytes it sent, not on its own copy of the
    // file: if the two ever disagreed, the hash check would find it and
    // nobody could say which of them was right.
    session.beach = beach;
    session.peers = peers;
    session.peers.deal(&plan);
    session.names = names;
    session.stay_on_air(announcer);
    session.home.from_lobby = true;
    session.home.game_name = state.game_name.clone();
    online.0 = Some(session);
    // The series is part of the terms, so every peer knows it is one
    // and tallies the same rounds. Without that the host alone would
    // count, and only the host would see a champion.
    *tournament = crate::app::tournament::Tournament::from_terms(terms, standing);
    next_vphase.set(VersusPhase::Running);
    next_screen.set(Screen::Versus);
}

/// Fold this tick's greetings and silences into the table: who has just
/// arrived, and who has stopped answering.
///
/// Both are news for the feed and for every peer, and both are the same
/// kind of bookkeeping, which is why they sit together rather than at
/// opposite ends of a two-hundred-line system.
fn note_arrivals_and_departures(
    state: &mut LobbyState,
    tr: &'static crate::app::i18n::Tr,
    greeted: Vec<(usize, String)>,
) {
    for (from, told) in greeted {
        let Some(hosted) = state.hosted_mut() else {
            return;
        };
        // A greeting arrives every second; only the first one, or a change
        // of mind about the name, is news worth putting in the feed.
        let row = hosted.peers.row(from);
        let arrived = row.name != told;
        row.name.clone_from(&told);
        if arrived {
            let notice = fill(tr.lobby_joined, &[("p", &told)]);
            state.say("", &notice);
            announce_to_table(state, "", &notice);
        }
    }
    // Anyone unheard for too long has walked away: UDP will not say so, and
    // a table that keeps counting them never has room again.
    let gone: Vec<usize> = state.hosted().map_or(Vec::new(), |hosted| {
        (0..hosted.peers.len())
            .rev()
            .filter(|peer| {
                hosted
                    .peers
                    .get(*peer)
                    .is_some_and(|p| p.silence > PEER_TTL)
            })
            .collect()
    });
    for peer in gone {
        let Some(hosted) = state.hosted_mut() else {
            return;
        };
        let who = hosted
            .peers
            .get(peer)
            .map_or_else(String::new, |p| p.name.clone());
        hosted.forget_peer(peer);
        if !who.is_empty() {
            let notice = fill(tr.lobby_left, &[("p", &who)]);
            state.say("", &notice);
            announce_to_table(state, "", &notice);
        }
    }
}

/// What one tick on the socket picked up: whether the beacon went out,
/// who named themselves, and what was said. Bundled because they travel
/// together and a function with eight arguments is a function asking to
/// be given a noun.
#[derive(Default)]
struct Picked {
    /// The once-a-second tick fell this frame, so the roster goes out too.
    announced: bool,
    greeted: Vec<(usize, String)>,
    said: Vec<(
        usize,
        crate::transport::WireName,
        crate::transport::WireChat,
    )>,
}

/// One tick on the host's own socket: age the table, put the beacon up,
/// take in what the peers sent, and pass the chat along to the rest of
/// the table.
///
/// What it learns goes back to the caller to be folded into the lobby,
/// which needs the rest of the state this borrow of the beach is holding.
fn work_the_socket(hosted: &mut Hosted, delta: f32, on_air: crate::transport::OnAir<'_>) -> Picked {
    let Hosted {
        announcer,
        transport,
        peers,
        announce_in,
    } = hosted;
    let mut picked = Picked {
        announced: once_a_second(announce_in, delta),
        ..Picked::default()
    };
    peers.age(delta);
    if picked.announced
        && let Ok(addr) = transport.local_addr()
    {
        announcer.announce(addr.port(), on_air);
    }
    // recv_all registers joiners from their greetings; a Watch tells us
    // that peer is here to look, not to play, and a Hello says what to
    // call whoever sent it.
    for (msg, from) in transport.recv_all() {
        // A peer the socket has only just registered has no row yet, and
        // anything at all from a peer is proof it is still there.
        peers.reach(transport.peer_count());
        peers.heard(from);
        match msg {
            NetMsg::Watch => peers.row(from).watch = true,
            NetMsg::Hello { name } => {
                let told = crate::transport::name_from_wire(&name);
                if !told.is_empty() {
                    picked.greeted.push((from, told));
                }
            }
            // The spokes of the star cannot hear each other, so the
            // hub repeats what it is told before showing it - under the
            // name it knows the sender by, not the one the datagram
            // claims. Chat is the only message that names its own sender,
            // and the host is the only peer that can check the claim,
            // since it alone knows which socket the line came from.
            //
            // Unchecked, a peer could speak under a rival's name, or under
            // the empty one, which is worse: an empty name is the room
            // itself talking (`Said::is_notice`), the channel that says who
            // joined and who left. So an empty name is refused outright
            // whoever sends it - that voice is the host's.
            //
            // The claim stands only where there is nothing to check it
            // against: a watcher greets with a bare `Watch` and never says
            // what to call it, so its own word is all the name it has.
            NetMsg::Chat { name, text } => {
                let known = peers.get(from).map_or("", |peer| peer.name.as_str());
                let who = match known.is_empty() {
                    false => crate::transport::wire_name(known),
                    true => name,
                };
                if !crate::transport::name_from_wire(&who).is_empty() {
                    picked.said.push((from, who, text));
                }
            }
            NetMsg::Input(_)
            | NetMsg::Hash { .. }
            | NetMsg::Start { .. }
            | NetMsg::Pause { .. }
            | NetMsg::Resume { .. }
            | NetMsg::Queued { .. }
            | NetMsg::Roster { .. }
            | NetMsg::Abandoned { .. }
            | NetMsg::Incompatible { .. } => {}
        }
    }
    for (from, name, text) in picked.said.iter() {
        crate::app::net::relay(
            transport,
            *from,
            NetMsg::Chat {
                name: *name,
                text: *text,
            },
        );
    }
    picked
}

/// The line under the title while gathering: who is aboard, who is only
/// watching, and how many chairs the AI will take in behind them.
///
/// Pure, so what a host reads while waiting is checkable without a socket.
pub(super) fn gathering_feedback(
    tr: &'static crate::app::i18n::Tr,
    config: &MatchConfig,
    players_aboard: usize,
    watching: usize,
) -> String {
    let mut line = match players_aboard {
        1 => tr.lobby_rivals_one.to_string(),
        n => fill(tr.lobby_rivals_many, &[("n", &n.to_string())]),
    };
    if watching > 0 {
        line += &fill(tr.lobby_watchers, &[("n", &watching.to_string())]);
    }
    // The AI seats come from the host's dials, not from this count, so say
    // how many are coming rather than surprising the table with them.
    let bots = config
        .bots
        .min((MAX_PLAYERS as u8).saturating_sub((players_aboard + 1) as u8));
    if bots > 0 {
        line += &fill(tr.lobby_ai_seats, &[("n", &bots.to_string())]);
    }
    line
}

/// Whether this frame starts the match.
///
/// Not while a line is being typed, which is the entire job of this: the
/// host is the one player who both talks and starts, `host_tick` runs
/// ahead of the input that owns the keyboard, and Enter therefore launched
/// the match out from under a half-written sentence. It could not send a
/// message at all.
///
/// The unattended quota is exempt: nothing is being typed on a machine
/// nobody is sitting at.
pub(super) fn should_launch(
    joined: usize,
    typing: bool,
    enter: bool,
    quota: Option<usize>,
) -> bool {
    if joined == 0 {
        return false;
    }
    match quota {
        Some(quota) if joined >= quota => true,
        _ => enter && !typing,
    }
}

/// Say something to every peer at the table, as the host. An empty `who`
/// is the lobby speaking rather than a player.
pub(super) fn announce_to_table(state: &LobbyState, who: &str, line: &str) {
    if let Some(hosted) = state.hosted() {
        hosted.transport.send(NetMsg::chat(who, line));
    }
}

/// Which peers get a seat, in peer order, and which are watching (`None`).
///
/// Seats run out before connections do: the socket takes nine peers and the
/// table has six chairs. The surplus is seated as onlookers rather than
/// handed a seat number the sim has no slot for.
pub(super) fn seat_plan(peers: &crate::app::net::PeerBook) -> Vec<Option<u8>> {
    let mut next = 1u8; // seat 0 is the host's
    peers
        .iter()
        .map(|peer| {
            if peer.watch || usize::from(next) >= MAX_PLAYERS {
                return None;
            }
            let seat = next;
            next += 1;
            Some(seat)
        })
        .collect()
}

/// Tell the network a hosted beach is going away, if this lobby is hosting
/// one. Both ways out of hosting come through here: leaving the screen, and
/// starting the match.
pub(super) fn say_goodbye(state: &LobbyState) {
    if let Some(hosted) = state.hosted()
        && let Ok(addr) = hosted.transport.local_addr()
    {
        hosted.announcer.closing(addr.port());
    }
}

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

    /// `n` nameless peers, the given ones watching.
    fn table(n: usize, watchers: &[usize]) -> crate::app::net::PeerBook {
        let names = vec![""; n];
        peers_named(&names, watchers)
    }

    /// Seats go to the peers that came to play, in the order they arrived,
    /// with the host holding seat zero throughout.
    #[test]
    fn the_table_is_dealt_in_arrival_order_behind_the_host() {
        assert_eq!(seat_plan(&table(0, &[])), Vec::<Option<u8>>::new());
        assert_eq!(
            seat_plan(&table(1, &[])),
            vec![Some(1)],
            "the host keeps zero"
        );
        assert_eq!(seat_plan(&table(3, &[])), vec![Some(1), Some(2), Some(3)]);
    }

    /// An onlooker takes no chair, and the players behind it close up
    /// rather than inheriting a gap.
    #[test]
    fn watchers_are_stepped_over_and_the_seats_close_up() {
        assert_eq!(seat_plan(&table(3, &[0])), vec![None, Some(1), Some(2)]);
        assert_eq!(seat_plan(&table(3, &[1])), vec![Some(1), None, Some(2)]);
        assert_eq!(seat_plan(&table(3, &[0, 1, 2])), vec![None, None, None]);
    }

    /// Every answer `host_step` can give. It asks who is asking before
    /// anything goes on the air, does nothing once there is already a
    /// beach, and never stops the dev hook to ask a question nobody is
    /// sitting there to answer.
    #[test]
    fn hosting_asks_before_it_announces() {
        assert_eq!(host_step(idle()), HostStep::Nothing);
        assert_eq!(
            host_step(HostAsk {
                pressed_h: true,
                ..idle()
            }),
            HostStep::Ask
        );
        assert_eq!(
            host_step(HostAsk {
                answered: true,
                ..idle()
            }),
            HostStep::Go
        );
        // Busy is busy, pressed or not: without this the prompt would
        // open over a running lobby.
        assert_eq!(
            host_step(HostAsk {
                pressed_h: true,
                busy: true,
                ..idle()
            }),
            HostStep::Nothing
        );
        assert_eq!(
            host_step(HostAsk {
                busy: true,
                ..idle()
            }),
            HostStep::Nothing
        );
        // And the unattended hook goes straight through, H or no H: a
        // prompt on a machine nobody is sitting at is a hang.
        assert_eq!(
            host_step(HostAsk {
                auto: true,
                ..idle()
            }),
            HostStep::Go
        );
        assert_eq!(
            host_step(HostAsk {
                pressed_h: true,
                auto: true,
                ..idle()
            }),
            HostStep::Go
        );
    }

    /// The socket takes more peers than the table has chairs, so the extras
    /// watch rather than take a seat the sim has no slot for.
    #[test]
    fn the_table_runs_out_of_chairs_before_the_socket_runs_out_of_peers() {
        use crate::sim::MAX_PLAYERS;

        // Four rivals on a six-seat table: seats 1-4 behind the host's 0.
        assert_eq!(
            seat_plan(&table(4, &[])),
            vec![Some(1), Some(2), Some(3), Some(4)]
        );
        // Peers 1 and 3 came to watch, so the seats close up behind them.
        assert_eq!(
            seat_plan(&table(4, &[1, 3])),
            vec![Some(1), None, Some(2), None]
        );
        // Every connection the socket will take, all of them here to play.
        let full = seat_plan(&table(crate::transport::MAX_PEERS, &[]));
        assert_eq!(
            full.iter().filter(|seat| seat.is_some()).count(),
            MAX_PLAYERS - 1,
            "the host holds the sixth chair"
        );
        assert!(
            full.iter()
                .flatten()
                .all(|&seat| usize::from(seat) < MAX_PLAYERS),
            "no peer is given a seat the sim has no slot for"
        );
        assert!(full.last().unwrap().is_none(), "the late ones watch");
    }

    /// Enter means two things to a host, say this and start the match, and
    /// it cannot mean both. `host_tick` runs before the input that owns
    /// the keyboard, so an Enter meant to send a line used to launch the
    /// round instead, which left the host unable to say anything at all.
    #[test]
    fn a_half_written_sentence_does_not_start_the_match() {
        // The everyday case: rivals aboard, nothing being typed, Enter goes.
        assert!(should_launch(1, false, true, None));
        assert!(
            !should_launch(1, false, false, None),
            "and nothing without it"
        );
        assert!(
            !should_launch(0, false, true, None),
            "nor with an empty table"
        );

        // Mid-sentence, Enter belongs to the sentence.
        assert!(!should_launch(1, true, true, None));
        assert!(!should_launch(3, true, true, None));

        // The unattended quota is exempt: nobody is sitting at that machine
        // to be typing, and it must not wait for an Enter that never comes.
        assert!(should_launch(2, false, false, Some(2)));
        assert!(should_launch(2, true, false, Some(2)));
        assert!(!should_launch(1, false, false, Some(2)), "not filled yet");
    }

    /// Chat is the one message that names its own sender, and the host is
    /// the only peer that can check the claim. A line comes back under the
    /// name its sender greeted with, whatever the datagram says: a peer
    /// wearing a rival's name is put back in its own, and one wearing no
    /// name at all - the room's own voice, which is what says who joined
    /// and who left - is put back in its own too, so a forged notice comes
    /// out as somebody saying something odd rather than as the room.
    ///
    /// Over a real socket, because the whole point is which end of it the
    /// line arrived on.
    #[test]
    fn a_peer_speaks_under_the_name_it_greeted_with() {
        let mut state = LobbyState {
            standing: Standing::hosting(
                Announcer::new(0xC0FFEE).expect("announcer"),
                UdpTransport::host(0).expect("game socket"),
            ),
            ..LobbyState::default()
        };
        let port = state
            .hosted()
            .expect("hosting")
            .transport
            .local_addr()
            .expect("addr")
            .port();
        let bo = UdpTransport::join(("127.0.0.1", port)).expect("join");
        bo.send(NetMsg::hello("Bo"));

        // Drain until the greeting has been folded into Bo's row, which is
        // what the stamping reads.
        let mut said = Vec::new();
        for _ in 0..40 {
            std::thread::sleep(std::time::Duration::from_millis(5));
            let hosted = state.hosted_mut().expect("hosting");
            let picked = work_the_socket(hosted, 0.0, crate::transport::OnAir::default());
            for (from, told) in picked.greeted {
                hosted.peers.row(from).name = told;
            }
            said.extend(picked.said);
            if state
                .hosted()
                .expect("hosting")
                .peers
                .get(0)
                .is_some_and(|peer| peer.name == "Bo")
            {
                break;
            }
        }
        assert_eq!(
            state
                .hosted()
                .expect("hosting")
                .peers
                .get(0)
                .map(|p| p.name.as_str()),
            Some("Bo"),
            "the greeting is on file"
        );

        // Bo now says three things: one under its own name, one wearing a
        // rival's, and one wearing none.
        bo.send(NetMsg::chat("Bo", "ready?"));
        bo.send(NetMsg::chat("Anna", "I am Anna, honest"));
        bo.send(NetMsg::chat("", "Anna has left the beach"));
        said.clear();
        for _ in 0..40 {
            std::thread::sleep(std::time::Duration::from_millis(5));
            let hosted = state.hosted_mut().expect("hosting");
            said.extend(work_the_socket(hosted, 0.0, crate::transport::OnAir::default()).said);
            if said.len() >= 2 {
                break;
            }
        }
        let heard: Vec<(String, String)> = said
            .iter()
            .map(|(_, name, text)| {
                (
                    crate::transport::name_from_wire(name),
                    crate::transport::chat_from_wire(text),
                )
            })
            .collect();
        assert_eq!(
            heard,
            [
                ("Bo".to_string(), "ready?".to_string()),
                ("Bo".to_string(), "I am Anna, honest".to_string()),
                ("Bo".to_string(), "Anna has left the beach".to_string()),
            ],
            "every line under the name Bo greeted with: no rival's name to \
             wear, and no forging the room's"
        );
    }

    /// The one peer the host has no name for: a watcher greets with a bare
    /// `Watch` and never says what to call it, so its own word is all there
    /// is to go on. Its word may not be the empty one, though - that is the
    /// room talking, and a peer is not the room, however little is known
    /// about it.
    #[test]
    fn a_nameless_peer_may_name_itself_but_not_the_room() {
        let mut state = LobbyState {
            standing: Standing::hosting(
                Announcer::new(0xDECAF).expect("announcer"),
                UdpTransport::host(0).expect("game socket"),
            ),
            ..LobbyState::default()
        };
        let port = state
            .hosted()
            .expect("hosting")
            .transport
            .local_addr()
            .expect("addr")
            .port();
        let rail = UdpTransport::join(("127.0.0.1", port)).expect("join");
        rail.send(NetMsg::Watch);
        rail.send(NetMsg::chat("", "Anna has left the beach"));
        rail.send(NetMsg::chat("Cy", "good luck!"));

        let mut said = Vec::new();
        for _ in 0..40 {
            std::thread::sleep(std::time::Duration::from_millis(5));
            let hosted = state.hosted_mut().expect("hosting");
            said.extend(work_the_socket(hosted, 0.0, crate::transport::OnAir::default()).said);
            if !said.is_empty() {
                break;
            }
        }
        let heard: Vec<(String, String)> = said
            .iter()
            .map(|(_, name, text)| {
                (
                    crate::transport::name_from_wire(name),
                    crate::transport::chat_from_wire(text),
                )
            })
            .collect();
        assert_eq!(
            heard,
            [("Cy".to_string(), "good luck!".to_string())],
            "the watcher names itself, and the forged notice is dropped \
             rather than carried under a name nobody has"
        );
    }
}