pinch-points 0.9.0

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

use crate::sim::{HASH_INTERVAL, Lockstep, MAX_PLAYERS, PlayerAction};
use crate::transport::{
    Announcer, Batch, MatchTerms, NetMsg, SeriesStanding, UdpTransport, chat_from_wire,
    name_from_wire, table_from_wire, wire_table,
};
use bevy::prelude::*;
pub use peers::{Goodbye, Peer, PeerBook, Place, renumber};
use std::collections::VecDeque;

/// A bot connected straight to this host (route 2): the seat it holds
/// this round, which of the host's bots it is, and what it is called.
///
/// Named rather than a tuple: `(seat, id, ..)` is two small numbers next
/// to each other, kept apart only by their order.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct HostedBot {
    pub seat: u8,
    pub id: crate::bots::listener::BotId,
    pub name: String,
}

/// Why a joiner was put out of the beach it greeted, each of them the
/// end of the greeting: the socket let go, and a line saying why. Heard in
/// the lobby and mid-round alike, and said with the same line in both.
///
/// Ordered from least to most telling: when several arrive together, the
/// greatest is the one said (`PutOut::hear`), whatever order they came in.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub enum PutOut {
    /// The host closed its socket: the beach is gone, whether or not its
    /// beacon's farewell reached this listener.
    Closed,
    /// The host's socket had no room for this peer, watching or playing
    /// ([`crate::transport::MAX_PEERS`]): said, rather than met with a
    /// silence that reads as a wrong address.
    Full,
    /// The host asked us to go: back to the list.
    Kicked,
    /// We came as a bot, and the host is not taking bots. Being asked to
    /// go, with the reason: the host never singled this peer out.
    NoBots,
    /// That beach is running a different build, which answered with the
    /// protocol version it speaks. Greeting it again would only be ignored
    /// again, and a joiner left saying hello forever looks exactly like a
    /// network fault.
    Mismatch(u8),
}

impl PutOut {
    /// Note `why` as a reason this peer was put out, keeping whichever of
    /// it and the reason already heard is the more telling.
    pub fn hear(put_out: &mut Option<PutOut>, why: PutOut) {
        *put_out = (*put_out).max(Some(why));
    }

    /// The line the status bar says it with.
    pub fn feedback(self, tr: &'static crate::app::i18n::Tr) -> String {
        match self {
            PutOut::Mismatch(version) => crate::app::i18n::fill(
                tr.lobby_version_clash,
                &[
                    ("t", &version.to_string()),
                    ("o", &crate::transport::PROTOCOL_VERSION.to_string()),
                ],
            ),
            PutOut::Full => tr.lobby_no_room.to_string(),
            PutOut::Kicked => tr.lobby_kicked_you.to_string(),
            PutOut::NoBots => tr.lobby_no_bots.to_string(),
            PutOut::Closed => tr.lobby_host_closed.to_string(),
        }
    }
}

