pinch-points 0.6.0

A fast, kid-friendly crab-routing game: route streams of crabs into your sandcastle before the tide comes in
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
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
//! Castles: their tier-scaled keep, the pennant on top, and the shudder
//! and floating points a bank sets off.

use super::{WALL_COLOR, image_sprite, on_board, z};
use crate::app::Sim;
use crate::app::art::Art;
use crate::app::layout::{self, TILE};
use crate::app::palette;
use crate::sim::{TileKind, castle_tier};
use bevy::prelude::*;

/// Marker for a castle's sprite tree; carries the tier it was built at so a
/// score crossing a threshold rebuilds it (spec ยง3.4: the castle grows with
/// score and doubles as the scoreboard).
#[derive(Component)]
pub struct CastleSprite {
    x: u8,
    y: u8,
    tier: u8,
    /// Whose it is. Kept because the castle wears its owner's colour and a
    /// tide event can hand it to somebody else without its tier moving: on
    /// tier alone the sprite stands in the old owner's colour until the new
    /// one scores across a threshold.
    owner: u8,
}

pub fn sync_castles(
    mut commands: Commands,
    sim: Res<Sim>,
    art: Res<Art>,
    mut covered: Local<Vec<bool>>,
    existing: Query<(Entity, &CastleSprite)>,
) {
    let board = &sim.0;
    covered.clear();
    covered.resize(board.width() as usize * board.height() as usize, false);
    for (entity, sprite) in &existing {
        if !on_board(board, sprite.x, sprite.y) {
            commands.entity(entity).despawn();
            continue;
        }
        let idx = usize::from(board.index_of(sprite.x, sprite.y));
        match board.tile_at(sprite.x, sprite.y) {
            TileKind::Castle(owner)
                if owner == sprite.owner
                    && castle_tier(board.scores()[owner as usize]) == sprite.tier =>
            {
                covered[idx] = true;
            }
            TileKind::Castle(_)
            | TileKind::Empty
            | TileKind::Rock
            | TileKind::Spawner(_)
            | TileKind::Turnstile { .. }
            | TileKind::Kelp
            | TileKind::Pool => {
                commands.entity(entity).despawn();
            }
        }
    }
    for (x, y, kind) in board.tiles() {
        let idx = usize::from(board.index_of(x, y));
        if covered[idx] {
            continue;
        }
        let TileKind::Castle(owner) = kind else {
            continue;
        };
        let tier = castle_tier(board.scores()[owner as usize]);
        let color = palette::player_color(owner);
        let pos = layout::tile_center(board, x, y);
        let base_size = TILE * (0.55 + 0.12 * f32::from(tier));
        commands
            .spawn((
                CastleSprite { x, y, tier, owner },
                CastleKick(0.0),
                image_sprite(&art.castle, color, Vec2::splat(base_size * 1.12)),
                Transform::from_translation(pos.extend(z::TILE_FEATURE + 0.2)),
            ))
            .with_children(|parent| {
                // The keep sits on the sand rather than in it.
                parent.spawn((
                    image_sprite(
                        &art.shadow,
                        Color::srgba(1.0, 1.0, 1.0, 0.7),
                        Vec2::splat(base_size * 1.3),
                    ),
                    Transform::from_translation(layout::SUN.extend(-0.3)),
                ));
                if tier >= 1 {
                    // The curtain wall the first tier throws up: a
                    // battlemented ring, hollow, with the keep inside it.
                    parent.spawn((
                        image_sprite(&art.keep_ring, color.darker(0.12), Vec2::splat(TILE * 0.99)),
                        Transform::from_translation(Vec3::new(0.0, 0.0, -0.1)),
                    ));
                }
                if tier >= 2 {
                    // Bucket-moulded corner towers on the front wall.
                    for side in [-1.0, 1.0] {
                        parent.spawn((
                            image_sprite(
                                &art.turret,
                                color.lighter(0.10),
                                Vec2::splat(TILE * 0.28),
                            ),
                            Transform::from_translation(Vec3::new(
                                side * base_size * 0.42,
                                base_size * 0.42,
                                0.1,
                            )),
                        ));
                    }
                }
                if tier >= 3 {
                    // The moat, dug outermost: water with its own ripples,
                    // open in the middle where the keep stands.
                    parent.spawn((
                        image_sprite(&art.moat, Color::WHITE, Vec2::splat(TILE * 1.06)),
                        Transform::from_translation(Vec3::new(0.0, 0.0, -0.2)),
                    ));
                }
                // Pennant on top; every tier flies the flag.
                // The flag (spec ยง3.4: flying their colour flag): a
                // driftwood pole with a bright owner-coloured pennant,
                // sticking up past the keep so it reads at a glance.
                let pole_height = TILE * 0.34;
                let pole_top = base_size * 0.5 + pole_height;
                parent.spawn((
                    Sprite::from_color(WALL_COLOR, Vec2::new(2.5, pole_height)),
                    Transform::from_translation(Vec3::new(
                        -TILE * 0.06,
                        base_size * 0.5 + pole_height / 2.0,
                        0.3,
                    )),
                ));
                parent.spawn((
                    Pennant,
                    Sprite::from_color(color.lighter(0.22), Vec2::new(TILE * 0.20, TILE * 0.12)),
                    Transform::from_translation(Vec3::new(
                        -TILE * 0.06 + TILE * 0.11,
                        pole_top - TILE * 0.05,
                        0.3,
                    )),
                ));
            });
    }
}

