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
//! The stuck-player hint: after a few failed runs, one signpost of a
//! solution, shown dimmed on the sand.
//!
//! Only ever one, and only on request: a puzzle that hands you the answer
//! is not a puzzle, and one you cannot see into is not a lesson. The levels
//! ship with a solution the tests already replay, so the game knows the
//! answer whether or not it says so.

use crate::app::campaign::CampaignKind;
use crate::app::{Campaign, Phase, Sim, art, layout, palette};
use crate::sim::Placement;
use bevy::prelude::*;

/// Failed runs on one level before the hint is offered.
pub const STUCK_AFTER: u32 = 3;

/// How stuck the player is on the level they are playing, and what they have
/// been shown.
#[derive(Resource, Default)]
pub struct Hints {
    /// The level these counts belong to, so switching levels starts fresh.
    /// The list as well as the index: Tide Pool and Beach Day both have a
    /// fourth level, and being stuck on one is not being stuck on the
    /// other. `None` before any level has been played.
    level: Option<(CampaignKind, usize)>,
    /// Failed runs on it.
    losses: u32,
    /// Whether the level carries a solution to take a step from. A
    /// player's own level and a pasted one have none, and offering H there
    /// promised a hint the key then could not give.
    answerable: bool,
    /// The placement being shown, if the player asked for one.
    shown: Option<Placement>,
}

impl Hints {
    /// Whether the player has failed enough to be offered a way in.
    pub fn offered(&self) -> bool {
        self.answerable && self.losses >= STUCK_AFTER
    }

    pub fn showing(&self) -> bool {
        self.shown.is_some()
    }

    /// Forget everything: a different level, or a fresh look at this one.
    /// A whole struct literal, so a new field cannot survive a reset unseen.
    fn reset(&mut self, campaign: &Campaign) {
        *self = Hints {
            level: Some(level_of(campaign)),
            losses: 0,
            answerable: !campaign.current().solution.is_empty(),
            shown: None,
        };
    }
}

/// The level the campaign is on, as the hint counts it.
fn level_of(campaign: &Campaign) -> (CampaignKind, usize) {
    (campaign.kind, campaign.index)
}

/// The dimmed arrow.
#[derive(Component)]
pub struct HintGhost;

/// How long "no signposts left" stays on the hint line, in seconds.
const DENIED_SECS: f32 = 2.5;

/// A refusal the player deserves a sentence about, counting down.
///
/// Only the spent-inventory one. Every other refusal is answered by aiming
/// somewhere else and the flash says enough; this one is answered by
/// picking a signpost back up.
#[derive(Resource, Default)]
pub struct DeniedNote(f32);

/// Catch the denials worth explaining and start the countdown.
pub fn note_denials(
    mut denials: MessageReader<crate::app::PlacementDenied>,
    mut note: ResMut<DeniedNote>,
) {
    if denials.read().any(|d| d.player == 0 && d.out_of_signposts) {
        note.0 = DENIED_SECS;
    }
}

/// Age it out. A level change clears it too: the sentence is about the
/// board that refused, and that board is gone.
pub fn tick_denied_note(time: Res<Time>, campaign: Res<Campaign>, mut note: ResMut<DeniedNote>) {
    if campaign.is_changed() {
        note.0 = 0.0;
        return;
    }
    note.0 = (note.0 - time.delta_secs()).max(0.0);
}

/// Count a failed run, and start over when the level changes.
pub fn record_loss(campaign: Res<Campaign>, mut hints: ResMut<Hints>) {
    if hints.level != Some(level_of(&campaign)) {
        hints.reset(&campaign);
    }
    hints.losses += 1;
    // A new attempt is a clean board; the ghost is re-shown on request.
    hints.shown = None;
}

/// Drop the hint when the level does.
pub fn reset_on_level(campaign: Res<Campaign>, mut hints: ResMut<Hints>) {
    if hints.level != Some(level_of(&campaign)) {
        hints.reset(&campaign);
    } else {
        hints.shown = None;
    }
}

/// The placement to show: the first one of the level's solution that the
/// player has not already made. Somebody halfway there is shown their *next*
/// step rather than the one they got right.
fn next_step(campaign: &Campaign, sim: &Sim) -> Option<Placement> {
    campaign
        .current()
        .solution
        .iter()
        .copied()
        .find(|&(x, y, dir)| sim.0.signpost_at(x, y).is_none_or(|sp| sp.dir != dir))
}

