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
//! 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::cycle::Cycle;
use crate::app::i18n::fill;
use crate::app::menu_ui;
use crate::app::palette;
use crate::app::settings::GameSettings;
use crate::app::side_panels::leading_seats;
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(
SeriesLength::from_index(usize::from(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: somebody has a majority of the
/// rounds, or the last round has been played.
fn tally_decides(&self) -> bool {
let best = *self.wins.iter().max().unwrap_or(&0);
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::side_panels::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::side_panels::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>,
settings: Res<GameSettings>,
online: Res<crate::app::net::Online>,
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 = crate::app::teams::in_play(&settings, &online, 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() {
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::player_color(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;
/// 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,
settings: Res<GameSettings>,
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;
let mode = crate::app::teams::in_play(&settings, &online, seats.0.max(2));
// 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.
match &mut online.0 {
Some(session) => {
session.next_round = false;
if let Some(crate::transport::SeriesStanding { round, wins }) =
session.series_standing.take()
{
tournament.round = round;
tournament.wins = wins;
}
}
None => tournament.round += 1,
}
// 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::next_map(&mut config, &beaches);
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(2.4, 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.0.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::net::Online>();
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()
};
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"
);
}
#[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");
}
/// 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());
}
}