pub struct OnlineSession {
    pub transport: UdpTransport,
    pub session: Lockstep,
    /// Seats in the match, humans plus AI. The lockstep only carries the
    /// humans, so this is not `session.player_count()`.
    pub seats: u8,
    /// What the lobby agreed the match is: AI seats, map, gulls, round
    /// length, light, team scoring, and the board's seed. Every peer builds
    /// from these, so nothing about the round is a local opinion.
    pub terms: MatchTerms,
    /// The host's handmade beach, compressed, when the round is played on
    /// one. A generated arena travels as a seed in [`Self::terms`]; a
    /// level somebody built has to travel as itself, because no peer but
    /// the host has the file. Empty for the built-in maps.
    pub beach: Vec<u8>,
    /// The peers on the socket, one row each: the chair the launch plan
    /// gave it (`Queued` for one that turned up mid-round, and for every
    /// peer a joiner knows, since a joiner keeps no plan and answers
    /// nobody), what it calls itself, whether it asked to watch, and how
    /// long since it last said anything.
    ///
    /// The silence is the difference between a player who has *gone* and
    /// one who is merely behind: a machine still talking to us has not left
    /// the room, however far its inputs have fallen back. A joiner keeps
    /// the one row it has, the host, and calls the round off when that goes
    /// quiet.
    pub(crate) peers: PeerBook,
    /// This peer joined as a bot connected to this machine (route 1), and
    /// the seat name it greeted with, "Greedy (Ana)": it greets with the
    /// flag that says so and under that name, between rounds and back in
    /// the lobby too. Kept whole rather than read off its chair, since a
    /// bot the full table dealt no chair has none to read it from, and
    /// went home greeting as a person under the player's own name.
    pub bot: Option<String>,
    /// Joiner side: the host asked this peer to leave, and why. Said with
    /// `Kicked` or `NoBots`, which can arrive mid-round or on the results
    /// card as well as in the lobby, and walks the joiner out with the
    /// reason rather than leaving it greeting a host that has forgotten it.
    pub put_out: Option<PutOut>,
    /// Host side, route 2: the bots connected straight to this host, each
    /// with the seat it holds this round and what it is called. The host
    /// commits their inputs as well as its own.
    pub bots_here: Vec<HostedBot>,
    /// What each seat is called, agreed at the handshake so every peer
    /// shows the same table. Empty entries fall back to seat labels; local
    /// couch names never apply to an online round.
    pub names: [String; MAX_PLAYERS],
    /// What holds each seat, agreed with the names: a bot wears the robot
    /// on every screen at the table.
    pub kinds: [crate::sim::SeatKind; MAX_PLAYERS],
    /// The peers' state hashes against our own, and the first frame they
    /// disagreed on, if ever.
    hashes: HashCheck,
    /// Whether the picture has stopped moving, and on whom.
    stall: StallWatch,
    /// Seats given up on this round, each with the frame it was emptied
    /// from, so the shell can put an AI in each and say so once rather
    /// than every frame, and the host can keep telling the table.
    pub abandoned: Vec<(u8, u32)>,
    /// Lines said to the table since the shell last read them, each with
    /// who said it.
    ///
    /// Drained rather than kept: the round's own feed is where a line is
    /// shown, and the feed keeps its own history.
    pub heard: Vec<(String, String)>,
    /// What the people without a chair are doing: the tide vote, the
    /// crowd's size, the calls for the winner.
    pub stands: crate::app::spectators::Stands,
    /// The beach this session came from, and what it owes it.
    pub home: Home,
    /// A next round has been agreed and the session is armed for it; the
    /// shell reads this and walks everyone back into the arena. Cleared by
    /// whoever acts on it.
    pub next_round: bool,
    /// Where the series stands as the next round begins, as the host said
    /// it: the 1-based round number and the wins per seat, both re-dealt to
    /// this round's chairs. The shell folds it into its `Tournament` on the
    /// way into the arena, so a peer admitted mid-series joins the table's
    /// standings rather than starting its own. `None` outside a series.
    pub series_standing: Option<SeriesStanding>,
    /// Ticks of `Resume` still to repeat (see [`pump::RESUME_ECHOES`]).
    resume_echo: u8,
    /// Host: seconds until the next `Ping`, between rounds.
    ping_in: f32,
    /// Ticks played since the round began here, which spaces out the
    /// host's `Start` sent again to a peer not heard from in it yet
    /// (`pump::START_AGAIN`) and its players' clocks, and a watcher's word
    /// on what it holds (`pump::WATCHER_WORD_EVERY`).
    round_ticks: u32,
    /// Joiner: the newest frame the host has committed this round, as far
    /// as its inputs have arrived, read against the host's clock.
    host_newest: Option<u32>,
    /// Joiner: the frames the host last said it was missing, per seat
    /// (`Batch::wants`): this peer's own commits are resent from there.
    host_wants: Option<[u32; MAX_PLAYERS]>,
    /// Joiner: the last clock reading not yet acted on (see
    /// `pump::keep_time`).
    clock_apart: Option<i64>,
    /// How many rounds the host has dealt on this socket, the one being
    /// played included: what a `Start` is numbered with, so a joiner can
    /// tell the next round from any it has already been dealt
    /// ([`Self::is_next_round`]). Counted across matches, not from each
    /// launch: a joiner still on the results card of the last match is
    /// called into the next one by its first `Start`, which has to come
    /// after every round that joiner was dealt.
    pub rounds_dealt: u32,
    /// Who won the last round to finish: the seats its results card
    /// crowned, a bit each by its chairs. Written by the host when the
    /// tide comes in, sent with its call for the next round, and taken
    /// from that call by a joiner, for one walked on before its own board
    /// had finished (see [`Invitation::crowned`]).
    pub crowned: u8,
    /// A round joined late, or owed to someone who came late to it.
    pub catch_up: catch_up::CatchUp,
    /// Lockstep messages dropped for naming another round than the one
    /// played here ([`Self::of_this_round`]), over the session's life: the
    /// last round's still on the wire, or the next one's reaching a peer
    /// still finishing this. Counted for the soak and the log; nothing
    /// reads it to decide anything.
    pub stale_rounds: u32,
    /// Between rounds of a series: on the host, its map page is up; on a
    /// joiner, the host has said so (`NetMsg::Roster::picking`). The
    /// results card says it while the table waits. Cleared as a round
    /// begins.
    pub picking_map: bool,
    /// Host: the seats its partner picks put its bots and the AI in, once
    /// it has picked any ([`order`]); `None` for a table dealt in seat
    /// order. Carried over from the lobby, and back to it.
    pub arranged: Option<order::Arranged>,
}

