pinch-points 0.8.0

A fast, kid-friendly crab-routing game: route streams of crabs into your sandcastle before time runs out
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
//! The pause overlay: Esc (or Start on a pad) during play opens a card with
//! Continue / Back to menu / Quit.
//!
//! Offline it simply freezes the sim. Online it runs the lockstep pause
//! protocol (see `sim::net`): the peers agree on a frame, everyone's commits
//! stop there, and the match halts on the same frame on every screen. A peer
//! that pauses opens the card on the others too, or their beach would
//! freeze with no explanation.

use crate::app::menu_ui;
use crate::app::net::Online;
use crate::app::palette;
use crate::app::settings::GameSettings;
use crate::app::{Paused, Phase, Screen};
use bevy::prelude::*;

/// One pause-card action; navigation and Enter both match on this.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum PauseAction {
    Continue,
    ToMenu,
    Quit,
}

impl PauseAction {
    pub const ALL: [PauseAction; 3] = [
        PauseAction::Continue,
        PauseAction::ToMenu,
        PauseAction::Quit,
    ];
}

const OPTIONS: usize = PauseAction::ALL.len();

/// Whether the pause card is open, and which row is selected.
#[derive(Resource, Default)]
pub struct PauseMenu {
    pub open: bool,
    /// Whether the round was already stopped when the card was raised.
    ///
    /// A replay can be paused from its own transport before the card is
    /// opened, and a card that handed the round back running whatever it
    /// found would start the recording again with no key pressed.
    held: bool,
    /// Whether the card was raised for this player alone: a spectator's,
    /// which stops nothing, since a watcher does not get to freeze the
    /// match. The table's pause did not raise it, so the table playing on
    /// does not put it away either.
    own: bool,
    selected: usize,
}

impl PauseMenu {
    /// Whether the card is up and the round is stopped under it, which is
    /// what the count, the music and the prompt line wait on. A
    /// spectator's own card stops nothing: the table plays on behind it,
    /// and a countdown held under it left the spectator behind the match
    /// until the host forgot them as gone.
    pub fn stops_the_round(&self) -> bool {
        self.open && !self.own
    }
}

#[derive(Component)]
pub struct PauseUi;

#[derive(Component)]
pub struct PauseRow(usize);

/// The card, titled for what it is: "paused" when the round stopped, and
/// a plain menu for a spectator, whose match plays on behind it.
fn spawn_card(commands: &mut Commands, settings: &GameSettings, own: bool) {
    let tr = settings.tr();
    let title = match own {
        true => tr.pause_menu_title,
        false => tr.pause_title,
    };
    commands
        .spawn((
            PauseUi,
            GlobalZIndex(menu_ui::layer::CARD),
            menu_ui::centred_overlay(),
        ))
        .with_children(|wrap| {
            wrap.spawn(menu_ui::screen_card()).with_children(|card| {
                card.spawn((
                    Text::new(title),
                    menu_ui::display_font(30.0),
                    TextColor(palette::GOLD),
                ));
                card.spawn(Node {
                    height: Val::Px(6.0),
                    ..default()
                });
                menu_ui::spawn_rows(card, OPTIONS, 24.0, PauseRow);
            });
        });
}

fn close(
    commands: &mut Commands,
    menu: &mut PauseMenu,
    paused: &mut Paused,
    ui: &Query<Entity, With<PauseUi>>,
) {
    menu.open = false;
    // Give the round back exactly as the card found it.
    paused.0 = menu.held;
    for entity in ui {
        commands.entity(entity).despawn();
    }
}

/// The pause card: whether it is up and where its cursor is, the freeze
/// it holds, and the commands and entities that draw it.
#[derive(bevy::ecs::system::SystemParam)]
pub struct PauseCard<'w, 's> {
    commands: Commands<'w, 's>,
    menu: ResMut<'w, PauseMenu>,
    paused: ResMut<'w, Paused>,
    ui: Query<'w, 's, Entity, With<PauseUi>>,
}

/// The two ways out of a round from the card: the menu, and the desktop.
#[derive(bevy::ecs::system::SystemParam)]
pub struct Leaving<'w> {
    next_screen: ResMut<'w, NextState<Screen>>,
    exit: MessageWriter<'w, AppExit>,
}