/// H, once the player has failed enough, reveals one signpost.
pub fn hint_input(
    keys: Res<ButtonInput<KeyCode>>,
    caps: Res<crate::app::keycaps::KeyCaps>,
    campaign: Res<Campaign>,
    sim: Res<Sim>,
    mut hints: ResMut<Hints>,
) {
    if !caps.just_pressed(&keys, 'H') || !hints.offered() {
        return;
    }
    hints.shown = next_step(&campaign, &sim);
}

/// Keep the ghost arrow matching what the hint is showing.
pub fn draw_hint(
    mut commands: Commands,
    hints: Res<Hints>,
    sim: Res<Sim>,
    art: Res<art::Art>,
    ghosts: Query<Entity, With<HintGhost>>,
    mut drawn_on: Local<(u8, u8)>,
) {
    // Redrawn when the hint changes, or when the board's size does: the
    // ghost sits at a tile centre, which only the size moves. Redrawing on
    // every change to the sim tore the sprite down and put it back thirty
    // times a second. Every level load writes `hints`, so a swapped board
    // of the same size is caught there.
    let size = (sim.0.width(), sim.0.height());
    if !hints.is_changed() && !(sim.is_changed() && *drawn_on != size) {
        return;
    }
    *drawn_on = size;
    for ghost in &ghosts {
        commands.entity(ghost).despawn();
    }
    let Some((x, y, dir)) = hints.shown else {
        return;
    };
    let pos = layout::tile_center(&sim.0, x, y);
    // The signpost that goes here, as a ghost: the board's outline faint
    // and its arrow a little less so, in no seat's colour.
    let size = Some(Vec2::splat(layout::TILE * 0.94));
    commands
        .spawn((
            HintGhost,
            Sprite {
                image: art.sign_shape.clone(),
                color: palette::PARCHMENT.with_alpha(0.2),
                custom_size: size,
                ..default()
            },
            Transform::from_translation(pos.extend(layout::z::SIGNPOST - 0.1))
                .with_rotation(layout::dir_rotation(dir)),
        ))
        .with_child((
            Sprite {
                image: art.sign_paint.clone(),
                color: palette::PARCHMENT.with_alpha(0.45),
                custom_size: size,
                ..default()
            },
            Transform::from_translation(Vec3::new(0.0, 0.0, 0.01)),
        ));
}

pub fn clear_hint_ghosts(mut commands: Commands, ghosts: Query<Entity, With<HintGhost>>) {
    for ghost in &ghosts {
        commands.entity(ghost).despawn();
    }
}