#[derive(Resource, Default)]
pub struct Online(pub Option<OnlineSession>);

/// Pass `msg` from peer `from` on to every other peer. Star topology: the
/// spokes cannot hear each other, so whatever one says reaches the rest
/// only by the hub repeating it, and inputs, pauses, resumes and chat
/// are all repeated this same way.
pub(crate) fn relay(transport: &UdpTransport, from: usize, msg: NetMsg) {
    for other in 0..transport.peer_count() {
        if other != from {
            transport.send_to(other, msg.clone());
        }
    }
}

/// Drain the session while the results card is up. See
/// [`OnlineSession::poll_between_rounds`] for why this cannot wait for the
/// sim: the sim is exactly what has stopped.
pub fn poll_between_rounds(time: Res<Time>, mut online: ResMut<Online>) {
    if let Some(session) = &mut online.0 {
        session.poll_between_rounds(time.delta_secs());
    }
}

/// Keep the session talking, every fixed tick, while its round is dealt
/// but not yet played: the interlude, the line-up and the count. See
/// [`OnlineSession::listen`]: a peer silent through them was taken for
/// gone, its seat given to the AI before it had played a frame.
pub fn listen_before_the_round(time: Res<Time>, mut online: ResMut<Online>) {
    if let Some(session) = &mut online.0 {
        session.before_the_round(time.delta_secs());
    }
}

pub(crate) mod catch_up;
mod crowd;
mod home;
pub mod order;
mod peers;
mod presence;
mod pump;
mod rounds;
pub use home::{Home, LobbyReturn};
use presence::StallWatch;
pub(crate) use presence::{abandon_the_departed, catch_up_again, leave_a_hostless_round};
#[cfg(test)]
pub(crate) use pump::CATCH_UP_FRAMES;
use pump::HashCheck;
pub use rounds::Invitation;
pub(crate) use rounds::{
    arrange_the_deal, chairs_for_bots, input_delay, lockstep_for, seat_kinds, seat_names,
    seat_the_hosts_bots,
};

impl OnlineSession {
    pub fn new(
        transport: UdpTransport,
        session: Lockstep,
        seats: u8,
        terms: MatchTerms,
    ) -> OnlineSession {
        OnlineSession {
            transport,
            session,
            seats,
            terms,
            beach: Vec::new(),
            peers: PeerBook::default(),
            bot: None,
            put_out: None,
            bots_here: Vec::new(),
            names: Default::default(),
            kinds: Default::default(),
            hashes: HashCheck::default(),
            stall: StallWatch::default(),
            abandoned: Vec::new(),
            heard: Vec::new(),
            stands: Default::default(),
            home: Home::nowhere(),
            next_round: false,
            series_standing: None,
            resume_echo: 0,
            ping_in: 0.0,
            round_ticks: 0,
            host_newest: None,
            host_wants: None,
            clock_apart: None,
            rounds_dealt: 0,
            crowned: 0,
            catch_up: Default::default(),
            stale_rounds: 0,
            picking_map: false,
            arranged: None,
        }
    }

    /// Is this session the star's hub? Seat 0 hosts and relays. Public
    /// because the shell has to know who calls the next round.
    pub fn is_host(&self) -> bool {
        self.session.seat() == Some(0)
    }

    /// Whether this peer watches rather than plays.
    pub fn watching(&self) -> bool {
        self.session.watching()
    }

