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
//! The highlight reel: the last fifteen seconds of a finished round, zoomed
//! on the castle that decided it, written out as an animated GIF.
//!
//! Built by re-simulating the round's [`Replay`] rather than by capturing
//! the screen: determinism means the recording *is* the round, so the reel
//! needs no render pipeline, no window and no timing luck, and lives beside
//! the sim as a headless rasterizer over board state (see [`crate::gif`]
//! for the encoder underneath).

use crate::gif::Gif;
use crate::sim::{
    Board, CrabKind, Direction, GullState, MAX_PLAYERS, PlayerId, Replay, TICKS_PER_SECOND,
    TileKind,
};

/// How much of the ending the reel keeps.
pub const REEL_SECONDS: u32 = 15;
/// Frames a second in the finished GIF.
const FPS: u32 = 10;
/// Sim ticks between captured frames.
const TICKS_PER_FRAME: u32 = TICKS_PER_SECOND / FPS;
/// Pixels per board tile.
const TILE: u32 = 16;
/// The zoom: how many tiles of board the reel frames.
const WINDOW_W: u8 = 9;
const WINDOW_H: u8 = 7;

/// Palette slots. Kept small and named so the drawing code reads as
/// colours rather than as magic numbers.
mod ink {
    pub const SAND: u8 = 0;
    pub const SAND_DARK: u8 = 1;
    pub const ROCK: u8 = 2;
    pub const WALL: u8 = 3;
    pub const KELP: u8 = 4;
    pub const POOL: u8 = 5;
    pub const LOG: u8 = 6;
    pub const HOLE: u8 = 7;
    pub const GULL: u8 = 8;
    pub const CRAB: u8 = 9;
    pub const GOLDEN: u8 = 10;
    pub const GIANT: u8 = 11;
    /// Seat colours occupy the last slots, one per seat. They restate
    /// `app::palette`'s flag colours as raw bytes, because this module is
    /// engine-free and that one speaks `bevy::Color`; a test holds the two
    /// in step.
    pub const SEAT: u8 = 12;
}

const PALETTE: [[u8; 3]; 18] = [
    [222, 196, 148], // sand
    [206, 180, 132], // sand, the darker checker
    [96, 96, 104],   // rock
    [82, 62, 44],    // wall
    [46, 132, 72],   // kelp
    [96, 168, 208],  // pool
    [122, 88, 54],   // driftwood log
    [56, 40, 30],    // spawner hole
    [244, 244, 250], // gull
    [214, 92, 60],   // crab
    [240, 206, 74],  // golden crab
    [150, 52, 44],   // giant crab
    [214, 68, 68],   // seat 1
    [64, 120, 202],  // seat 2
    [76, 176, 79],   // seat 3
    [227, 186, 58],  // seat 4
    [178, 102, 209], // seat 5
    [242, 140, 51],  // seat 6
];

/// The highest seat with a colour of its own, for clamping.
const MAX_SEAT: u8 = MAX_PLAYERS as u8 - 1;

/// A single frame's worth of palette indices.
struct Frame {
    pixels: Vec<u8>,
    width: u32,
    height: u32,
    /// Board tile at the frame's top-left corner.
    origin: (u8, u8),
}

impl Frame {
    fn new(origin: (u8, u8)) -> Frame {
        let (width, height) = (u32::from(WINDOW_W) * TILE, u32::from(WINDOW_H) * TILE);
        Frame {
            pixels: vec![ink::SAND; (width * height) as usize],
            width,
            height,
            origin,
        }
    }

    fn set(&mut self, x: u32, y: u32, color: u8) {
        if x < self.width && y < self.height {
            self.pixels[(y * self.width + x) as usize] = color;
        }
    }

    fn rect(&mut self, x: i64, y: i64, w: u32, h: u32, color: u8) {
        for dy in 0..h {
            for dx in 0..w {
                let (px, py) = (x + i64::from(dx), y + i64::from(dy));
                if px >= 0 && py >= 0 {
                    self.set(px as u32, py as u32, color);
                }
            }
        }
    }