/// A castle's flag; waves gently in the sea breeze.
#[derive(Component)]
pub struct Pennant;

/// A scale wobble on a castle when a crab banks there (the original's
/// rocket shudder). Set to 1.0 on a bank, decays to rest.
#[derive(Component)]
pub struct CastleKick(pub f32);

/// How long the castles are in the air when the tide swaps them.
const FLIGHT: f32 = 1.1;

/// How much bigger a castle looks at the top of its flight. The path is a
/// straight line, so this is the only thing saying it is off the ground
/// rather than sliding along the sand.
const RISE: f32 = 0.30;

/// The swap animation: how long is left, and where each castle is flying
/// from.
///
/// A resource and not a component because a castle changing hands is
/// rebuilt by [`sync_castles`] mid-flight (new owner, new colour, often a
/// new tier), and a component would go down with the entity it was on.
#[derive(Resource, Default)]
pub struct CastleFlight {
    left: f32,
    /// Where each castle in the air set off from. Empty when none is.
    from: Vec<Flight>,
}

/// One castle's journey: the tile it is landing on, and where it left.
pub struct Flight {
    tile: (u8, u8),
    from: Vec2,
}

/// The swap detector's memory: the castles as they stood last frame, and
/// the board clock they stood on.
///
/// The clock is what tells a new board from the old one. Without it a match
/// that ended on a CastleSwap leaves the swapped layout here, and the next
/// round on the same map reads as a swap on its first frame.
#[derive(Default)]
pub struct Detector {
    ticks: u64,
    held: Vec<Held>,
}

impl Detector {
    /// Whether `board` is a different board from the one remembered: the
    /// clock rolled back (a fresh round or level, whose clock starts at 0)
    /// or the beach changed size under it. Either way what is remembered
    /// says nothing about this board.
    fn is_fresh(&self, board: &crate::sim::Board) -> bool {
        board.ticks() < self.ticks
            || self
                .held
                .iter()
                .any(|held| !on_board(board, held.x, held.y))
    }
}

/// A castle as the swap detector sees it: whose it is, and where.
///
/// Named because the comparison that spots a swap is about which of these
/// changed and which did not, and in `(u8, u8, u8)` the two coordinates and
/// the owner are the same type.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Held {
    x: u8,
    y: u8,
    owner: u8,
}

/// Where a castle is, and how big it looks, `progress` of the way from
/// `from` to `home`.
///
/// Split out because it has to start exactly on one tile and finish exactly
/// on the other, or a castle lands off its own sand.
fn hop(from: Vec2, home: Vec2, progress: f32) -> (Vec2, f32) {
    // A straight line between the two tiles, eased out of the launch and
    // into the landing so it reads as a thing setting off and arriving
    // rather than a thing being dragged.
    let eased = progress * progress * (3.0 - 2.0 * progress);
    // Up off the sand and back down onto it, in scale alone: zero at both
    // ends, so the castle finishes exactly the size it started.
    let height = (progress * std::f32::consts::PI).sin();
    (from.lerp(home, eased), 1.0 + RISE * height)
}