    /// The round this session plays, as its batches say it
    /// ([`Batch::round`]): the low byte of the deal that began it.
    pub(super) fn round_tag(&self) -> u8 {
        crate::transport::round_tag(self.rounds_dealt)
    }

    /// Whether a lockstep message tagged `round` (an input batch, a hash,
    /// a pause, a resume, a seat given up on) is about the round played
    /// here. Every round counts its frames from zero, so a frame number
    /// cannot tell one round's message from another's; the tag can. One of
    /// another round is dropped, and counted in [`Self::stale_rounds`].
    pub(super) fn of_this_round(&mut self, round: u8) -> bool {
        let ours = round == self.round_tag();
        if !ours {
            self.stale_rounds = self.stale_rounds.saturating_add(1);
        }
        ours
    }

    /// Whether the book holds no plan to go by because none was ever
    /// dealt: the direct `PINCH_HOST`/`PINCH_JOIN` pair's first round,
    /// which never went through a lobby. Its one peer is the player at
    /// the other castle, though the book has it in line.
    ///
    /// Not merely an empty plan: a table formed in the lobby and launched
    /// against the AI with nobody aboard has one too, and so does one
    /// whose every planned peer has been forgotten. There, everybody on
    /// the socket came after the launch and plays nothing this round.
    pub(super) fn keeps_no_plan(&self) -> bool {
        !self.home.from_lobby && self.peers.planned() == 0
    }

    /// Whether `peer` is sent the round's inputs. A joiner sends its own
    /// to the one peer it has, the host, and the direct pair's host to its
    /// one peer. Everyone else goes by the plan
    /// ([`PeerBook::follows_by_plan`]): a lobby table launched against
    /// the AI, or one whose planned peers have all been forgotten, has an
    /// empty plan and everybody on its socket in line.
    pub(super) fn follows_the_round(&self, peer: usize) -> bool {
        !self.is_host() || self.keeps_no_plan() || self.peers.follows_by_plan(peer)
    }

    /// Whether `peer` plays this round, as far as this session can tell.
    /// A joiner hears only the host, which always does; the host goes by
    /// the plan, or takes the direct pair's one peer at its word.
    pub(super) fn plays_this_round(&self, peer: usize) -> bool {
        !self.is_host() || self.peers.seat_of(peer).is_some() || self.keeps_no_plan()
    }

    /// The chairs spoken for at the next deal: the people in the lockstep
    /// plus every peer owed a chair, queued or left without one at the
    /// launch, and the host's own bots only as far as the deal would still
    /// seat them with one more person aboard. What the running beacon
    /// reports as taken.
    ///
    /// Counted the way the lobby's beacon counts them
    /// ([`crate::app::lobby::chairs_taken`]): the next deal seats a person
    /// ahead of a bot (`seat_the_hosts_bots`), so four people and two bots
    /// still have a chair for a fifth person.
    pub(crate) fn players_spoken_for(&self) -> u8 {
        let queued = self
            .peers
            .iter()
            .filter(|peer| peer.wants_a_chair())
            .count();
        let bots = self.bots_here.len();
        let people =
            (self.session.player_count().saturating_sub(bots) + queued).min(MAX_PLAYERS) as u8;
        crate::app::lobby::chairs_taken(people, bots)
    }
}

