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
860
861
862
863
864
865
866
//! Best-of-three and best-of-five tournaments: a local series of versus
//! rounds on rotating maps.
//! Round wins accumulate here; the interlude screen bridges the rounds and
//! the results card grows a series block (and a champion headline once the
//! series is decided).

use crate::app::i18n::fill;
use crate::app::match_setup::TermsDials;
use crate::app::menu_ui;
use crate::app::palette;
use crate::app::seating::leading_seats;
use crate::app::settings::GameSettings;
use crate::app::teams::TeamMode;
use crate::app::{Screen, Seats, Sim};
use crate::sim::MAX_PLAYERS;
use bevy::prelude::*;

/// How long a series runs: the three positions of the match screen's mode
/// dial.
///
/// One dial rather than a flag and a length: a match is one round, three or
/// five, and everything that follows is arithmetic on
/// [`SeriesLength::rounds`].
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum SeriesLength {
    #[default]
    Single,
    BestOfThree,
    BestOfFive,
}

impl SeriesLength {
    pub const ALL: [SeriesLength; 3] = [
        SeriesLength::Single,
        SeriesLength::BestOfThree,
        SeriesLength::BestOfFive,
    ];

    /// Whether a series is being played at all. A single round is on the
    /// same dial because that is how the screen offers it, but it starts no
    /// tournament and shows no standings.
    pub fn is_series(self) -> bool {
        self != SeriesLength::Single
    }

    /// Rounds in a full series: the most that will be played.
    pub fn rounds(self) -> u8 {
        match self {
            SeriesLength::Single => 1,
            SeriesLength::BestOfThree => 3,
            SeriesLength::BestOfFive => 5,
        }
    }

    /// Rounds that take it, ending the series early: a majority, which is
    /// what "best of" means. Derived rather than written down twice, so a
    /// length added to the dial cannot disagree with itself.
    pub fn target(self) -> u8 {
        self.rounds() / 2 + 1
    }
}

/// Where a series stands, if there is one.
///
/// One value rather than `active` and `finished` flags: four readers each
/// re-derived "running" as `active && !finished`, and a pair of flags
/// admits a fourth state nothing means.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum SeriesState {
    /// A single round, or no match at all: nothing to tally.
    #[default]
    Off,
    /// Rounds still to play.
    Running,
    /// Decided; the next Enter leaves for the menu.
    Decided,
}

#[derive(Resource, Default)]
pub struct Tournament {
    pub state: SeriesState,
    /// 1-based current round.
    pub round: u8,
    pub wins: [u8; MAX_PLAYERS],
    /// How long this one runs. Read only while `state` is not `Off`: a table that is
    /// not in a series has no length to speak of, and the default sits at
    /// [`SeriesLength::Single`] to say so.
    pub length: SeriesLength,
}

/// Who a series belongs to. Rounds are awarded per *seat*, because that is
/// how the wins are stored, but a team series is won by the team: both its
/// members hold the same tally, so asking which seat leads sees a tie and
/// answers nobody. The card needs to know which question was asked.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Champion {
    Seat(u8),
    Team(u8),
}

impl Champion {
    /// Whether `seat` is one of the winners: itself, or a member of the
    /// winning team.
    pub fn claims(self, seat: u8, mode: TeamMode) -> bool {
        match self {
            Champion::Seat(s) => s == seat,
            Champion::Team(t) => mode.team_of(seat) == t,
        }
    }
}

impl Tournament {
    pub fn start(length: SeriesLength) -> Self {
        Self::taken_up(length, 1, [0; MAX_PLAYERS])
    }

    /// The tournament a peer arms from the host's invitation: the series
    /// length the terms carry, at the round and tally the wire says. The
    /// host and every joiner run this same function, so a peer admitted
    /// mid-series takes up the standing rather than starting its own.
    pub fn taken_up(length: SeriesLength, round: u8, wins: [u8; MAX_PLAYERS]) -> Self {
        match length.is_series() {
            true => Tournament {
                state: SeriesState::Running,
                round: round.max(1),
                wins,
                length,
            },
            false => Tournament::default(),
        }
    }