/// Fly the castles to their new places when the tide swaps them round.
///
/// The sim hands each castle to the next owner where it stands: nothing
/// moves, the colours change. That is right for the round and wrong for
/// the eye, so the render layer says it the other way about: your castle
/// *travels* to where the next one was, over the sand, and lands wearing
/// the colour it took off in.
///
/// The swap is spotted by watching the board rather than by listening for
/// the tide event. The event is raised by the snapshot comparison a tick
/// behind the board it describes, so by the time it arrives a castle asked
/// where it came from answers "here"; watching for the same castles on the
/// same tiles under different owners cannot be mistimed.
///
/// Runs after [`kick_castles`], which also writes scale: a bank landing in
/// the same frame as a swap should not fight the flight for the transform.
///
/// A fresh board (see [`Detector::is_fresh`]) empties both the memory and
/// any flight still in the air, so a round that ends mid-swap leaves
/// nothing to land on the next beach. Done here rather than on screen exit
/// because a rematch on the same map is a board swap with no screen change
/// in it.
pub fn fly_castles(
    time: Res<Time>,
    sim: Res<Sim>,
    settings: Res<crate::app::settings::GameSettings>,
    mut flight: ResMut<CastleFlight>,
    mut before: Local<Detector>,
    // Swapped with the last reading rather than built fresh each frame.
    mut now: Local<Vec<Held>>,
    mut castles: Query<(&CastleSprite, &mut Transform)>,
) {
    let board = &sim.0;
    if before.is_fresh(board) {
        before.held.clear();
        flight.from.clear();
        flight.left = 0.0;
    }
    before.ticks = board.ticks();
    now.clear();
    now.extend(board.tiles().filter_map(|(x, y, kind)| match kind {
        TileKind::Castle(owner) => Some(Held { x, y, owner }),
        TileKind::Empty
        | TileKind::Rock
        | TileKind::Spawner(_)
        | TileKind::Turnstile { .. }
        | TileKind::Kelp
        | TileKind::Pool => None,
    }));
    if swapped(&before.held, &now) && !settings.reduced_motion {
        flight.from.clear();
        let mut old = before.held.clone();
        for held in now.iter() {
            // An owner with two castles has them paired in board order,
            // which is arbitrary but consistent, and nothing crosses.
            if let Some(at) = old.iter().position(|was| was.owner == held.owner) {
                let was = old.remove(at);
                flight.from.push(Flight {
                    tile: (held.x, held.y),
                    from: layout::tile_center(board, was.x, was.y),
                });
            }
        }
        flight.left = FLIGHT;
    }
    std::mem::swap(&mut before.held, &mut now);
    if flight.left <= 0.0 {
        return;
    }
    flight.left = (flight.left - time.delta_secs()).max(0.0);
    let progress = 1.0 - flight.left / FLIGHT;
    for (sprite, mut transform) in &mut castles {
        let home = layout::tile_center(board, sprite.x, sprite.y);
        let from = flight
            .from
            .iter()
            .find(|flight| flight.tile == (sprite.x, sprite.y))
            .map_or(home, |flight| flight.from);
        let (at, scale) = hop(from, home, progress);
        transform.translation.x = at.x;
        transform.translation.y = at.y;
        transform.scale = Vec3::splat(scale);
    }
    if flight.left == 0.0 {
        // Landed: hand the transform back exactly as it was found, so
        // nothing downstream inherits a fraction of a scale.
        flight.from.clear();
        for (sprite, mut transform) in &mut castles {
            let home = layout::tile_center(board, sprite.x, sprite.y);
            transform.translation = home.extend(transform.translation.z);
            transform.scale = Vec3::ONE;
        }
    }
}

/// Whether the castles changed hands: the same tiles holding the same
/// owners between them, dealt out differently.
///
/// Deliberately narrow: a castle built, a castle lost or a score crossing a
/// tier all change this list too, and only a permutation of who holds what
/// is a swap.
fn swapped(before: &[Held], now: &[Held]) -> bool {
    if before.len() < 2 || before.len() != now.len() || before == now {
        return false;
    }
    let tiles = |list: &[Held]| {
        let mut out: Vec<(u8, u8)> = list.iter().map(|held| (held.x, held.y)).collect();
        out.sort_unstable();
        out
    };
    let owners = |list: &[Held]| {
        let mut out: Vec<u8> = list.iter().map(|held| held.owner).collect();
        out.sort_unstable();
        out
    };
    tiles(before) == tiles(now) && owners(before) == owners(now)
}