/// Parse the dev env vars into a ready session, if requested.
/// `PINCH_HOST=47777` or `PINCH_JOIN=192.168.1.10:47777`.
pub fn session_from_env() -> Option<OnlineSession> {
    // The direct hooks skip the lobby, so there is no Start to agree on:
    // both processes must be told the same terms. `PINCH_BOTS=n` seats n AI
    // players behind the two humans and has to be set on both sides.
    let bots: u8 = crate::app::dev::bots().unwrap_or(0);
    // Two humans and the AI behind them; MAX_PLAYERS is the ceiling, and
    // the clamp is on the bots so a wild PINCH_BOTS cannot wrap the sum
    // back under the two humans.
    let humans = 2u8;
    let bots = bots.min(MAX_PLAYERS as u8 - humans);
    let seats = humans + bots;
    let terms = MatchTerms {
        bots,
        ..crate::app::match_setup::terms(
            &crate::app::match_setup::MatchConfig::default(),
            crate::app::teams::TeamMode::Solo,
            0,
        )
    };
    // The name this player goes by online: their P1 name from settings,
    // read straight off disk because the dev hooks run before the app's
    // resources are wired up.
    let own = crate::app::settings::GameSettings::load().0.names[0].clone();
    if let Some(port) = crate::app::dev::direct_host() {
        let port: u16 = port.parse().ok()?;
        let transport = UdpTransport::host(port).ok()?;
        info!("hosting on UDP port {port}, waiting for a peer ({seats} seats)");
        let mut session = OnlineSession::new(
            transport,
            Lockstep::new(0, vec![0, 1], crate::sim::DEFAULT_DELAY),
            seats,
            terms,
        );
        session.names[0] = own;
        return Some(session);
    }
    if let Some(addr) = crate::app::dev::direct_join() {
        let transport = UdpTransport::join(addr.as_str()).ok()?;
        transport.send(NetMsg::hello(&own));
        info!("joining {addr} ({seats} seats)");
        let mut session = OnlineSession::new(
            transport,
            Lockstep::new(1, vec![0, 1], crate::sim::DEFAULT_DELAY),
            seats,
            terms,
        );
        session.names[1] = own;
        return Some(session);
    }
    None
}

#[cfg(test)]
mod spectator_tests {
    use super::*;
    use crate::sim::DEFAULT_DELAY;

    pub(super) fn hosting_session(seed: u64) -> OnlineSession {
        OnlineSession::new(
            UdpTransport::host(0).expect("game socket"),
            Lockstep::new(0, vec![0, 1], DEFAULT_DELAY),
            2,
            MatchTerms {
                seed,
                ..MatchTerms::default()
            },
        )
    }

    /// Who counts as watching this round, which decides both whose vote
    /// the host takes and what number the table is shown.
    ///
    /// Not `Peer::watches`, which is a wish as much as a place: it is true
    /// of somebody in line for the *next* round, who is sent no frames and
    /// sees nothing, and of a seated player that has asked to watch next
    /// time while still playing this one. Counting either had a player in
    /// the audience for its own round, and let a peer with no board vote
    /// on what happened on it.
    #[test]
    fn only_someone_in_the_round_without_a_chair_is_watching_it() {
        let mut session = hosting_session(11);
        // Three peers in the launch plan: one seated, one watching, one
        // seated but asking to watch next round. Then a fourth in line.
        session.peers.row(0).place = Place::Seated(1);
        session.peers.row(1).place = Place::Watching;
        session.peers.row(2).place = Place::Seated(2);
        session.peers.row(2).watch = true;
        session.peers.row(3).place = Place::Queued;
        session.peers.row(3).watch = true;

        assert!(!session.watching_this_round(0), "a player");
        assert!(session.watching_this_round(1), "a watcher");
        assert!(
            !session.watching_this_round(2),
            "still playing, however it means to spend the next round"
        );
        assert!(
            !session.watching_this_round(3),
            "in line, sent no frames, watching nothing"
        );
        assert_eq!(session.watchers_in_round(), 1, "one of the four");
    }

    /// A pick is counted only from someone watching this round, and only
    /// by the host, which is the only peer that counts anything.
    #[test]
    fn a_call_for_the_winner_is_taken_from_a_watcher_while_the_calls_are_open() {
        use crate::sim::InputMsg;
        let mut session = hosting_session(5);
        session.peers.row(0).place = Place::Seated(1);
        session.peers.row(1).place = Place::Watching;
        session.peers.row(2).place = Place::LateWatching;
        session.peers.row(3).place = Place::Queued;
        session.take_pick(true, 0, 0);
        session.take_pick(true, 1, 1);
        session.take_pick(true, 2, 1);
        session.take_pick(true, 3, 0);
        session.take_pick(true, 1, 9);
        let picks = session.crowd_picks_now();
        assert_eq!(
            picks.counts,
            [0, 2, 0, 0, 0, 0],
            "two watchers; the player and the queue unheard"
        );
        assert!(picks.open > 0);
        // A spectator may change its mind, and a spoke counts nothing.
        session.take_pick(true, 1, 0);
        session.take_pick(false, 2, 0);
        assert_eq!(session.crowd_picks_now().counts, [1, 1, 0, 0, 0, 0]);

        // Past the first half minute the calls are in.
        let close = crate::app::spectators::PICKS_OPEN_FOR;
        for frame in 0..close {
            session.session.commit_local(PlayerAction::None);
            session.session.receive(InputMsg {
                player: 1,
                frame: DEFAULT_DELAY + frame,
                action: PlayerAction::None,
            });
            while session.session.advance().is_some() {}
        }
        assert!(session.session.frame() >= close);
        assert_eq!(session.crowd_picks_now().open, 0);
        session.take_pick(true, 1, 1);
        assert_eq!(
            session.crowd_picks_now().counts,
            [1, 1, 0, 0, 0, 0],
            "a call after the close is not taken"
        );
    }