    /// [`Tournament::taken_up`] read straight off the wire: the terms say
    /// whether there is a series, and the standing says where it is. A
    /// series with no standing (the host's stale re-answer to a greeting,
    /// before the first round has been called) opens at round one.
    pub fn from_terms(
        terms: crate::transport::MatchTerms,
        standing: Option<crate::transport::SeriesStanding>,
    ) -> Self {
        let crate::transport::SeriesStanding { round, wins } =
            standing.unwrap_or_else(crate::transport::SeriesStanding::opening);
        Self::taken_up(terms.series(), round, wins)
    }

    /// Where this series stands, in the form the wire carries it, or
    /// `None` when there is no series to speak of.
    pub fn standing(&self) -> Option<crate::transport::SeriesStanding> {
        self.in_series()
            .then_some(crate::transport::SeriesStanding {
                round: self.round,
                wins: self.wins,
            })
    }

    /// Whether a series is on at all, running or decided: the results card
    /// shows the standings either way.
    pub fn in_series(&self) -> bool {
        self.state != SeriesState::Off
    }

    /// Whether there are rounds still to play.
    pub fn is_running(&self) -> bool {
        self.state == SeriesState::Running
    }

    /// Whether the series has been decided.
    pub fn is_decided(&self) -> bool {
        self.state == SeriesState::Decided
    }

    /// Whether the tally settles the series: the one winner a tally can
    /// name ([`Tournament::winner`]) has a majority of the rounds, or the
    /// last round has been played.
    ///
    /// The winner and not merely the most wins, so a lead two seats share
    /// is never read as a majority. A tied round goes to nobody
    /// ([`leading_seats`] names no leader in a tie), so a series can reach
    /// its last round with the tally still level: that is decided by the
    /// round count alone, with [`Tournament::winner`] naming no one.
    fn tally_decides(&self, mode: TeamMode, seats: u8) -> bool {
        let best = match self.winner(mode, seats) {
            None => 0,
            Some(Champion::Seat(seat)) => self.wins[usize::from(seat)],
            // Every member holds the team's tally.
            Some(Champion::Team(team)) => mode
                .seats_of(team, seats)
                .first()
                .map_or(0, |&seat| self.wins[usize::from(seat)]),
        };
        best >= self.length.target() || self.round >= self.length.rounds()
    }

    /// The unique holder of the most round wins, if there is one. Only
    /// meaningful free-for-all; [`Tournament::winner`] is the one to ask.
    fn champion(&self) -> Option<u8> {
        crate::app::seating::unique_max(&self.wins).map(|s| s as u8)
    }

    /// Who took the series, under the mode it was played in. In team play
    /// the tally is read one seat per team (every member is awarded the
    /// same round) so the comparison is between teams and a shared tally
    /// is a win, not a tie.
    pub fn winner(&self, mode: TeamMode, seats: u8) -> Option<Champion> {
        if mode == TeamMode::Solo {
            return self.champion().map(Champion::Seat);
        }
        let tallies: Vec<u8> = (0..mode.teams(seats))
            .map(|team| {
                mode.seats_of(team, seats)
                    .first()
                    .map_or(0, |&seat| self.wins[usize::from(seat)])
            })
            .collect();
        crate::app::seating::unique_max(&tallies).map(|team| Champion::Team(team as u8))
    }
}

/// Award the finished round to its unique leader (or, in team play, to
/// every seat on the leading team) and decide the series. Runs before the results card spawns.
pub fn record_series_round(
    sim: Res<Sim>,
    seats: Res<Seats>,
    scoring: crate::app::teams::Scoring,
    mut tournament: ResMut<Tournament>,
) {
    if !tournament.is_running() {
        return;
    }
    // Every peer counts the round it just watched, so its results card is
    // right even for the final round, which is followed by no invitation.
    // Online, the host's next invitation carries the authoritative wins
    // moved onto the re-dealt seats and `enter_interlude` overwrites this
    // with them, so a mid-series seat change corrects itself.
    let mode = scoring.live_mode(seats.0);
    let leaders = leading_seats(sim.0.scores(), seats.0, mode);
    for (seat, led) in leaders.iter().enumerate() {
        if *led {
            tournament.wins[seat] += 1;
        }
    }
    if tournament.tally_decides(mode, seats.0) {
        tournament.state = SeriesState::Decided;
    }
}