    /// Where a board position in subunits lands in the frame, in pixels.
    /// Positions outside the window come back anyway (negative or large);
    /// [`Frame::rect`] clips them.
    fn at(&self, tile_x: f32, tile_y: f32) -> (i64, i64) {
        let x = (tile_x - f32::from(self.origin.0)) * TILE as f32;
        let y = (tile_y - f32::from(self.origin.1)) * TILE as f32;
        (x as i64, y as i64)
    }
}

/// Which seat's castle the reel should frame: the winner, or, if the round
/// ended level, whoever banked the most while the reel was running, and
/// the lower seat if that is level too. Only seats `in_play` count, and a
/// round nobody scored in has no leader to frame.
fn deciding_seat(
    final_scores: &[u32; MAX_PLAYERS],
    gains: &[u32; MAX_PLAYERS],
    in_play: impl Fn(usize) -> bool,
) -> Option<u8> {
    let seats = || (0..MAX_PLAYERS).filter(|&s| in_play(s));
    let best = seats().map(|s| final_scores[s]).max()?;
    if best == 0 {
        return None;
    }
    seats()
        .filter(|&s| final_scores[s] == best)
        // `max_by_key` keeps the last of a tie; reversed, the first.
        .rev()
        .max_by_key(|&s| gains[s])
        .map(|s| s as u8)
}

/// The tile the reel centres on: the deciding seat's keep on `board`, the
/// beach as it stands when the reel opens (Castle Swap hands keeps round
/// mid-round, so the round's starting board can name a rival's), or the
/// middle of the beach when nobody decided it.
fn reel_focus(
    board: &Board,
    final_scores: &[u32; MAX_PLAYERS],
    gains: &[u32; MAX_PLAYERS],
) -> (u8, u8) {
    let has_keep = |s: usize| board.castle_of(s as PlayerId).is_some();
    deciding_seat(final_scores, gains, has_keep)
        .and_then(|seat| board.castle_of(seat))
        .unwrap_or((board.width() / 2, board.height() / 2))
}

/// The window's top-left tile: centred on `focus`, nudged back inside the
/// board so the reel never frames empty space off the edge.
fn window_origin(board: &Board, focus: (u8, u8)) -> (u8, u8) {
    let clamp = |value: u8, window: u8, size: u8| {
        let half = window / 2;
        if size <= window {
            0
        } else {
            value.saturating_sub(half).min(size - window)
        }
    };
    (
        clamp(focus.0, WINDOW_W, board.width()),
        clamp(focus.1, WINDOW_H, board.height()),
    )
}