/// The line under the header while the hint is available or showing.
pub fn hint_line(
    tr: &crate::app::i18n::Tr,
    hints: &Hints,
    denied: &DeniedNote,
    phase: &Phase,
) -> Option<String> {
    // The denial answers the key that was just pressed, so it outranks both
    // the stuck-hint and the level's lesson for as long as it lasts.
    if denied.0 > 0.0 {
        return Some(tr.denied_no_posts.to_string());
    }
    if !hints.offered() || !matches!(phase, Phase::Setup | Phase::Lost) {
        return None;
    }
    Some(if hints.showing() {
        tr.hint_showing.to_string()
    } else {
        tr.hint_offer.to_string()
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::app::CampaignKind;
    use crate::sim::{Level, campaign_levels};

    fn campaign_at(index: usize) -> Campaign {
        let levels = campaign_levels();
        let builtins = levels.len();
        Campaign {
            kind: CampaignKind::TidePool,
            levels,
            index,
            builtins,
        }
    }

    /// The hint shows the next step, not the first one: a player who has
    /// placed half a solution is shown what they are missing.
    #[test]
    fn the_hint_skips_what_is_already_placed() {
        // Level 28 is the one with two placements.
        let campaign = campaign_at(27);
        let level: &Level = campaign.current();
        assert_eq!(level.solution.len(), 2, "picked a two-post level");
        let mut sim = Sim(level.board());
        assert_eq!(next_step(&campaign, &sim), Some(level.solution[0]));

        let (x, y, dir) = level.solution[0];
        assert!(sim.0.place_signpost(0, x, y, dir));
        assert_eq!(
            next_step(&campaign, &sim),
            Some(level.solution[1]),
            "the first step is done, so show the second"
        );

        let (x, y, dir) = level.solution[1];
        assert!(sim.0.place_signpost(0, x, y, dir));
        assert_eq!(next_step(&campaign, &sim), None, "nothing left to show");

        // A post pointing the wrong way is not the step.
        let mut wrong = Sim(level.board());
        let (x, y, dir) = level.solution[0];
        assert!(wrong.0.place_signpost(0, x, y, dir.right()));
        assert_eq!(next_step(&campaign, &wrong), Some(level.solution[0]));
    }

    /// The flow end to end: three failed runs open the offer, and only then
    /// does H show one step: the first one the player is missing.
    #[test]
    fn three_losses_open_the_hint_and_h_shows_one_step() {
        use bevy::ecs::system::RunSystemOnce;

        let mut app = App::new();
        app.init_resource::<ButtonInput<KeyCode>>();
        app.init_resource::<crate::app::keycaps::KeyCaps>();
        app.init_resource::<Hints>();
        app.insert_resource(campaign_at(27));
        let level = campaign_at(27).current().clone();
        app.insert_resource(Sim(level.board()));

        let lose = |app: &mut App| {
            let _ = app.world_mut().run_system_once(record_loss);
        };
        let ask = |app: &mut App| {
            let mut keys = app.world_mut().resource_mut::<ButtonInput<KeyCode>>();
            keys.reset_all();
            keys.press(KeyCode::KeyH);
            let _ = app.world_mut().run_system_once(hint_input);
        };

        // Two failures and a hopeful H: nothing yet.
        lose(&mut app);
        lose(&mut app);
        ask(&mut app);
        assert!(!app.world().resource::<Hints>().offered());
        assert!(!app.world().resource::<Hints>().showing());

        // The third opens it, and H takes it.
        lose(&mut app);
        assert!(app.world().resource::<Hints>().offered());
        ask(&mut app);
        assert_eq!(
            app.world().resource::<Hints>().shown,
            Some(level.solution[0]),
            "one signpost, and the first one they are missing"
        );

        // Placing that one and asking again moves the hint along.
        let (x, y, dir) = level.solution[0];
        assert!(
            app.world_mut()
                .resource_mut::<Sim>()
                .0
                .place_signpost(0, x, y, dir)
        );
        ask(&mut app);
        assert_eq!(
            app.world().resource::<Hints>().shown,
            Some(level.solution[1]),
            "the hint follows the player"
        );
    }

    /// Running out of signposts says so, and says it differently from
    /// every other refusal.
    ///
    /// Both kinds of no fire the same flash and the same knock, so without
    /// this line "you have none left" and "not on that tile" are
    /// indistinguishable.
    #[test]
    fn a_spent_inventory_gets_a_sentence_of_its_own() {
        use crate::app::i18n::EN;
        let hints = Hints::default();
        assert!(!hints.offered(), "not stuck: no line of its own to compete");

        assert_eq!(
            hint_line(&EN, &hints, &DeniedNote(0.0), &Phase::Setup),
            None
        );
        assert_eq!(
            hint_line(&EN, &hints, &DeniedNote(1.0), &Phase::Setup).as_deref(),
            Some(EN.denied_no_posts),
        );
        // It outranks the stuck-hint, which is about the level rather than
        // about the key just pressed.
        let stuck = Hints {
            losses: STUCK_AFTER,
            answerable: true,
            ..Default::default()
        };
        assert_eq!(
            hint_line(&EN, &stuck, &DeniedNote(0.0), &Phase::Setup).as_deref(),
            Some(EN.hint_offer),
        );
        assert_eq!(
            hint_line(&EN, &stuck, &DeniedNote(1.0), &Phase::Setup).as_deref(),
            Some(EN.denied_no_posts),
        );
    }

    /// Only the inventory refusal raises it. A tile that simply cannot take
    /// a signpost is answered by aiming elsewhere, and the flash says so.
    #[test]
    fn only_the_inventory_refusal_is_worth_a_sentence() {
        use crate::app::PlacementDenied;
        use bevy::ecs::system::RunSystemOnce;

        let mut app = App::new();
        app.init_resource::<DeniedNote>();
        app.add_message::<PlacementDenied>();

        app.world_mut().write_message(PlacementDenied {
            player: 0,
            out_of_signposts: false,
        });
        let _ = app.world_mut().run_system_once(note_denials);
        assert_eq!(app.world().resource::<DeniedNote>().0, 0.0, "a bad tile");

        app.world_mut().write_message(PlacementDenied {
            player: 0,
            out_of_signposts: true,
        });
        let _ = app.world_mut().run_system_once(note_denials);
        assert!(
            app.world().resource::<DeniedNote>().0 > 0.0,
            "a spent inventory"
        );
    }

    /// Losses only count toward the level they happened on.
    #[test]
    fn switching_levels_starts_the_count_over() {
        let mut hints = Hints {
            answerable: true,
            ..Hints::default()
        };
        for _ in 0..STUCK_AFTER {
            hints.level = Some((CampaignKind::TidePool, 4));
            hints.losses += 1;
        }
        assert!(hints.offered());
        hints.reset(&campaign_at(5));
        assert!(!hints.offered(), "a new level is not a stuck one");
    }

    /// A level with no solution to take a step from (the player's own, or
    /// a pasted one) never offers H, however stuck: the key has nothing
    /// to show there.
    #[test]
    fn no_solution_no_offer() {
        // Stage six: the earlier ones with no arrows to place carry none.
        let mut campaign = campaign_at(5);
        let mut hints = Hints::default();
        hints.reset(&campaign);
        hints.losses = STUCK_AFTER;
        assert!(hints.offered(), "a shipped stage has its answer");
        let index = campaign.index;
        campaign.levels[index].solution.clear();
        hints.reset(&campaign);
        hints.losses = STUCK_AFTER;
        assert!(!hints.offered());
    }

    /// The same index in the other list is a different level: three
    /// losses on Tide Pool's sixth do not open a hint on Beach Day's.
    #[test]
    fn the_other_list_at_the_same_index_is_another_level() {
        use bevy::ecs::system::RunSystemOnce;

        let mut app = App::new();
        app.init_resource::<Hints>();
        app.insert_resource(campaign_at(5));
        for _ in 0..STUCK_AFTER {
            let _ = app.world_mut().run_system_once(record_loss);
        }
        assert!(app.world().resource::<Hints>().offered());
        app.world_mut().resource_mut::<Campaign>().kind = CampaignKind::BeachDay;
        let _ = app.world_mut().run_system_once(reset_on_level);
        assert!(
            !app.world().resource::<Hints>().offered(),
            "Beach Day's sixth level is not the one they were stuck on"
        );
    }

    /// Hints for the level `campaign` is on, stuck on it and showing a step.
    fn stuck_and_showing(campaign: &Campaign) -> Hints {
        Hints {
            level: Some(level_of(campaign)),
            losses: STUCK_AFTER,
            answerable: true,
            shown: Some((1, 1, crate::sim::Direction::Up)),
        }
    }

    /// Once a step is on the board the line says how to read it, and the
    /// line keeps quiet while the run plays out or after it is won: the
    /// hint is for a board that is still being set up, or just lost.
    #[test]
    fn the_hint_line_says_what_is_shown_and_only_where_it_helps() {
        use crate::app::i18n::EN;
        let hints = stuck_and_showing(&campaign_at(3));
        let quiet = DeniedNote(0.0);
        assert_eq!(
            hint_line(&EN, &hints, &quiet, &Phase::Setup).as_deref(),
            Some(EN.hint_showing)
        );
        assert_eq!(
            hint_line(&EN, &hints, &quiet, &Phase::Lost).as_deref(),
            Some(EN.hint_showing)
        );
        for phase in [Phase::Running, Phase::Won] {
            assert_eq!(hint_line(&EN, &hints, &quiet, &phase), None, "{phase:?}");
        }
    }

    /// Going back to the same level takes the step off the board but keeps
    /// the count, so the offer stands; a different level starts clean.
    #[test]
    fn a_reload_keeps_the_count_and_a_new_level_clears_it() {
        let mut app = App::new();
        app.insert_resource(campaign_at(3));
        let hints = stuck_and_showing(&campaign_at(3));
        app.insert_resource(hints);
        app.add_systems(Update, reset_on_level);
        app.update();
        let hints = app.world().resource::<Hints>();
        assert!(!hints.showing(), "the step is taken off");
        assert!(hints.offered(), "and the count stands");
        app.world_mut().resource_mut::<Campaign>().index = 4;
        app.update();
        let hints = app.world().resource::<Hints>();
        assert!(!hints.offered(), "a new level starts from nothing");
    }

    /// The denial fades with time, and goes at once when the level changes:
    /// it was about a board that is no longer there.
    #[test]
    fn the_denial_fades_and_goes_with_the_level() {
        let mut app = App::new();
        app.insert_resource(campaign_at(3));
        app.init_resource::<Time>();
        app.insert_resource(DeniedNote(2.0));
        app.add_systems(Update, tick_denied_note);
        // The first frame sees the campaign as new, which clears it; set it
        // again to watch it fade.
        app.update();
        app.insert_resource(DeniedNote(2.0));
        app.world_mut()
            .resource_mut::<Time>()
            .advance_by(std::time::Duration::from_millis(500));
        app.update();
        let left = app.world().resource::<DeniedNote>().0;
        assert!((left - 1.5).abs() < 1e-3, "{left}");
        app.world_mut().resource_mut::<Campaign>().index = 5;
        app.update();
        assert_eq!(app.world().resource::<DeniedNote>().0, 0.0);
    }
}