/// One contender's line in the series tally.
pub struct Standing {
    pub who: String,
    /// A star per round won.
    pub stars: String,
    pub color: Color,
}

impl Standing {
    /// Name and stars as one line, for a tally written inline.
    pub fn line(&self) -> String {
        format!("{}  {}", self.who, self.stars)
    }
}

/// The series tally, one row per contender: who, and a star per round won.
/// Solo rows are seats; team rows are teams, because a pair holding two
/// rounds between them has won two, not four.
pub fn standings(
    settings: &GameSettings,
    names: &crate::app::SeatNames,
    tournament: &Tournament,
    mode: TeamMode,
    seats: u8,
) -> Vec<Standing> {
    (0..mode.teams(seats))
        .map(|team| {
            let face = crate::app::teams::face_of(mode, team, seats);
            let wins = tournament.wins[usize::from(face)];
            let who = if mode == TeamMode::Solo {
                names.label(settings.tr(), face)
            } else {
                crate::app::teams::label(settings, names, mode, team, seats)
            };
            Standing {
                who,
                stars: "*".repeat(usize::from(wins)),
                color: palette::seat_text(face),
            }
        })
        .collect()
}

/// "Round 2 of 3": where the series has got to, over how long it runs.
///
/// One function for the interlude and the results card, which draw the
/// same line two screens apart. The length used to be spelled into the
/// translated string itself, so every series counted its rounds out of
/// five however long it actually was.
pub fn round_line(tr: &crate::app::i18n::Tr, tournament: &Tournament) -> String {
    fill(
        tr.tour_round,
        &[
            ("n", &tournament.round.to_string()),
            ("b", &tournament.length.rounds().to_string()),
        ],
    )
}

/// The champion's name for the headline, and the seat whose colour it wears.
pub fn champion_name(
    settings: &GameSettings,
    names: &crate::app::SeatNames,
    mode: TeamMode,
    champion: Champion,
    seats: u8,
) -> (String, u8) {
    match champion {
        Champion::Seat(seat) => (names.label(settings.tr(), seat), seat),
        Champion::Team(team) => (
            crate::app::teams::label(settings, names, mode, team, seats),
            crate::app::teams::face_of(mode, team, seats),
        ),
    }
}

/// Marker for the between-rounds interlude card.
#[derive(Component)]
pub struct InterludeUi;

/// How long the interlude stands between two rounds of a series.
pub const INTERLUDE_SECS: f32 = 2.4;

/// Auto-advance clock on the interlude card.
#[derive(Component)]
pub struct InterludeTimer(pub Timer);