/// Open, navigate, and act on the pause card. Runs on the play screens.
pub fn pause_input(
    card: PauseCard,
    buttons: menu_ui::Buttons,
    settings: Res<GameSettings>,
    screen: Res<State<Screen>>,
    phase: Res<State<Phase>>,
    mut online: ResMut<Online>,
    leaving: Leaving,
) {
    let PauseCard {
        mut commands,
        mut menu,
        mut paused,
        ui,
    } = card;
    let keys = &*buttons.keys;
    let Leaving {
        mut next_screen,
        mut exit,
    } = leaving;
    // Pads: Start toggles the card, but never during puzzle setup where
    // Start means "begin the run".
    let start_ok = !(*screen.get() == Screen::Puzzle && *phase.get() == Phase::Setup);
    let pad_start = start_ok && buttons.pad(GamepadButton::Start);
    // Nor on a puzzle's won or lost card, where Esc is the way back to
    // the stage list and a pause card would open under it for a frame.
    let done = *screen.get() == Screen::Puzzle && matches!(*phase.get(), Phase::Won | Phase::Lost);
    let escape = !done && keys.just_pressed(KeyCode::Escape);
    let pad_up = buttons.pad(GamepadButton::DPadUp);
    let pad_down = buttons.pad(GamepadButton::DPadDown);
    let pad_accept = buttons.pad(GamepadButton::South);

    // A peer's pause opens the card here too, so a frozen beach is never
    // unexplained. Their Escape is as good as ours.
    let peer_paused = online.0.as_ref().is_some_and(|s| s.session.paused());
    if !menu.open {
        if escape || pad_start || peer_paused {
            menu.open = true;
            menu.selected = 0;
            // What to hand back on the way out: a replay stopped from its
            // own transport must still be stopped when the card closes.
            menu.held = paused.0;
            menu.own = false;
            match online.0.as_mut() {
                // Online: the peers agree on a frame to stop at, and the sim
                // halts there by itself. Freezing the local ticker instead
                // would stop the network pump that carries the resume.
                Some(session) if !peer_paused => {
                    menu.own = session.watching();
                    session.request_pause();
                }
                Some(_) => {}
                None => paused.0 = true,
            }
            spawn_card(&mut commands, &settings, menu.own);
        }
        return;
    }

    if keys.just_pressed(KeyCode::Escape) || pad_start {
        if let Some(session) = online.0.as_mut() {
            session.request_resume();
        }
        close(&mut commands, &mut menu, &mut paused, &ui);
        return;
    }
    // A peer resumed: everyone plays on. A spectator's own card was never
    // the table's, and stays up until they close it. It used to be shut
    // on the very next frame, so "Esc: menu" could not reach the menu.
    if online.0.is_some() && !peer_paused && !menu.own {
        close(&mut commands, &mut menu, &mut paused, &ui);
        return;
    }
    let before = menu.selected;
    menu.selected = menu_ui::nav(keys, menu.selected, OPTIONS);
    // Up wins over a same-frame down, as it always has. Read only when the
    // keys did not move the cursor already: over a results card the pad's
    // d-pad also arrives as W/S through the menu bridge, and reading both
    // moved two rows a press, so Down from Continue landed on Quit.
    let pad_nav = if menu.selected != before {
        menu_ui::Nav::Stay
    } else if pad_up {
        menu_ui::Nav::Up
    } else if pad_down {
        menu_ui::Nav::Down
    } else {
        menu_ui::Nav::Stay
    };
    menu.selected = menu_ui::step(pad_nav, menu.selected, OPTIONS);
    if menu_ui::enter(keys) || pad_accept {
        match PauseAction::ALL[menu.selected] {
            PauseAction::Continue => {
                if let Some(session) = online.0.as_mut() {
                    session.request_resume();
                }
                close(&mut commands, &mut menu, &mut paused, &ui);
            }
            PauseAction::ToMenu => {
                // Leaving drops the session anyway, but resume first so the
                // peers are not left frozen waiting for a player who quit.
                if let Some(session) = online.0.as_mut() {
                    session.request_resume();
                }
                close(&mut commands, &mut menu, &mut paused, &ui);
                next_screen.set(Screen::Menu);
            }
            PauseAction::Quit => {
                exit.write(AppExit::Success);
            }
        }
    }
}