/// Draw one frame of board state.
fn draw(board: &Board, origin: (u8, u8)) -> Frame {
    let mut frame = Frame::new(origin);
    for row in 0..WINDOW_H {
        for col in 0..WINDOW_W {
            let (x, y) = (origin.0 + col, origin.1 + row);
            if x >= board.width() || y >= board.height() {
                continue;
            }
            let (px, py) = (u32::from(col) * TILE, u32::from(row) * TILE);
            // Widened first: two coordinates past 127 overflow a u8.
            let checker = if (u16::from(x) + u16::from(y)).is_multiple_of(2) {
                ink::SAND
            } else {
                ink::SAND_DARK
            };
            let (fill, inset) = match board.tile_at(x, y) {
                TileKind::Empty => (checker, 0),
                TileKind::Rock => (ink::ROCK, 2),
                TileKind::Kelp => (ink::KELP, 2),
                TileKind::Pool => (ink::POOL, 0),
                TileKind::Turnstile { .. } => (ink::LOG, 5),
                TileKind::Spawner(_) => (ink::HOLE, 3),
                TileKind::Castle(owner) => (ink::SEAT + owner.min(MAX_SEAT), 1),
            };
            if inset > 0 {
                frame.rect(i64::from(px), i64::from(py), TILE, TILE, checker);
            }
            frame.rect(
                i64::from(px + inset),
                i64::from(py + inset),
                TILE - 2 * inset,
                TILE - 2 * inset,
                fill,
            );
            // Walls ride the tile's edges, two pixels thick.
            for (dir, wx, wy, w, h) in [
                (Direction::Up, px, py, TILE, 2),
                (Direction::Down, px, py + TILE - 2, TILE, 2),
                (Direction::Left, px, py, 2, TILE),
                (Direction::Right, px + TILE - 2, py, 2, TILE),
            ] {
                if board.wall_at(x, y, dir) {
                    frame.rect(i64::from(wx), i64::from(wy), w, h, ink::WALL);
                }
            }
            // A signpost is a small chip in its owner's colour.
            if let Some(post) = board.signpost_at(x, y) {
                frame.rect(
                    i64::from(px + 5),
                    i64::from(py + 5),
                    6,
                    6,
                    ink::SEAT + post.owner.min(MAX_SEAT),
                );
            }
        }
    }
    for crab in board.crabs() {
        let (x, y) = creature_tile_pos(board, crab.tile, crab.dir, crab.progress);
        let (px, py) = frame.at(x, y);
        frame.rect(px + 4, py + 4, 8, 8, crab_ink(crab.kind));
    }
    // Crab Monopoly's crabs, off the beach and not yet banked: drawn where
    // they were picked up until they set off, then slid to the keep they
    // land in. Left out, half the beach vanished from the reel at the
    // event and the banker's score rose with nothing arriving.
    for flight in board.sweeping() {
        let crab = &flight.crab;
        let from = creature_tile_pos(board, crab.tile, crab.dir, crab.progress);
        let keep = board
            .castle_of(flight.owner)
            .map_or(from, |(x, y)| (f32::from(x), f32::from(y)));
        let span = flight.lands.saturating_sub(flight.launch).max(1) as f32;
        let t = (board.ticks().saturating_sub(flight.launch) as f32 / span).min(1.0);
        let (x, y) = (
            from.0 + (keep.0 - from.0) * t,
            from.1 + (keep.1 - from.1) * t,
        );
        let (px, py) = frame.at(x, y);
        frame.rect(px + 4, py + 4, 8, 8, crab_ink(crab.kind));
    }
    for gull in board.gulls() {
        let (x, y) = creature_tile_pos(board, gull.tile, gull.dir, gull.progress);
        let (px, py) = frame.at(x, y);
        let size = if matches!(gull.state, GullState::Flying { .. }) {
            12
        } else {
            10
        };
        frame.rect(px + 3, py + 3, size, size, ink::GULL);
    }
    frame
}

/// The colour a crab of this kind is drawn in.
fn crab_ink(kind: CrabKind) -> u8 {
    match kind {
        CrabKind::Golden => ink::GOLDEN,
        CrabKind::Giant => ink::GIANT,
        CrabKind::Common | CrabKind::Juvenile | CrabKind::Molting | CrabKind::Sparkling => {
            ink::CRAB
        }
    }
}

/// A creature's position in tile units, its part-way progress included.
fn creature_tile_pos(board: &Board, tile: u16, dir: Direction, progress: u16) -> (f32, f32) {
    let (x, y) = board.coords_u8(tile);
    let (dx, dy) = dir.offset();
    let t = f32::from(progress) / f32::from(crate::sim::SUBUNITS_PER_TILE);
    (f32::from(x) + dx as f32 * t, f32::from(y) + dy as f32 * t)
}