/// What each seat banked over one frame's events, added up.
///
/// The sim reports a bank per crab, and a castle can take several on one
/// tick: eight, measured over a set of six-seat rounds. [`score_pip`] has
/// no jitter in it, so a pip per crab puts eight identical `+1`s pixel on
/// pixel and the player who banked eight reads one `+1` drawn too dark.
///
/// Summed instead: `+8` is the number that happened, and this is the only
/// place it is ever shown.
///
/// [`score_pip`]: crate::app::effects::score_pip
fn gains<'a>(
    events: impl IntoIterator<Item = &'a crate::app::sim_events::SimEvent>,
) -> [u32; crate::sim::MAX_PLAYERS] {
    use crate::app::sim_events::SimEvent;
    let mut gained = [0u32; crate::sim::MAX_PLAYERS];
    for event in events {
        if let SimEvent::CrabBanked { owner, value, .. } = event
            && let Some(total) = gained.get_mut(usize::from(*owner))
        {
            *total = total.saturating_add(*value);
        }
    }
    gained
}

/// Bounce the owner's castle on every bank and float the points gained
/// over the keep, in the owner's colour.
pub fn kick_castles(
    mut commands: Commands,
    mut events: MessageReader<crate::app::sim_events::SimEvent>,
    sim: Res<Sim>,
    time: Res<Time>,
    settings: Res<crate::app::settings::GameSettings>,
    mut castles: Query<(&CastleSprite, &mut CastleKick, &mut Transform)>,
) {
    let board = &sim.0;
    // Reduced motion keeps the floating points and drops the bounce.
    let calm = settings.reduced_motion;
    let gained = gains(events.read());
    for (sprite, mut kick, _) in &mut castles {
        // A stranded sprite (off this board) is `sync_castles`'s to
        // remove; it has no tile to read.
        if !on_board(board, sprite.x, sprite.y) {
            continue;
        }
        let TileKind::Castle(owner) = board.tile_at(sprite.x, sprite.y) else {
            continue;
        };
        let Some(&points) = gained.get(usize::from(owner)) else {
            continue;
        };
        if points == 0 {
            continue;
        }
        kick.0 = if calm { 0.0 } else { 1.0 };
        crate::app::effects::score_pip(
            &mut commands,
            format!("+{points}"),
            layout::tile_center(board, sprite.x, sprite.y) + Vec2::new(0.0, TILE * 0.35),
            palette::player_color(owner).lighter(0.15),
        );
    }
    let dt = time.delta_secs();
    for (_, mut kick, mut transform) in &mut castles {
        if kick.0 <= 0.0 {
            continue;
        }
        kick.0 = (kick.0 - dt * 3.2).max(0.0);
        // A quick squash-and-settle: overshoot then ease back.
        let wobble = 1.0 + 0.20 * kick.0 * (kick.0 * std::f32::consts::PI * 2.0).sin().abs();
        transform.scale = Vec3::splat(wobble);
    }
}