/// Style the option rows around the selection.
pub fn update_pause_rows(
    menu: Res<PauseMenu>,
    settings: Res<GameSettings>,
    mut rows: Query<(&PauseRow, &mut Text, &mut TextColor)>,
) {
    let tr = settings.tr();
    let labels = [tr.pause_continue, tr.pause_to_menu, tr.pause_quit];
    for (row, mut text, mut color) in &mut rows {
        menu_ui::paint_row(row.0 == menu.selected, labels[row.0], &mut text, &mut color);
    }
}

/// Leaving a play screen always clears the card and unfreezes.
pub fn reset_pause(
    mut commands: Commands,
    mut menu: ResMut<PauseMenu>,
    mut paused: ResMut<Paused>,
    ui: Query<Entity, With<PauseUi>>,
) {
    close(&mut commands, &mut menu, &mut paused, &ui);
}

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

    /// The card's own behaviour, which the pause *protocol* tests never
    /// touch: Escape opens it and freezes an offline round, the selection
    /// walks the options, and picking "back to the beach" leaves.
    #[test]
    fn escape_opens_the_card_and_the_menu_row_leaves() {
        let mut app = App::new();
        app.add_plugins(bevy::state::app::StatesPlugin);
        app.init_state::<Screen>();
        app.init_state::<Phase>();
        app.init_resource::<ButtonInput<KeyCode>>();
        app.init_resource::<PauseMenu>();
        app.init_resource::<Paused>();
        app.init_resource::<Online>();
        app.insert_resource(GameSettings::default());
        app.add_message::<AppExit>();
        app.add_systems(Update, pause_input);

        let tap = |app: &mut App, key: KeyCode| {
            let mut keys = app.world_mut().resource_mut::<ButtonInput<KeyCode>>();
            keys.reset_all();
            keys.press(key);
            app.update();
            app.world_mut()
                .resource_mut::<ButtonInput<KeyCode>>()
                .reset_all();
        };

        // A versus round, running.
        app.insert_resource(State::new(Screen::Versus));
        tap(&mut app, KeyCode::Escape);
        assert!(app.world().resource::<PauseMenu>().open, "the card opened");
        assert!(
            app.world().resource::<Paused>().0,
            "an offline round freezes with it"
        );

        // The card is three rows: down twice reaches the last of them.
        let row = |app: &App| PauseAction::ALL[app.world().resource::<PauseMenu>().selected];
        tap(&mut app, KeyCode::KeyS);
        tap(&mut app, KeyCode::KeyS);
        assert_eq!(row(&app), PauseAction::Quit);
        // A third wraps to the top rather than falling off the end.
        tap(&mut app, KeyCode::KeyS);
        assert_eq!(row(&app), PauseAction::Continue);
        // And back the other way, onto the row this test then takes.
        tap(&mut app, KeyCode::KeyW);
        assert_eq!(row(&app), PauseAction::Quit);
        tap(&mut app, KeyCode::KeyW);
        assert_eq!(row(&app), PauseAction::ToMenu);

        tap(&mut app, KeyCode::Enter);
        app.update(); // let the state transition apply
        assert!(!app.world().resource::<PauseMenu>().open, "the card closed");
        assert!(!app.world().resource::<Paused>().0, "and unfroze");
        assert_eq!(*app.world().resource::<State<Screen>>().get(), Screen::Menu);
    }

    /// A spectator's Escape opens a card of their own. The lockstep names
    /// no frame for a watcher, so the table never pauses, and the card used
    /// to read that as "a peer resumed" and shut itself the next frame:
    /// "Esc: menu" on the spectator's prompt led nowhere.
    #[test]
    fn a_spectators_card_stays_up() {
        use crate::app::net::OnlineSession;
        use crate::sim::{DEFAULT_DELAY, Lockstep};
        use crate::transport::{MatchTerms, UdpTransport};

        let mut app = App::new();
        app.add_plugins(bevy::state::app::StatesPlugin);
        app.init_state::<Screen>();
        app.init_state::<Phase>();
        app.insert_resource(State::new(Screen::Versus));
        app.init_resource::<ButtonInput<KeyCode>>();
        app.init_resource::<PauseMenu>();
        app.init_resource::<Paused>();
        app.insert_resource(GameSettings::default());
        app.add_message::<AppExit>();
        let watcher = OnlineSession::new(
            UdpTransport::host(0).expect("socket"),
            Lockstep::observer(vec![0, 1], DEFAULT_DELAY),
            2,
            MatchTerms::default(),
        );
        assert!(watcher.watching());
        app.insert_resource(Online(Some(watcher)));
        app.add_systems(Update, pause_input);

        app.world_mut()
            .resource_mut::<ButtonInput<KeyCode>>()
            .press(KeyCode::Escape);
        app.update();
        app.world_mut()
            .resource_mut::<ButtonInput<KeyCode>>()
            .reset_all();
        for _ in 0..3 {
            app.update();
        }
        assert!(app.world().resource::<PauseMenu>().open, "still up");
    }

    /// The card takes the keyboard while it is up.
    ///
    /// It is an overlay and not a `Screen`, and it freezes the sim through
    /// a resource of its own, so every input system's own run condition
    /// stays true while it is open. Before `keys_are_free` gated them, the
    /// same W that walked these rows moved the board cursor behind the
    /// card, and an arrow key queued a placement that fired on resume.
    #[test]
    fn the_card_takes_the_keyboard_while_it_is_up() {
        use crate::app::conditions::keys_are_free;
        use crate::app::cursor::{Cursor, move_cursor};
        use crate::app::play_input::versus_input;
        use crate::app::{PendingActions, PlacementDenied, Sim, VersusPhase};
        use crate::sim::classic_arena;

        let mut app = App::new();
        app.add_plugins(bevy::state::app::StatesPlugin);
        app.init_state::<Screen>();
        app.init_state::<Phase>();
        app.init_state::<VersusPhase>();
        app.insert_resource(State::new(Screen::Versus));
        app.insert_resource(Sim(classic_arena(false, 2)));
        app.insert_resource(GameSettings::default());
        app.init_resource::<ButtonInput<KeyCode>>();
        app.init_resource::<Time>();
        app.init_resource::<PendingActions>();
        app.init_resource::<PauseMenu>();
        app.init_resource::<Paused>();
        app.init_resource::<Online>();
        app.add_message::<PlacementDenied>();
        app.add_message::<AppExit>();
        app.world_mut()
            .spawn((Cursor::seated(0), Transform::default()));
        // The schedule's own conditions, so this cannot pass while the real
        // ones let the keys through.
        app.add_systems(
            Update,
            (
                pause_input,
                (move_cursor, versus_input).run_if(keys_are_free),
            )
                .chain(),
        );

        let tap = |app: &mut App, key: KeyCode| {
            let mut keys = app.world_mut().resource_mut::<ButtonInput<KeyCode>>();
            keys.reset_all();
            keys.press(key);
            app.update();
            app.world_mut()
                .resource_mut::<ButtonInput<KeyCode>>()
                .reset_all();
        };
        let cursor = |app: &mut App| {
            let mut q = app.world_mut().query::<&Cursor>();
            let c = q.iter(app.world()).next().expect("one cursor");
            (c.x, c.y)
        };

        tap(&mut app, KeyCode::Escape);
        assert!(app.world().resource::<PauseMenu>().open, "the card opened");
        let parked = cursor(&mut app);

        // S walks the card's rows and nothing else.
        tap(&mut app, KeyCode::KeyS);
        assert_eq!(
            PauseAction::ALL[app.world().resource::<PauseMenu>().selected],
            PauseAction::ToMenu
        );
        assert_eq!(cursor(&mut app), parked, "the cursor stayed put");

        // And an arrow key queues nothing for the resume to play out.
        tap(&mut app, KeyCode::ArrowUp);
        assert_eq!(
            app.world().resource::<PendingActions>().0[0],
            crate::sim::PlayerAction::None,
            "no placement waiting behind the card"
        );

        // Closing it hands the keys back.
        tap(&mut app, KeyCode::Escape);
        assert!(!app.world().resource::<PauseMenu>().open, "the card closed");
        tap(&mut app, KeyCode::KeyS);
        assert_ne!(cursor(&mut app), parked, "the cursor moves again");
    }

    /// On a puzzle's won or lost card Escape is the way back to the stage
    /// list, read by the card's own input; the pause card stays out of it
    /// rather than opening underneath for a frame.
    #[test]
    fn the_card_stays_shut_on_a_finished_puzzle() {
        let mut app = App::new();
        app.add_plugins(bevy::state::app::StatesPlugin);
        app.init_state::<Screen>();
        app.init_state::<Phase>();
        app.init_resource::<ButtonInput<KeyCode>>();
        app.init_resource::<PauseMenu>();
        app.init_resource::<Paused>();
        app.init_resource::<Online>();
        app.insert_resource(GameSettings::default());
        app.add_message::<AppExit>();
        app.add_systems(Update, pause_input);
        app.insert_resource(State::new(Screen::Puzzle));
        for phase in [Phase::Won, Phase::Lost] {
            app.insert_resource(State::new(phase));
            let mut keys = app.world_mut().resource_mut::<ButtonInput<KeyCode>>();
            keys.reset_all();
            keys.press(KeyCode::Escape);
            app.update();
            assert!(!app.world().resource::<PauseMenu>().open, "{phase:?}");
            assert!(!app.world().resource::<Paused>().0, "{phase:?}");
        }
        // And in the running phase the same press opens it.
        app.insert_resource(State::new(Phase::Running));
        let mut keys = app.world_mut().resource_mut::<ButtonInput<KeyCode>>();
        keys.reset_all();
        keys.press(KeyCode::Escape);
        app.update();
        assert!(app.world().resource::<PauseMenu>().open);
    }

    /// A running puzzle, with the running-phase input beside the card as
    /// the schedule has it. Read by both, the phase input froze the round
    /// and the card took that frozen state as what to hand back on
    /// Continue. One reader now; Continue unfreezes.
    #[test]
    fn continue_unfreezes_a_running_puzzle() {
        let mut app = App::new();
        app.add_plugins(bevy::state::app::StatesPlugin);
        app.init_state::<Screen>();
        app.init_state::<Phase>();
        app.init_resource::<ButtonInput<KeyCode>>();
        app.init_resource::<PauseMenu>();
        app.init_resource::<Paused>();
        app.init_resource::<Online>();
        app.init_resource::<crate::app::keycaps::KeyCaps>();
        app.insert_resource(GameSettings::default());
        app.add_message::<AppExit>();
        app.add_message::<crate::app::LoadLevel>();
        app.add_systems(
            Update,
            (crate::app::play_input::running_input, pause_input).chain(),
        );
        app.insert_resource(State::new(Screen::Puzzle));
        app.insert_resource(State::new(Phase::Running));

        let tap = |app: &mut App, key: KeyCode| {
            let mut keys = app.world_mut().resource_mut::<ButtonInput<KeyCode>>();
            keys.reset_all();
            keys.press(key);
            app.update();
            app.world_mut()
                .resource_mut::<ButtonInput<KeyCode>>()
                .reset_all();
        };
        tap(&mut app, KeyCode::Escape);
        assert!(app.world().resource::<PauseMenu>().open, "the card opened");
        assert!(app.world().resource::<Paused>().0, "and froze the round");
        tap(&mut app, KeyCode::Enter);
        assert!(
            !app.world().resource::<PauseMenu>().open,
            "Continue closed it"
        );
        assert!(
            !app.world().resource::<Paused>().0,
            "and the round runs again"
        );
        // Escape again closes it the same way.
        tap(&mut app, KeyCode::Escape);
        assert!(app.world().resource::<PauseMenu>().open);
        tap(&mut app, KeyCode::Escape);
        assert!(!app.world().resource::<PauseMenu>().open);
        assert!(
            !app.world().resource::<Paused>().0,
            "Escape out is Continue too"
        );
    }
}