/// Entering the interlude advances the series bookkeeping (next round,
/// rotated map, config re-armed) and shows the standings for a beat.
pub fn enter_interlude(
    mut commands: Commands,
    local: crate::app::teams::LocalScoring,
    names: Res<crate::app::SeatNames>,
    seats: Res<Seats>,
    mut online: ResMut<crate::app::net::Online>,
    dials: crate::app::match_setup::Dials,
    mut tournament: ResMut<Tournament>,
) {
    let crate::app::match_setup::Dials {
        mut config,
        beaches,
    } = dials;
    // Online the standings are drawn on the table the host has just dealt
    // the next round, which the tally below has been moved onto: the
    // finished round's seats and names, still in `Seats` and `SeatNames`
    // until the next board is built, put a newcomer's nought under the old
    // AI's name, and left the top AI's wins off the card.
    let (names, seats) = match &online.0 {
        Some(session) => (crate::app::SeatNames(session.names.clone()), session.seats),
        None => (crate::app::SeatNames(names.0.clone()), seats.0),
    };
    // The pure rule rather than `Scoring`, which reads the session this
    // system writes; a series is never a replay's.
    let mode = crate::app::teams::in_play(local.mode(), &online, None, seats.max(2));
    let settings = &local.settings;
    // The session is through the doorway; the flag has done its work of
    // carrying it past `end_versus`. Online, the map and the seed are the
    // host's to say and arrive in the terms; the config steps below are
    // for a local series, and `load_versus` ignores them for an online one.
    //
    // The round number and the tally are the host's word online: it
    // re-deals them to the next round's seats and sends them out, so both
    // are adopted here rather than counted locally, which would advance the
    // round twice.
    //
    // And the whole series is taken from the invitation, length and state
    // with the round and the tally, as walking in from the lobby does: the
    // `Start` that brought this peer here may open a *new* match rather
    // than continue this one. A joiner still reading the scores of a
    // single round when the host went back to the lobby and launched a
    // best of three was pulled straight into it, and kept "no series":
    // no standings, and an Enter that left mid-series. The other way
    // round it kept the old standings over a single round. For the next
    // round of the same series this is the adoption it always was.
    //
    // Read, not taken: the session keeps the standing for the whole round,
    // because the host's `start_msg` packs it into every invitation it
    // re-answers and every round it hands a watcher, and one caught up
    // with `None` began its tally at round one with nobody on a win. A
    // single round is never left with an old series' standing: every way
    // into a round writes it afresh (`call_next_round`, `take_up`, the
    // lobby launch).
    match &mut online.0 {
        Some(session) => {
            session.next_round = false;
            *tournament = Tournament::from_terms(session.terms, session.series_standing);
        }
        None => tournament.round += 1,
    }
    // A round walked into part way through, as a watcher whose `Start`
    // went astray on the results card: the host's frames run on while the
    // card shows, and the resend tails reach about a second back, so the
    // beat is skipped. The standings are on the scoreboard all the same.
    let beat = match online
        .0
        .as_ref()
        .is_some_and(|session| session.catch_up.board.is_some())
    {
        true => 0.0,
        false => INTERLUDE_SECS,
    };
    // The next map: drawn again under step 2's Random card, else the
    // dial's own step, with the dial's own guards: past the shelf when
    // nothing on it seats the table, past the four-castle beaches when
    // five or six are sitting. A local series only: online the host's
    // invitation names the map, and this config is the player's own dials,
    // which the next beach they host reads its terms from. Stepped here,
    // a best of five left that dial four maps on from where they set it.
    if online.0.is_none() {
        crate::app::match_setup::map_for_next_round(
            &mut config,
            &beaches,
            crate::app::clock::fresh_seed(),
        );
        // Its own seed: the one step 2 previewed was the first round's.
        config.seed = None;
        config.armed = true;
    }
    let tr = settings.tr();
    // A breather on the beach, not a blackout: the postcard stands behind
    // and the tally rides the same tide-dressed card as every other screen.
    commands
        .spawn((
            InterludeUi,
            InterludeTimer(Timer::from_seconds(beat, TimerMode::Once)),
            Node {
                flex_direction: FlexDirection::Column,
                row_gap: Val::Px(12.0),
                ..menu_ui::centred_overlay()
            },
        ))
        .with_children(|overlay| {
            overlay.spawn(menu_ui::screen_card()).with_children(|card| {
                card.spawn((
                    Text::new(round_line(tr, &tournament)),
                    menu_ui::display_font(menu_ui::type_scale::DISPLAY),
                    TextColor(palette::GOLD),
                ));
                // A table, names in one column and stars in the next, so
                // every name starts at one edge and every tally at another.
                // Centred line by line, names of different lengths each
                // started somewhere else and their stars with them.
                card.spawn(Node {
                    display: Display::Grid,
                    grid_template_columns: RepeatedGridTrack::auto(2),
                    column_gap: Val::Px(14.0),
                    justify_items: JustifyItems::Start,
                    ..default()
                })
                .with_children(|table| {
                    let standings = standings(settings, &names, &tournament, mode, seats.max(2));
                    for Standing { who, stars, color } in standings {
                        for cell in [who, stars] {
                            table.spawn((
                                Text::new(cell),
                                TextFont {
                                    font_size: FontSize::Px(menu_ui::type_scale::HEADING),
                                    ..default()
                                },
                                TextLayout::no_wrap(),
                                TextColor(color),
                            ));
                        }
                    }
                });
            });
        });
}