/// A castle that just grew says so.
///
/// [`castle_tier`] is the whole scoreboard (spec ยง3.4), and without this a
/// castle crossing a threshold changes shape between one frame and the next
/// with nothing to mark it.
///
/// Runs after [`sync_castles`], and must: the sprite being cheered is the
/// one built at the *new* tier, and the events reaching this frame are the
/// previous frame's (see the `Frame` sets), so it is already standing.
#[allow(clippy::too_many_arguments)]
pub fn cheer_tier_ups(
    mut commands: Commands,
    mut events: MessageReader<crate::app::sim_events::SimEvent>,
    sim: Res<Sim>,
    art: Res<Art>,
    settings: Res<crate::app::settings::GameSettings>,
    mut rng: ResMut<crate::app::effects::VisualRng>,
    mut trauma: ResMut<crate::app::effects::Trauma>,
    mut castles: Query<(&CastleSprite, &mut CastleKick)>,
) {
    use crate::app::effects::{Burst, burst, ring};
    use crate::app::sim_events::SimEvent;
    let board = &sim.0;
    for event in events.read() {
        let SimEvent::TierUp { owner } = event else {
            continue;
        };
        // The growth itself is the news and it survives reduced motion;
        // only the fireworks over it stand down.
        if settings.reduced_motion {
            continue;
        }
        for (sprite, mut kick) in &mut castles {
            if sprite.owner != *owner || !on_board(board, sprite.x, sprite.y) {
                continue;
            }
            let at = layout::tile_center(board, sprite.x, sprite.y);
            let color = palette::player_color(*owner);
            ring(
                &mut commands,
                &art,
                at,
                color.lighter(0.25),
                TILE * 0.8,
                2.6,
                0.55,
            );
            burst(
                &mut commands,
                &mut rng,
                &Burst {
                    image: art.puff.clone(),
                    pos: at,
                    color: Color::srgba(0.95, 0.9, 0.76, 0.9),
                    count: 9,
                    size: 15.0,
                    speed: 62.0,
                    gravity: 55.0,
                },
            );
            for _ in 0..4 {
                crate::app::effects::glint(&mut commands, &mut rng, &art, at, color.lighter(0.4));
            }
            kick.0 = 1.0;
        }
        trauma.add(0.2);
    }
}

/// Flutter every pennant: a small shear-like x-scale ripple plus a slight
/// tilt, phased per entity so flags do not wave in lockstep.
pub fn wave_pennants(time: Res<Time>, mut flags: Query<(Entity, &mut Transform), With<Pennant>>) {
    let t = time.elapsed_secs();
    for (entity, mut transform) in &mut flags {
        let phase = f32::from(entity.to_bits() as u16 % 17);
        transform.scale.x = 1.0 + (t * 5.0 + phase).sin() * 0.12;
        transform.rotation = Quat::from_rotation_z((t * 3.0 + phase).sin() * 0.08);
    }
}

#[cfg(test)]
mod tests {
    use super::{gains, hop};
    use crate::app::sim_events::SimEvent;
    use crate::sim::{CrabKind, MAX_PLAYERS};
    use bevy::prelude::*;

    /// A crab of `kind` worth `value` walking into `owner`'s keep.
    fn bank(owner: u8, value: u32) -> SimEvent {
        SimEvent::CrabBanked {
            id: 0,
            owner,
            pos: Vec2::ZERO,
            keep: Vec2::ZERO,
            value,
            kind: CrabKind::Common,
        }
    }

    /// The floating number is the only place a bank's worth is ever shown,
    /// so on a frame that banked eight it has to say eight.
    ///
    /// Said as `+1` eight times it lands in the same place at the same
    /// speed, since `score_pip` has no jitter: the copies rise as one and
    /// the number is simply wrong, drawn a little too dark.
    #[test]
    fn a_frame_of_banks_floats_one_number_and_it_is_the_total() {
        assert_eq!(gains([]), [0; MAX_PLAYERS], "a quiet frame gains nobody");
        assert_eq!(gains(&[bank(1, 3)])[1], 3, "one crab is worth its own");
        let stream: Vec<SimEvent> = (0..8).map(|_| bank(1, 1)).collect();
        assert_eq!(
            gains(&stream)[1],
            8,
            "eight into one keep is eight, not eight ones"
        );
        // Crabs are not all worth the same, so this is a sum and not a
        // count: a golden one is fifty walking.
        assert_eq!(gains(&[bank(2, 50), bank(2, 1)])[2], 51);
    }

    /// Seats are added up apart. Six castles filling on one tick is six
    /// numbers over six keeps, and each of them is that keep's own.
    #[test]
    fn every_seat_is_counted_over_its_own_keep() {
        let frame: Vec<SimEvent> = vec![bank(0, 1), bank(3, 2), bank(0, 4), bank(3, 1)];
        let gained = gains(&frame);
        assert_eq!(gained[0], 5, "two crabs home");
        assert_eq!(gained[3], 3);
        assert_eq!(
            gained[1], 0,
            "and a seat that banked nothing floats nothing"
        );
        assert_eq!(gained.iter().sum::<u32>(), 8, "nothing counted twice");
        // A seat past the end of the table is dropped rather than indexed
        // off it: the owner rides in on an observed event, and every other
        // reader of one is careful about that.
        let stray = gains(&[bank(MAX_PLAYERS as u8, 9), bank(u8::MAX, 9)]);
        assert_eq!(stray, [0; MAX_PLAYERS], "no seat, no number");
    }