/// Build the reel for a finished round: re-simulate the replay, keep the
/// last [`REEL_SECONDS`], and encode it. `None` if the replay is too short
/// to have a board or an ending worth showing.
pub fn reel(replay: &Replay) -> Option<Vec<u8>> {
    if replay.inputs.is_empty() {
        return None;
    }
    let total = replay.inputs.len();
    let window = (REEL_SECONDS * TICKS_PER_SECOND) as usize;
    let start = total.saturating_sub(window);

    // Play it through for the final scores and for how much each seat
    // banked inside the window, the measure of "deciding", keeping the
    // board as the window opens to draw the reel from.
    let mut board = replay.level.board();
    let mut opening = None;
    for (tick, actions) in replay.inputs.iter().enumerate() {
        if tick == start {
            opening = Some(board.clone());
        }
        board.tick(actions);
    }
    let finals = *board.scores();
    let mut board = opening?;
    let at_start = *board.scores();
    let gains = std::array::from_fn(|s| finals[s].saturating_sub(at_start[s]));
    let focus = reel_focus(&board, &finals, &gains);

    // The window again, drawing every few ticks.
    let origin = window_origin(&board, focus);
    let (width, height) = (u32::from(WINDOW_W) * TILE, u32::from(WINDOW_H) * TILE);
    let mut gif = Gif::new(width as u16, height as u16, &PALETTE);
    let delay = (100 / FPS) as u16;
    let mut frames = 0;
    for (tick, actions) in replay.inputs.iter().enumerate().skip(start) {
        if (tick - start).is_multiple_of(TICKS_PER_FRAME as usize) {
            gif.add_frame(&draw(&board, origin).pixels, delay);
            frames += 1;
        }
        board.tick(actions);
    }
    // Hold on the final board for a beat, the way a highlight should end.
    gif.add_frame(&draw(&board, origin).pixels, delay * 15);
    frames += 1;
    (frames > 1).then(|| gif.finish())
}

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

    /// A crab Crab Monopoly is carrying home is still on the reel: where it
    /// was picked up while it waits, at its keep as it lands.
    #[test]
    fn a_swept_crab_stays_on_the_reel_until_it_lands() {
        let mut board = Board::new(9, 7, 5);
        board.rules_mut().sweep_flight = true;
        board.set_tile(7, 5, TileKind::Castle(1));
        board.spawn_crab(
            1,
            1,
            Direction::Down,
            crate::sim::Handedness::Left,
            CrabKind::Golden,
        );
        board.spawn_crab(
            2,
            1,
            Direction::Down,
            crate::sim::Handedness::Left,
            CrabKind::Common,
        );
        board.force_tide_event(crate::sim::TideEvent::Monopoly, 1);
        assert_eq!(board.sweeping().len(), 1, "the golden crab is in the air");
        let pixel = |frame: &Frame, x: u8, y: u8| {
            let (px, py) = (
                u32::from(x) * TILE + TILE / 2,
                u32::from(y) * TILE + TILE / 2,
            );
            frame.pixels[(py * frame.width + px) as usize]
        };
        let waiting = draw(&board, (0, 0));
        assert_eq!(pixel(&waiting, 1, 1), ink::GOLDEN, "where it was picked up");
        let lands = board.sweeping()[0].lands;
        while board.ticks() < lands {
            board.tick_idle();
        }
        assert_eq!(board.sweeping().len(), 1, "on its last tick in the air");
        let landing = draw(&board, (0, 0));
        assert_eq!(pixel(&landing, 7, 5), ink::GOLDEN, "at the keep");
    }

    /// The reel wears the same flags the match did. It cannot share the
    /// palette outright, that one being `bevy::Color` where this module is
    /// engine-free, so the two copies are held together here.
    #[test]
    fn the_reel_flies_the_games_own_flags() {
        for seat in 0..MAX_PLAYERS as u8 {
            let want = crate::app::palette::classic_color(seat).to_srgba();
            let want = [want.red, want.green, want.blue].map(|c| (c * 255.0).round() as i32);
            let got = PALETTE[(ink::SEAT + seat) as usize].map(i32::from);
            for channel in 0..3 {
                assert!(
                    (want[channel] - got[channel]).abs() <= 1,
                    "seat {seat} channel {channel}: reel {got:?} against game {want:?}"
                );
            }
        }
    }

    fn recorded_round(ticks: usize) -> Replay {
        let board = classic_arena_seeded(0x21EE1, false, 4);
        let mut replay = Replay::new(Level::from_board("Reel", 3, board.clone()));
        let mut board = board;
        for tick in 0..ticks {
            let mut actions = [PlayerAction::None; MAX_PLAYERS];
            if tick == 40 {
                actions[0] = PlayerAction::Place {
                    x: 4,
                    y: 4,
                    dir: Direction::Up,
                };
            }
            board.tick(&actions);
            replay.record(actions);
        }
        replay
    }

    #[test]
    fn a_reel_is_a_playable_gif() {
        let replay = recorded_round(900);
        let bytes = reel(&replay).expect("a round of that length has a reel");
        assert_eq!(&bytes[..6], b"GIF89a");
        assert_eq!(*bytes.last().expect("trailer"), 0x3B);
        // One frame per FPS-th of a second across the window, plus the hold.
        let frames = bytes.iter().filter(|&&b| b == 0x2C).count();
        assert!(
            frames >= (REEL_SECONDS * FPS) as usize,
            "expected a full window of frames, got {frames}"
        );
    }

    /// A round shorter than the window still produces a reel, of whatever
    /// there was.
    #[test]
    fn short_rounds_still_make_a_reel() {
        assert!(reel(&recorded_round(60)).is_some());
        assert!(reel(&recorded_round(0)).is_none(), "nothing to show");
    }

    /// The reel frames the winner's castle, and stays on the board.
    #[test]
    fn the_window_follows_the_deciding_castle() {
        let board = classic_arena_seeded(1, false, 4);
        // Seat 2's castle is at the bottom-right on the classic arena.
        let corner = board.castle_of(1).expect("seat 2 has a castle");
        let origin = window_origin(&board, corner);
        assert!(
            origin.0 + WINDOW_W <= board.width() && origin.1 + WINDOW_H <= board.height(),
            "the window stayed on the board: {origin:?}"
        );
        // A castle in the middle of a big board is centred exactly.
        let mut wide = Board::new(20, 13, 1);
        wide.set_tile(10, 6, TileKind::Castle(0));
        assert_eq!(window_origin(&wide, (10, 6)), (6, 3));
    }

    /// The far corner of the biggest board a byte can name draws: its
    /// checkerboard sum is past what a byte holds.
    #[test]
    fn a_window_far_out_on_a_huge_board_draws() {
        let mut huge = Board::new(255, 255, 1);
        huge.set_tile(250, 250, TileKind::Castle(0));
        let origin = window_origin(&huge, (250, 250));
        assert!(origin.0 > 128 && origin.1 > 128, "{origin:?}");
        let frame = draw(&huge, origin);
        assert!(!frame.pixels.is_empty());
    }

    #[test]
    fn the_deciding_seat_is_the_winner_then_the_late_surge() {
        let all = |_: usize| true;
        let decide = |finals, gains| deciding_seat(finals, gains, all);
        assert_eq!(decide(&[10, 40, 5, 0, 0, 0], &[0; MAX_PLAYERS]), Some(1));
        // A dead heat goes to whoever earned it in the closing seconds.
        assert_eq!(decide(&[40, 40, 0, 0, 0, 0], &[3, 9, 0, 0, 0, 0]), Some(1));
        assert_eq!(decide(&[40, 40, 0, 0, 0, 0], &[9, 3, 0, 0, 0, 0]), Some(0));
        // Level all the way through: the first seat, not the last.
        assert_eq!(decide(&[40, 40, 0, 0, 0, 0], &[5, 5, 0, 0, 0, 0]), Some(0));
    }

    /// A round nobody scored in has no leader, and an empty chair is never
    /// one: before, a scoreless round framed seat 6, which on a two-seat
    /// beach has no keep.
    #[test]
    fn a_scoreless_round_or_an_empty_chair_decides_nothing() {
        let two = |s: usize| s < 2;
        assert_eq!(
            deciding_seat(&[0; MAX_PLAYERS], &[0; MAX_PLAYERS], two),
            None
        );
        assert_eq!(
            deciding_seat(&[3, 0, 0, 0, 0, 9], &[0; MAX_PLAYERS], two),
            Some(0),
            "seat 6 is not at the table"
        );
        let board = classic_arena_seeded(1, false, 2);
        let middle = (board.width() / 2, board.height() / 2);
        assert_eq!(
            reel_focus(&board, &[0; MAX_PLAYERS], &[0; MAX_PLAYERS]),
            middle
        );
    }

    /// The reel frames the winner's keep where it is when the reel opens:
    /// after a Castle Swap that is not where it stood at the start of the
    /// round.
    #[test]
    fn the_reel_frames_the_keep_the_winner_holds_now() {
        let mut board = Board::new(20, 13, 1);
        board.set_tile(1, 1, TileKind::Castle(1));
        board.set_tile(18, 11, TileKind::Castle(0));
        let finals = [0, 40, 0, 0, 0, 0];
        assert_eq!(reel_focus(&board, &finals, &[0; MAX_PLAYERS]), (1, 1));
    }
}