/// The interlude rolls into the next round on its own (or on Enter).
pub fn interlude_tick(
    time: Res<Time>,
    keys: Res<ButtonInput<KeyCode>>,
    mut timers: Query<&mut InterludeTimer>,
    mut next_screen: ResMut<NextState<Screen>>,
) {
    for mut timer in &mut timers {
        timer.0.tick(time.delta());
        if timer.0.is_finished() || menu_ui::enter(&keys) {
            next_screen.set(Screen::Versus);
        }
    }
}

/// Back at the menu, any running series is abandoned.
pub fn reset_on_menu(mut tournament: ResMut<Tournament>) {
    *tournament = Tournament::default();
}

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

    /// The round line counts out of the series actually being played. The
    /// length lived inside the translated string for a while, so a
    /// best-of-three read "Round 1 of 5" and then stopped at three.
    #[test]
    fn the_round_line_counts_out_of_this_series_not_the_longest_one() {
        use crate::app::i18n::ALL_LANGS;

        for (length, rounds) in [
            (SeriesLength::BestOfThree, "3"),
            (SeriesLength::BestOfFive, "5"),
        ] {
            let mut t = Tournament::start(length);
            t.round = 2;
            let line = round_line(&crate::app::i18n::EN, &t);
            assert!(line.contains(rounds), "{length:?}: {line}");
            assert!(line.contains('2'), "{length:?}: {line}");
        }

        // And in every language: a total spelled into the string itself
        // rather than left as a placeholder is the bug, so the check is
        // that no translation still carries a bare five.
        let mut t = Tournament::start(SeriesLength::BestOfThree);
        t.round = 1;
        for lang in ALL_LANGS {
            let line = round_line(lang.tr(), &t);
            assert!(
                !line.contains('5'),
                "{lang:?} still counts out of five: {line}"
            );
            assert!(
                line.contains('3'),
                "{lang:?} does not say how long it is: {line}"
            );
        }
    }

    /// Both members of the leading pair hold the same tally, so a per-seat
    /// search sees a tie and only the team search finds the winner.
    #[test]
    fn a_team_series_is_won_by_the_team() {
        let mut t = Tournament::start(SeriesLength::BestOfFive);
        // Two rounds to the pair {0,1}, one to the pair {2,3}.
        t.wins = [2, 2, 1, 1, 0, 0];
        assert_eq!(t.champion(), None, "the seats are tied, and always will be");
        assert_eq!(t.winner(TeamMode::Pairs, 4), Some(Champion::Team(0)));
        assert_eq!(t.winner(TeamMode::Solo, 4), None);
        // A drawn series still crowns nobody.
        t.wins = [2, 2, 2, 2, 0, 0];
        assert_eq!(t.winner(TeamMode::Pairs, 4), None);
        // Trios read the interleaved halves, not the blocks.
        t.wins = [1, 3, 1, 3, 1, 3];
        assert_eq!(t.winner(TeamMode::Trios, 6), Some(Champion::Team(1)));
    }

    /// The series bookkeeping itself, which nothing exercised: a round goes
    /// to its leader, three of them end the series early, and a team round
    /// is awarded to every seat on the winning team.
    #[test]
    fn three_rounds_take_the_series() {
        use crate::sim::classic_arena;

        let mut app = App::new();
        app.insert_resource(Sim(classic_arena(false, 4)));
        app.insert_resource(Seats(4));
        app.insert_resource(GameSettings::default());
        app.init_resource::<crate::app::Daily>();
        app.init_resource::<crate::app::net::Online>();
        app.init_resource::<crate::app::Playback>();
        app.insert_resource(Tournament::start(SeriesLength::BestOfFive));
        app.add_systems(Update, record_series_round);

        // Seat 1 banks the most, three rounds running.
        {
            let mut sim = app.world_mut().resource_mut::<Sim>();
            for (seat, score) in [(0, 0), (1, 9), (2, 3), (3, 1)] {
                sim.0.set_score(seat, score);
            }
        }
        for round in 1..=3u8 {
            app.world_mut().resource_mut::<Tournament>().round = round;
            app.update();
        }
        let tour = app.world().resource::<Tournament>();
        assert_eq!(tour.wins, [0, 3, 0, 0, 0, 0]);
        assert!(
            tour.is_decided(),
            "first to three ends it before round five"
        );
        assert_eq!(tour.winner(TeamMode::Solo, 4), Some(Champion::Seat(1)));

        // A finished series stops counting, however many more rounds run.
        app.update();
        assert_eq!(app.world().resource::<Tournament>().wins[1], 3);

        // In pairs the round goes to both members of the leading pair.
        app.insert_resource(Tournament::start(SeriesLength::BestOfFive));
        app.world_mut().resource_mut::<GameSettings>().team_mode = TeamMode::Pairs;
        app.update();
        assert_eq!(
            app.world().resource::<Tournament>().wins,
            [1, 1, 0, 0, 0, 0],
            "the pair map is {{0,1}} {{2,3}}: seat 1's nine takes the round for \
             seat 0 too, who banked nothing"
        );
    }

    /// The two lengths are one dial and one piece of arithmetic: a best of
    /// n is taken by a majority of n, and a single round is neither.
    #[test]
    fn best_of_n_is_taken_by_a_majority_of_n() {
        assert_eq!(SeriesLength::BestOfThree.rounds(), 3);
        assert_eq!(SeriesLength::BestOfThree.target(), 2, "two of three");
        assert_eq!(SeriesLength::BestOfFive.rounds(), 5);
        assert_eq!(SeriesLength::BestOfFive.target(), 3, "three of five");
        assert!(!SeriesLength::Single.is_series());
        assert!(SeriesLength::BestOfThree.is_series());
        assert!(SeriesLength::BestOfFive.is_series());
    }

    /// A short series is over a round sooner than a long one, on the same
    /// tally. The long series ran through `three_rounds_take_the_series`
    /// above; this is the one the new dial position adds.
    #[test]
    fn two_rounds_take_a_best_of_three() {
        let decided = |length: SeriesLength, wins: [u8; MAX_PLAYERS], round: u8| {
            let mut t = Tournament::start(length);
            t.wins = wins;
            t.round = round;
            t.tally_decides(TeamMode::Solo, 4)
        };
        assert!(
            decided(SeriesLength::BestOfThree, [2, 0, 0, 0, 0, 0], 2),
            "two rounds take a best of three"
        );
        assert!(
            !decided(SeriesLength::BestOfFive, [2, 0, 0, 0, 0, 0], 2),
            "and leave a best of five still running"
        );
        // A tally that never reaches the target still ends at the last round.
        assert!(
            decided(SeriesLength::BestOfThree, [1, 1, 1, 0, 0, 0], 3),
            "the third round ends it however it stands"
        );
        // Two tied rounds give both leaders two, and nobody the series: the
        // third round is still to play.
        assert!(
            !decided(SeriesLength::BestOfThree, [2, 2, 0, 0, 0, 0], 2),
            "a shared majority decides nothing"
        );
        assert!(decided(SeriesLength::BestOfThree, [3, 2, 0, 0, 0, 0], 3));
    }

    /// A team series is decided by the team's tally, which every member
    /// holds: the tie between team-mates is not a tie.
    #[test]
    fn a_team_majority_decides_a_team_series() {
        let mut t = Tournament::start(SeriesLength::BestOfThree);
        t.wins = [2, 2, 0, 0, 0, 0];
        t.round = 2;
        assert!(t.tally_decides(TeamMode::Pairs, 4));
        assert!(!t.tally_decides(TeamMode::Solo, 4));
    }

    #[test]
    fn champion_needs_a_unique_top() {
        let mut t = Tournament::start(SeriesLength::BestOfFive);
        assert_eq!(t.champion(), None, "no wins yet");
        t.wins = [2, 1, 0, 0, 0, 0];
        assert_eq!(t.champion(), Some(0));
        t.wins = [2, 2, 0, 0, 0, 0];
        assert_eq!(t.champion(), None, "tied series has no champion");
    }

    /// A peer pulled from its results card into a new match takes the new
    /// match's series, not the old one's: the invitation that arrives on
    /// the card may be the host's next launch from the lobby, not the next
    /// round of what was being played.
    #[test]
    fn an_invitation_to_a_new_match_brings_its_own_series() {
        use crate::app::net::{Online, OnlineSession};
        use crate::transport::{MatchTerms, SeriesStanding, UdpTransport};

        let interlude = |was: Tournament, series: u8, standing: Option<SeriesStanding>| {
            let mut app = App::new();
            app.insert_resource(GameSettings::default());
            app.init_resource::<crate::app::Daily>();
            app.init_resource::<crate::app::SeatNames>();
            app.insert_resource(Seats(2));
            app.init_resource::<crate::app::match_setup::MatchConfig>();
            app.init_resource::<crate::app::match_setup::CustomBeaches>();
            app.insert_resource(was);
            let terms = MatchTerms {
                series,
                ..MatchTerms::default()
            };
            let mut session = OnlineSession::new(
                UdpTransport::join(("127.0.0.1", 47990)).expect("socket"),
                crate::app::net::lockstep_for(Some(1), (0..2).collect(), crate::sim::DEFAULT_DELAY),
                2,
                terms,
            );
            session.series_standing = standing;
            session.next_round = true;
            app.insert_resource(Online(Some(session)));
            app.add_systems(Update, enter_interlude);
            app.update();
            app.world_mut()
                .remove_resource::<Tournament>()
                .expect("tournament")
        };

        // A single round over, then the host's best of three.
        let t = interlude(Tournament::default(), 1, Some(SeriesStanding::opening()));
        assert!(t.is_running(), "a series now");
        assert_eq!((t.length, t.round), (SeriesLength::BestOfThree, 1));

        // A decided best of five, then the host's single round.
        let mut decided = Tournament::start(SeriesLength::BestOfFive);
        decided.wins = [3, 1, 0, 0, 0, 0];
        decided.state = SeriesState::Decided;
        let t = interlude(decided, 0, None);
        assert!(!t.in_series(), "no standings over a single round");

        // And the next round of the same series is still the host's word.
        let mut wins = [0; MAX_PLAYERS];
        wins[1] = 1;
        let t = interlude(
            Tournament::start(SeriesLength::BestOfThree),
            1,
            Some(SeriesStanding { round: 2, wins }),
        );
        assert!(t.is_running());
        assert_eq!((t.round, t.wins[1]), (2, 1));
    }

    /// A player admitted from the queue between rounds: the host has dealt
    /// the next round to three seats and moved the AI's win up one, while
    /// `Seats` and `SeatNames` still hold the two of the round just played.
    /// The card names the new table, so the AI's star sits by its name and
    /// the newcomer's nought by theirs.
    #[test]
    fn the_interlude_names_the_table_just_dealt() {
        use crate::app::net::{Online, OnlineSession};
        use crate::transport::{MatchTerms, SeriesStanding, UdpTransport};

        let mut app = App::new();
        app.insert_resource(GameSettings::default());
        app.init_resource::<crate::app::Daily>();
        let mut was = crate::app::SeatNames::default();
        was.0[0] = "Ann".into();
        was.0[1] = "Robo".into();
        app.insert_resource(was);
        app.insert_resource(Seats(2));
        app.init_resource::<crate::app::match_setup::MatchConfig>();
        app.init_resource::<crate::app::match_setup::CustomBeaches>();
        app.insert_resource(Tournament::start(SeriesLength::BestOfThree));
        let terms = MatchTerms {
            series: 1,
            bots: 1,
            ..MatchTerms::default()
        };
        let mut session = OnlineSession::new(
            UdpTransport::host(0).expect("socket"),
            crate::app::net::lockstep_for(Some(0), (0..3).collect(), crate::sim::DEFAULT_DELAY),
            3,
            terms,
        );
        session.names[0] = "Ann".into();
        session.names[1] = "Cy".into();
        session.names[2] = "Robo".into();
        session.series_standing = Some(SeriesStanding {
            round: 2,
            wins: [0, 0, 1, 0, 0, 0],
        });
        session.next_round = true;
        app.insert_resource(Online(Some(session)));
        app.add_systems(Update, enter_interlude);
        app.update();

        let mut texts = app.world_mut().query::<&Text>();
        let cells: Vec<String> = texts.iter(app.world()).map(|t| t.0.clone()).collect();
        let after = |who: &str| {
            let at = cells.iter().position(|c| c == who).expect(who);
            cells[at + 1].clone()
        };
        assert_eq!(after("Cy"), "", "the newcomer has no wins");
        assert_eq!(after("Robo"), "*", "the AI keeps its win by its name");
    }

    /// The interlude reads the standing off the session and leaves it
    /// there: it is what the host packs into every invitation it re-sends
    /// for the rest of the round, and into the round it hands a watcher.
    /// Taken, those carried none, and a player caught up mid-series began
    /// its tally at round one with nobody on a win.
    #[test]
    fn the_interlude_leaves_the_standing_for_the_round() {
        use crate::app::net::{Online, OnlineSession};
        use crate::transport::{MatchTerms, SeriesStanding, UdpTransport};

        let mut app = App::new();
        app.insert_resource(GameSettings::default());
        app.init_resource::<crate::app::Daily>();
        app.init_resource::<crate::app::SeatNames>();
        app.insert_resource(Seats(2));
        app.init_resource::<crate::app::match_setup::MatchConfig>();
        app.init_resource::<crate::app::match_setup::CustomBeaches>();
        app.insert_resource(Tournament::start(SeriesLength::BestOfFive));
        let terms = MatchTerms {
            series: 2,
            ..MatchTerms::default()
        };
        let mut session = OnlineSession::new(
            UdpTransport::host(0).expect("socket"),
            crate::app::net::lockstep_for(Some(0), (0..2).collect(), crate::sim::DEFAULT_DELAY),
            2,
            terms,
        );
        let standing = SeriesStanding {
            round: 3,
            wins: [1, 1, 0, 0, 0, 0],
        };
        session.series_standing = Some(standing);
        session.next_round = true;
        app.insert_resource(Online(Some(session)));
        app.add_systems(Update, enter_interlude);
        app.update();

        let t = app.world().resource::<Tournament>();
        assert_eq!((t.round, t.wins[1]), (3, 1), "the host's word, adopted");
        let online = app.world().resource::<Online>();
        let session = online.0.as_ref().expect("the session");
        assert!(!session.next_round, "through the doorway");
        assert_eq!(
            session.series_standing,
            Some(standing),
            "and still there for the round"
        );
    }

    /// The wire carries the series as a dial index, and the app reads it
    /// through [`MatchTerms::is_series`]. The two must agree for every
    /// position of the dial, or a best-of-five goes out to every joiner as
    /// a single round.
    #[test]
    fn the_wire_flag_agrees_with_the_dial() {
        for (index, length) in SeriesLength::ALL.iter().enumerate() {
            let terms = crate::transport::MatchTerms {
                series: index as u8,
                ..Default::default()
            };
            assert_eq!(terms.is_series(), length.is_series(), "{length:?}");
            let armed = Tournament::from_terms(terms, None);
            assert_eq!(
                armed.in_series(),
                length.is_series(),
                "{length:?} arms a tournament"
            );
            assert_eq!(armed.length, *length);
        }
        // Taken up mid-series, the standing is the host's, not a fresh one.
        let mut wins = [0; MAX_PLAYERS];
        wins[2] = 2;
        let late = Tournament::taken_up(SeriesLength::BestOfFive, 4, wins);
        assert_eq!((late.round, late.wins[2]), (4, 2));
        assert!(!Tournament::taken_up(SeriesLength::Single, 4, wins).in_series());
    }
}