    #[test]
    fn a_vote_is_taken_only_from_someone_watching() {
        let sand = crate::sim::TideEvent::FreshSand.index() as u8;
        let open = |session: &OnlineSession| session.stands.tide.votes.open().is_some();

        // Seated: a player may not call the tide down on its own table.
        let mut session = hosting_session(1);
        session.peers.row(0).place = Place::Seated(1);
        session.take_vote(true, 0, sand);
        assert!(!open(&session), "a player at the table");

        // In line for the next round: sent no frames, sees no board.
        let mut session = hosting_session(2);
        session.peers.row(0).place = Place::Queued;
        session.take_vote(true, 0, sand);
        assert!(!open(&session), "a peer in the queue");

        // Watching: heard.
        let mut session = hosting_session(3);
        session.peers.row(0).place = Place::Watching;
        session.take_vote(true, 0, sand);
        assert!(open(&session), "a spectator");

        // And a spoke counts nothing, whoever sent it: only the hub tallies.
        let mut session = hosting_session(4);
        session.peers.row(0).place = Place::Watching;
        session.take_vote(false, 0, sand);
        assert!(!open(&session), "not the host");
    }

    /// One watcher, one vote. The card can be reopened and pressed again
    /// inside the window, and every press used to count: one keen watcher
    /// outvoted a room. Now the latest press is the watcher changing its
    /// mind.
    #[test]
    fn a_watcher_pressing_again_changes_its_vote_rather_than_adding_one() {
        use crate::sim::TideEvent;
        let mut session = hosting_session(6);
        session.peers.row(0).place = Place::Watching;
        session.peers.row(1).place = Place::Watching;
        let (sand, swap, mania) = (
            TideEvent::FreshSand.index() as u8,
            TideEvent::CastleSwap.index() as u8,
            TideEvent::CrabMania.index() as u8,
        );
        // Peer 0 stuffs the box for a swap; peer 1 wants fresh sand.
        for _ in 0..5 {
            session.take_vote(true, 0, swap);
        }
        session.take_vote(true, 1, sand);
        // One each, a tie, which goes to the earlier event on the list.
        assert_eq!(
            session.stands.tide.votes.settle(10.0),
            Some(TideEvent::FreshSand),
            "five presses are one vote"
        );

        // And a vote moves with its voter when a peer before it goes.
        let mut session = hosting_session(7);
        for peer in 0..3 {
            session.peers.row(peer).place = Place::Watching;
        }
        session.take_vote(true, 0, mania);
        session.take_vote(true, 1, sand);
        session.take_vote(true, 2, sand);
        session.forget_peer(0);
        // Old peer 2 is now peer 1, and changes its mind: still two votes
        // in all, not three.
        session.take_vote(true, 1, mania);
        assert_eq!(
            session.stands.tide.votes.settle(10.0),
            Some(TideEvent::CrabMania)
        );
    }

    /// A direct `PINCH_HOST` pair keeps no launch plan, and
    /// `follows_the_round` lets it send to its one peer all the same, so
    /// the two keep talking to the one peer they have. Spectating is the place
    /// a peer was dealt, not something derived from that: read the other
    /// way, the host had its opponent down as a spectator, counted in the
    /// audience and allowed to vote on the game it was playing.
    #[test]
    fn a_direct_pair_has_no_spectators_in_it() {
        let mut session = hosting_session(5);
        // No plan was ever dealt, so the one peer keeps the default place.
        session.peers.reach(1);
        assert_eq!(session.peers.planned(), 0, "no plan at all");
        assert!(
            session.follows_the_round(0),
            "and it is sent the round regardless, which is the point"
        );

        assert!(!session.watching_this_round(0), "it is the other player");
        assert_eq!(session.watchers_in_round(), 0, "an audience of nobody");

        session.take_vote(true, 0, crate::sim::TideEvent::FreshSand.index() as u8);
        assert!(
            session.stands.tide.votes.open().is_none(),
            "and it cannot call the tide onto the game it is playing"
        );
    }