    /// The two ends are the point: a castle that lands a few pixels off
    /// its tile stays there until something else redraws it.
    #[test]
    fn a_hop_starts_and_finishes_on_the_sand() {
        let from = Vec2::new(-100.0, 40.0);
        let home = Vec2::new(220.0, -60.0);
        let (start, start_scale) = hop(from, home, 0.0);
        assert_eq!(start, from);
        assert!((start_scale - 1.0).abs() < 1e-6);
        let (end, end_scale) = hop(from, home, 1.0);
        assert!(end.distance(home) < 1e-3, "{end:?} vs {home:?}");
        assert!((end_scale - 1.0).abs() < 1e-6);
    }

    /// Only a permutation is a swap. A castle built, lost, or crossing a
    /// tier changes the list too, and animating those as flights would
    /// have castles sliding in from wherever the last one happened to be.
    #[test]
    fn only_a_reshuffle_counts_as_a_swap() {
        let held = |x, y, owner| super::Held { x, y, owner };
        let a = vec![held(1, 1, 0), held(5, 1, 1)];
        let swapped_pair = vec![held(1, 1, 1), held(5, 1, 0)];
        assert!(super::swapped(&a, &swapped_pair));
        assert!(!super::swapped(&a, &a), "nothing moved");
        assert!(!super::swapped(&[], &a), "the first frame is not a swap");
        assert!(
            !super::swapped(&a, &[held(1, 1, 0), held(5, 1, 1), held(9, 1, 2)]),
            "a castle was built"
        );
        assert!(
            !super::swapped(&a, &[held(1, 1, 0), held(7, 1, 1)]),
            "a castle moved tile, which the sim never does"
        );
        assert!(
            !super::swapped(&a, &[held(1, 1, 0), held(5, 1, 2)]),
            "a different owner turned up"
        );
        assert!(
            !super::swapped(&[held(1, 1, 0)], &[held(1, 1, 1)]),
            "one castle cannot swap with itself"
        );
    }

    /// A round that ends on a swap must not fly the next round's castles
    /// from where the last one left them: a board whose clock rolled
    /// back, or that shrank under the remembered castles, is a fresh one.
    #[test]
    fn a_new_round_forgets_the_last_layout() {
        let held = |x, y, owner| super::Held { x, y, owner };
        let mut board = crate::sim::Board::new(12, 9, 1);
        for _ in 0..50 {
            board.tick_idle();
        }
        let detector = super::Detector {
            ticks: board.ticks(),
            held: vec![held(1, 1, 0), held(10, 7, 1)],
        };
        assert!(!detector.is_fresh(&board), "the same board, ticking on");
        let next_round = crate::sim::Board::new(12, 9, 2);
        assert!(detector.is_fresh(&next_round), "the clock rolled back");
        let mut smaller = crate::sim::Board::new(9, 7, 1);
        for _ in 0..80 {
            smaller.tick_idle();
        }
        assert!(
            detector.is_fresh(&smaller),
            "a castle remembered off this board says the board changed"
        );
    }

    /// Straight between the two tiles, never off the line: a castle that
    /// bowed upwards would fly over the wall on a corner-to-corner swap.
    #[test]
    fn a_hop_travels_in_a_straight_line() {
        let from = Vec2::new(0.0, 0.0);
        let home = Vec2::new(400.0, 200.0);
        for step in 0..=10 {
            let progress = step as f32 / 10.0;
            let (at, _) = hop(from, home, progress);
            // Every point is on the segment: y is exactly half of x, which
            // is what the two ends say it should be.
            assert!((at.y - at.x * 0.5).abs() < 1e-3, "{at:?} at {progress}");
        }
        // And it is off the ground in between, which is the only thing
        // saying it is flying rather than sliding.
        assert!(hop(from, home, 0.5).1 > 1.0);
    }
}