    /// A spectator that walks away is forgotten, which nothing used to do:
    /// the round gives up only on *seats*, through `awaiting`, and a
    /// spectator is awaited by nobody. Left on the socket it was fed the
    /// round for the rest of it and counted in the audience on screen.
    #[test]
    fn a_spectator_that_goes_quiet_is_forgotten_and_the_rest_are_left_alone() {
        let mut session = hosting_session(6);
        session.peers.row(0).place = Place::Seated(1);
        session.peers.row(1).place = Place::Watching;
        session.peers.row(2).place = Place::Watching;
        session.peers.row(3).place = Place::Queued;
        // Everyone quiet a long while, and one of the watchers talking.
        for peer in 0..4 {
            session.peers.row(peer).silence = 60.0;
        }
        session.peers.row(1).silence = 0.0;
        let before = session.peers.len();

        session.forget_gone_bystanders();

        assert_eq!(session.peers.len(), before - 1, "one of the four went");
        assert_eq!(
            session.peers.get(0).map(|p| p.place),
            Some(Place::Seated(1)),
            "the seat is the round's own business, not this sweep's"
        );
        assert_eq!(
            session.peers.get(1).map(|p| p.place),
            Some(Place::Watching),
            "the watcher that is still talking stays"
        );
        assert_eq!(
            session.peers.get(2).map(|p| p.place),
            Some(Place::Queued),
            "and the hand-wired pair's player is the round's own business"
        );

        // At a table formed in the lobby, somebody in line who has gone
        // quiet goes too: it was counted as a chair taken all round.
        session.home.from_lobby = true;
        session.forget_gone_bystanders();
        assert_eq!(session.peers.len(), before - 2, "the one in line went");
        assert!(
            session.peers.iter().all(|p| p.place != Place::Queued),
            "and nobody is left in line"
        );
    }

    /// An empty name is the beach's own voice here: it is what announces
    /// a called event. So a peer that has a name may not drop it and speak
    /// as the room, and the lobby has refused that for as long as it has
    /// had chat. The round took the wire's word for it.
    ///
    /// Host side only, though. A spoke takes the vetted line as it stands,
    /// or it would stamp the host's name onto the one line that is meant
    /// to carry none.
    #[test]
    fn a_named_peer_cannot_speak_as_the_beach_itself() {
        let mut session = hosting_session(7);
        session.peers.row(0).name = "Cy".into();
        let forged = crate::transport::wire_chat("Anna has left the beach");

        let said = session.take_chat(true, 0, crate::transport::wire_name(""), forged);
        assert_eq!(
            said,
            Some(("Cy".to_string(), "Anna has left the beach".to_string())),
            "the host gives a named peer its own name back"
        );

        // A peer it knows nothing about keeps whatever it claimed. There
        // is one left: a greeting the host never received, which is a peer
        // it is about to learn the name of anyway.
        let stranger = session.take_chat(true, 1, crate::transport::wire_name("Dee"), forged);
        assert_eq!(stranger.map(|(who, _)| who), Some("Dee".to_string()));

        // But one that claims nothing and is known as nothing is refused,
        // rather than repeated to the table as the beach talking. Found by
        // running it: a watcher with no name set said a line that came out
        // looking exactly like the notice a called event makes.
        let nameless = session.take_chat(true, 2, crate::transport::wire_name(""), forged);
        assert_eq!(nameless, None, "nobody speaks as the room");

        // And a spoke repeats what the hub handed it, untouched.
        let spoke = session.take_chat(false, 0, crate::transport::wire_name(""), forged);
        assert_eq!(
            spoke.map(|(who, _)| who),
            Some(String::new()),
            "the beach's own voice reaches a joiner nameless"
        );
    }

    /// A spectator is vetted like anybody else, which it could not be
    /// while its greeting carried no name.
    ///
    /// Found by watching a real one: `Watch` was the one greeting with
    /// nothing in it, so the host had no name to check a spectator's chat
    /// against and took the line's own word for who said it. That is the
    /// whole of what the check exists to stop, and it was open to exactly
    /// the peers nobody at the table can see.
    #[test]
    fn a_spectator_cannot_speak_under_a_players_name() {
        let mut session = hosting_session(7);
        // As the host writes it down from the greeting, watcher or not.
        session.remember_peer_name(0, "Dee");
        let forged = crate::transport::wire_chat("I fold, take my castle");

        let said = session.take_chat(true, 0, crate::transport::wire_name("Bo"), forged);
        assert_eq!(
            said,
            Some(("Dee".to_string(), "I fold, take my castle".to_string())),
            "the crowd speaks under the name it turned up with"
        );
    }
}

#[cfg(test)]
mod table_tests {
    use super::*;
    use crate::sim::DEFAULT_DELAY;

    fn session(local: Option<u8>, port: u16) -> OnlineSession {
        let transport = match local {
            Some(0) => UdpTransport::host(0).expect("host socket"),
            _ => UdpTransport::join(("127.0.0.1", port)).expect("join"),
        };
        OnlineSession::new(
            transport,
            match local {
                Some(seat) => Lockstep::new(seat, vec![0, 1], DEFAULT_DELAY),
                None => Lockstep::observer(vec![0, 1], DEFAULT_DELAY),
            },
            2,
            MatchTerms::default(),
        )
    }

    /// The running beacon says how many chairs are spoken for: the humans
    /// in the lockstep and everyone in line who did not ask to watch.
    #[test]
    fn the_beacon_counts_the_queue_as_taken() {
        let mut host = session(Some(0), 0);
        assert_eq!(host.players_spoken_for(), 2, "the two at the table");
        host.peers.row(0).name = "Bo".into();
        assert_eq!(host.players_spoken_for(), 3, "one in line for a chair");
        host.peers.row(1).watch = true;
        assert_eq!(host.players_spoken_for(), 3, "a watcher wants no chair");
        for peer in 2..8 {
            host.peers.row(peer).name = "Cy".into();
        }
        assert_eq!(
            host.players_spoken_for(),
            MAX_PLAYERS as u8,
            "and never more chairs than the table has"
        );
    }

    /// The host's own bots give way to a person at the next deal, so the
    /// running beacon counts them as the lobby's does: four people and two
    /// door bots leave a chair for a fifth person.
    #[test]
    fn the_running_beacon_counts_the_hosts_bots_as_giving_way() {
        let mut host = OnlineSession::new(
            UdpTransport::host(0).expect("host socket"),
            Lockstep::new(0, (0..6).collect(), DEFAULT_DELAY),
            6,
            MatchTerms::default(),
        );
        for peer in 0..3 {
            host.peers.row(peer).place = Place::Seated(peer as u8 + 1);
        }
        for seat in [4, 5] {
            host.bots_here.push(HostedBot {
                seat,
                id: usize::from(seat),
                name: "Bot".into(),
            });
        }
        assert_eq!(
            host.players_spoken_for(),
            crate::app::lobby::chairs_taken(4, 2),
            "the lobby's count"
        );
        assert!(
            host.players_spoken_for() < MAX_PLAYERS as u8,
            "a fifth person is still seated ahead of a bot"
        );
    }

    /// A joiner reads its own seat in the host's abandonment notice: that
    /// is how it learns it was dropped, rather than waiting out the host
    /// and being told the host had left. Somebody else's seat, or the
    /// host's own view, says nothing of the kind.
    #[test]
    fn a_seat_told_of_its_own_abandonment_knows_it_was_dropped() {
        let host = session(Some(0), 0);
        let port = host.transport.local_addr().expect("addr").port();
        let mut joiner = session(Some(1), port);
        assert!(!joiner.dropped(), "nothing said yet");
        joiner.abandoned.push((0, 30));
        assert!(!joiner.dropped(), "another seat's abandonment is theirs");
        joiner.abandoned.push((1, 30));
        assert!(joiner.dropped(), "its own is the word it was waiting for");
        let mut host = host;
        host.abandoned.push((0, 30));
        assert!(!host.dropped(), "the host drops nobody it is");
        let mut watcher = session(None, port);
        watcher.abandoned.push((1, 30));
        assert!(
            !watcher.dropped(),
            "a spectator holds no seat to be dropped from"
        );
    }
}