use crate::buffer::Cell;
use crate::canvas::Canvas;
use crate::common::{DEFAULT_SEED, EffectRng, TerminalEffect, seeded_rng};
use crate::terrain::noise::PerlinNoise;
use crossterm::style;
use rand::RngExt;
use serde::{Deserialize, Serialize};
use std::sync::LazyLock;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Direction {
Left,
Right,
}
const WALK_POSES: usize = 3;
const POSES: usize = WALK_POSES + 1;
const CLAP_POSE: usize = WALK_POSES;
const SPRITE_ROWS: usize = 4;
const RIGHT_POSES: [[&str; SPRITE_ROWS]; POSES] = [
[
r" _~^~^~^~_ ",
r"\) / o o \ (/",
r" '_ ¬ _' ",
r" \ '-----' / ",
],
[
r" _~^~^~^~_ ",
r"\/ / o o \ (/",
r" '_ ¬ _' ",
r" | '-----' | ",
],
[
r" _~^~^~^~_ ",
r"\) / o o \ \/",
r" '_ ¬ _' ",
r" / '-----' \ ",
],
[
r" _~^~^~^~_ ",
r"\/ / o o \ \/",
r" '_ u _' ",
r" \ '-----' / ",
],
];
fn mirror(line: &str) -> String {
line.chars().rev().collect()
}
static CRAB_FRAMES: LazyLock<Vec<Vec<String>>> = LazyLock::new(|| {
let mut frames: Vec<Vec<String>> = RIGHT_POSES
.iter()
.map(|pose| pose.iter().map(|line| line.to_string()).collect())
.collect();
frames.extend(
RIGHT_POSES
.iter()
.map(|pose| pose.iter().map(|line| mirror(line)).collect()),
);
frames
});
fn sprite_width(rows: &[&str]) -> usize {
rows.iter()
.map(|line| line.chars().count())
.max()
.unwrap_or(0)
}
fn sprite() -> (usize, usize) {
let width = sprite_width(&RIGHT_POSES[0]);
(width, SPRITE_ROWS)
}
const SAND: &[char] = &['-', '~', '.', '~', '-', '.'];
const SAND_COLOUR: style::Color = style::Color::Rgb {
r: 104,
g: 88,
b: 62,
};
const SHADOW_COLOUR: style::Color = style::Color::Rgb {
r: 44,
g: 37,
b: 26,
};
const SHADOW_GLYPH: char = '_';
const WALK_GAIN: f32 = 1.0;
const WALK_SPEED_RANGE: (f32, f32) = (0.7, 1.3);
const HOP_SPEED: f32 = 9.0;
const GRAVITY: f32 = 22.0;
const HOP_INTERVAL: (f32, f32) = (1.4, 5.0);
fn touch_distance() -> f32 {
sprite().0 as f32 + 2.0
}
const MIN_SEPARATION: f32 = 6.0;
fn separation(screen_width: u16, count: usize) -> f32 {
if count < 2 {
return 0.0;
}
let span = right_edge(screen_width, sprite().0);
MIN_SEPARATION.min(span / count as f32)
}
#[derive(Clone)]
struct CrabEntity {
position: (f32, f32), velocity: (f32, f32), direction: Direction, current_frame: usize, animation_timer: f32, special_timer: f32, is_special: bool, hop_timer: f32, color: style::Color, airborne: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct CrabOptions {
#[serde(skip)]
pub crab_count: u16,
pub animation_speed: f32,
pub clap_duration: f32,
pub clap_chance: f32,
pub movement_speed: f32,
pub crab_coeff: f32,
pub seed: u64,
pub seabed_amplitude: f32,
pub seabed_period: f64,
}
impl Default for CrabOptions {
fn default() -> Self {
Self {
crab_count: 5,
animation_speed: 0.4,
clap_duration: 0.6,
clap_chance: 0.05,
movement_speed: 3.0,
crab_coeff: 1.0,
seed: DEFAULT_SEED,
seabed_amplitude: 21.0,
seabed_period: 500.0,
}
}
}
struct Seabed {
noise: PerlinNoise,
height: usize,
amplitude: f32,
period: f64,
offset: f64,
}
impl Seabed {
fn new(options: &CrabOptions, height: usize) -> Self {
Self {
noise: PerlinNoise::new(options.seed ^ SEABED_SEED_SALT),
height,
amplitude: if options.seabed_amplitude.is_finite() {
options.seabed_amplitude.max(0.0)
} else {
0.0
},
period: if options.seabed_period.is_finite()
&& options.seabed_period > 0.0
{
options.seabed_period
} else {
CrabOptions::default().seabed_period
},
offset: 0.0,
}
}
fn base_row(&self) -> f32 {
self.height as f32 - 1.0 - SPRITE_ROWS as f32
}
fn row_at(&self, x: f32) -> f32 {
let base = self.base_row();
if self.amplitude <= 0.0 {
return base.max(0.0);
}
let height = self.noise.octave_noise_2d(
x as f64 + self.offset,
0.0,
SEABED_OCTAVES,
SEABED_PERSISTENCE,
1.0 / self.period,
) as f32;
(base - height * self.amplitude).clamp(0.0, base.max(0.0))
}
fn sand_at(&self, x: f32) -> usize {
let foot = self.row_at(x) + SPRITE_ROWS as f32 - 1.0;
(foot.round() as isize).clamp(0, self.height as isize - 1) as usize
}
fn advance(&mut self, delta: f64, walk_speed: f64) {
self.offset += walk_speed * delta;
}
}
const SEABED_OCTAVES: i32 = 2;
const SEABED_PERSISTENCE: f64 = 0.5;
const SEABED_SEED_SALT: u64 = 0x5EA8_ED00_D15E_ABED;
pub struct Crab {
pub screen_size: (u16, u16),
options: CrabOptions,
canvas: Canvas,
crabs: Vec<CrabEntity>,
rng: EffectRng,
frame_timer: f32,
seabed: Seabed,
}
impl CrabEntity {
fn new(
position: (f32, f32),
velocity: (f32, f32),
hop_timer: f32,
rng: &mut EffectRng,
) -> Self {
let direction = if velocity.0 >= 0.0 {
Direction::Right
} else {
Direction::Left
};
let color = style::Color::Rgb {
r: rng.random_range(200..=255),
g: rng.random_range(50..=150),
b: rng.random_range(50..=100),
};
Self {
position,
velocity,
direction,
current_frame: 0,
animation_timer: 0.0,
special_timer: 0.0,
is_special: false,
airborne: false,
hop_timer,
color,
}
}
fn frame_index(&self) -> usize {
let pose = if self.is_special {
CLAP_POSE
} else {
self.current_frame % WALK_POSES
};
pose + match self.direction {
Direction::Right => 0,
Direction::Left => POSES,
}
}
fn frame_lines(&self) -> &[String] {
&CRAB_FRAMES[self.frame_index()]
}
#[allow(clippy::too_many_arguments)]
fn update(
&mut self,
dt: f32,
screen_size: (u16, u16),
seabed: &Seabed,
animation_speed: f32,
clap_duration: f32,
movement_speed: f32,
clap_chance: f32,
rng: &mut EffectRng,
) {
let (width, _height) = sprite();
let _ = screen_size;
self.position.0 += self.velocity.0 * movement_speed * WALK_GAIN * dt;
let ground = seabed.row_at(self.position.0);
if self.position.1 < ground {
self.velocity.1 += GRAVITY * dt;
}
self.position.1 += self.velocity.1 * dt;
let max_x = right_edge(screen_size.0, width);
if self.position.0 < 0.0 {
self.position.0 = 0.0;
self.velocity.0 =
rng.random_range(WALK_SPEED_RANGE.0..WALK_SPEED_RANGE.1);
} else if self.position.0 > max_x {
self.position.0 = max_x;
self.velocity.0 =
-rng.random_range(WALK_SPEED_RANGE.0..WALK_SPEED_RANGE.1);
}
if self.position.1 >= ground {
self.position.1 = ground;
self.velocity.1 = 0.0;
self.airborne = false;
}
if self.position.1 < 0.0 {
self.position.1 = 0.0;
self.velocity.1 = 0.0;
}
if self.velocity.0 > 0.0 {
self.direction = Direction::Right;
} else if self.velocity.0 < 0.0 {
self.direction = Direction::Left;
}
let is_moving = self.velocity.0.abs() > 0.1 || self.position.1 < ground;
if is_moving {
self.animation_timer += dt;
let interval = if animation_speed > 0.0 {
animation_speed
} else {
CrabOptions::default().animation_speed
};
if self.animation_timer >= interval {
self.animation_timer = 0.0;
self.current_frame = (self.current_frame + 1) % WALK_POSES;
}
} else {
self.animation_timer = 0.0;
self.current_frame = 0;
}
if self.is_special {
self.special_timer -= dt;
if self.special_timer <= 0.0 {
self.is_special = false;
}
} else if rng.random::<f32>() < clap_chance * dt {
self.is_special = true;
self.special_timer = clap_duration;
}
self.hop_timer -= dt;
if self.hop_timer <= 0.0 {
self.hop_timer = rng.random_range(HOP_INTERVAL.0..HOP_INTERVAL.1);
if self.position.1 >= ground {
self.velocity.1 = -HOP_SPEED;
}
}
if rng.random::<f32>() < 0.02 {
self.velocity.0 += rng.random_range(-0.2..0.2);
if self.velocity.0.abs() > WALK_SPEED_RANGE.1 {
self.velocity.0 = self.velocity.0.signum() * WALK_SPEED_RANGE.1;
}
}
}
fn startle(&mut self, rng: &mut EffectRng) {
self.velocity.1 = -HOP_SPEED * rng.random_range(0.5..0.8);
self.hop_timer = rng.random_range(HOP_INTERVAL.0..HOP_INTERVAL.1);
self.airborne = true;
}
}
fn right_edge(screen_width: u16, sprite_width: usize) -> f32 {
(screen_width as f32 - sprite_width as f32).max(0.0)
}
fn shadow_span(sprite_width: usize, altitude: f32) -> f32 {
let shrink = 1.0 - (altitude / 3.0).clamp(0.0, 0.75);
(((sprite_width as f32) * 0.62) * shrink).max(1.0)
}
impl TerminalEffect for Crab {
fn get_diff(&mut self) -> Vec<(usize, usize, Cell)> {
self.canvas.clear();
let (width, _height) = sprite();
let seabed = &self.seabed;
let screen_height = self.canvas.height();
for x in 0..self.canvas.width() {
let top = (seabed.row_at(x as f32).round() as isize)
.clamp(0, screen_height as isize - 1)
as usize;
for y in top..screen_height {
self.canvas.set(
x,
y,
Cell::new(
SAND[(x + y) % SAND.len()],
SAND_COLOUR,
style::Attribute::Reset,
),
);
}
}
for crab in &self.crabs {
let base_x = crab.position.0.round().max(0.0) as usize;
let base_y = crab.position.1.round().max(0.0) as usize;
let sand_row = seabed.sand_at(crab.position.0);
let altitude =
(seabed.row_at(crab.position.0) - crab.position.1).max(0.0);
let span = shadow_span(width, altitude);
let centre = base_x as f32 + (width as f32) * 0.5;
let from = (centre - span * 0.5).round().max(0.0) as usize;
let to = (centre + span * 0.5).round().max(0.0) as usize;
for x in from..to.min(self.canvas.width()) {
self.canvas.set(
x,
sand_row,
Cell::new(SHADOW_GLYPH, SHADOW_COLOUR, style::Attribute::Reset),
);
}
for (y_offset, line) in crab.frame_lines().iter().enumerate() {
let y = base_y + y_offset;
if y >= self.canvas.height() {
continue;
}
for (x_offset, ch) in line.chars().enumerate() {
let x = base_x + x_offset;
if x >= self.canvas.width() || ch == ' ' {
continue;
}
self.canvas.set(
x,
y,
Cell::new(ch, crab.color, style::Attribute::Reset),
);
}
}
}
self.canvas.commit()
}
fn update(&mut self) {
self.step(1.0 / 30.0);
}
fn update_with_context(&mut self, context: &crate::runtime::FrameContext) {
self.step(context.delta.as_secs_f64().min(0.1));
}
fn update_size(&mut self, width: u16, height: u16) {
self.screen_size = (width.max(1), height.max(1));
self.canvas.resize(self.screen_size.0, self.screen_size.1);
let area = self.screen_size.0 as f32 * self.screen_size.1 as f32;
self.options.crab_count =
(area / 800.0 * self.options.crab_coeff).clamp(3.0, 15.0) as u16;
}
fn reset(&mut self) {
*self = Self::new(self.options.clone(), self.screen_size);
}
}
impl Crab {
fn step(&mut self, dt: f64) {
self.frame_timer += dt as f32;
self.seabed.advance(
dt,
-(f64::from(self.options.movement_speed) * f64::from(WALK_GAIN)),
);
let seabed = &self.seabed;
for crab in &mut self.crabs {
crab.update(
dt as f32,
self.screen_size,
seabed,
self.options.animation_speed,
self.options.clap_duration,
self.options.movement_speed,
self.options.clap_chance,
&mut self.rng,
);
}
self.separate_crabs();
self.check_crab_collisions();
}
pub fn new(options: CrabOptions, screen_size: (u16, u16)) -> Self {
let mut rng = seeded_rng(options.seed, "crab");
let canvas = Canvas::new(screen_size.0, screen_size.1);
let (sprite_width, _sprite_height) = sprite();
let seabed = Seabed::new(&options, screen_size.1 as usize);
let max_x = right_edge(screen_size.0, sprite_width);
let columns = Self::spread(&mut rng, max_x, options.crab_count as usize);
let mut crabs = Vec::with_capacity(options.crab_count as usize);
for column in columns {
let ground = seabed.row_at(column);
let velocity = (
rng.random_range(WALK_SPEED_RANGE.0..WALK_SPEED_RANGE.1)
* if rng.random::<f32>() < 0.5 { -1.0 } else { 1.0 },
0.0,
);
let hop_timer = rng.random_range(HOP_INTERVAL.0..HOP_INTERVAL.1);
crabs.push(CrabEntity::new(
(column, ground),
velocity,
hop_timer,
&mut rng,
));
}
let seabed = Seabed::new(&options, screen_size.1 as usize);
Self {
screen_size,
options,
canvas,
crabs,
rng,
frame_timer: 0.0,
seabed,
}
}
fn spread(rng: &mut EffectRng, max_x: f32, count: usize) -> Vec<f32> {
const ATTEMPTS: usize = 24;
let (sprite_width, _) = sprite();
let mut columns = vec![0.0f32; count];
for index in 0..count {
let mut placed = false;
for gap in [sprite_width as f32 + 2.0, 1.0] {
for _ in 0..ATTEMPTS {
let candidate = rng.random_range(0.0..=max_x);
if columns[..index]
.iter()
.all(|other| (other - candidate).abs() >= gap)
{
columns[index] = candidate;
placed = true;
break;
}
}
if placed {
break;
}
}
if !placed {
columns[index] = rng.random_range(0.0..=max_x);
}
}
columns
}
fn separate_crabs(&mut self) {
let count = self.crabs.len();
if count < 2 {
return;
}
let min_gap = separation(self.screen_size.0, count);
if min_gap <= 0.0 {
return;
}
let max_x = right_edge(self.screen_size.0, sprite().0);
let mut order: Vec<usize> = (0..count).collect();
order.sort_by(|&a, &b| {
self.crabs[a]
.position
.0
.total_cmp(&self.crabs[b].position.0)
.then(a.cmp(&b))
});
for window in order.windows(2) {
let (behind, ahead) = (window[0], window[1]);
let floor = self.crabs[behind].position.0 + min_gap;
let lifted = self.crabs[ahead].position.0.max(floor);
self.crabs[ahead].position.0 = lifted.min(max_x);
}
for window in order.windows(2).rev() {
let (behind, ahead) = (window[0], window[1]);
let ceiling = self.crabs[ahead].position.0 - min_gap;
if self.crabs[behind].position.0 > ceiling {
self.crabs[behind].position.0 = ceiling;
}
}
}
fn check_crab_collisions(&mut self) {
let crab_count = self.crabs.len();
if crab_count < 2 {
return;
}
let reach = touch_distance();
let reach = reach * reach;
for i in 0..crab_count {
for j in (i + 1)..crab_count {
let dx = self.crabs[i].position.0 - self.crabs[j].position.0;
let dy = self.crabs[i].position.1 - self.crabs[j].position.1;
let distance_squared = dx * dx + dy * dy;
if distance_squared >= reach {
continue;
}
let relative = self.crabs[i].position.0 - self.crabs[j].position.0;
let closing = (self.crabs[i].velocity.0 - self.crabs[j].velocity.0)
* relative
< 0.0;
let head_on =
self.crabs[i].velocity.0 * self.crabs[j].velocity.0 < 0.0;
if !closing || !head_on {
continue;
}
let clap = !self.crabs[i].is_special && !self.crabs[j].is_special;
for crab in [i, j] {
if clap {
self.crabs[crab].is_special = true;
self.crabs[crab].special_timer = self.options.clap_duration;
}
if self.crabs[crab].airborne {
continue;
}
self.crabs[crab].velocity.0 = -self.crabs[crab].velocity.0;
self.crabs[crab].direction =
if self.crabs[crab].velocity.0 >= 0.0 {
Direction::Right
} else {
Direction::Left
};
self.crabs[crab].startle(&mut self.rng);
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashSet;
const SIZE: (u16, u16) = (80, 24);
fn colony() -> Crab {
Crab::new(CrabOptions::default(), SIZE)
}
#[test]
fn resize_recomputes_crab_count() {
let options = CrabOptions {
crab_count: 10,
crab_coeff: 1.0,
..Default::default()
};
let mut crab = Crab::new(options, (80, 40));
crab.update_size(10, 10);
assert_eq!(crab.screen_size, (10, 10));
assert_eq!(crab.options.crab_count, 3);
}
#[test]
fn new_terminates_at_minimum_size() {
let options = CrabOptions {
crab_count: 3,
..Default::default()
};
let _ = Crab::new(options, (6, 6));
}
#[test]
fn the_default_walk_is_a_scuttle_rather_than_a_sprint() {
let cells_per_second = |velocity: f32| {
velocity * CrabOptions::default().movement_speed * WALK_GAIN
};
let slow = cells_per_second(WALK_SPEED_RANGE.0);
let fast = cells_per_second(WALK_SPEED_RANGE.1);
assert!(
(1.5..=4.5).contains(&slow) && (1.5..=4.5).contains(&fast),
"the default colony walks at {slow:.1} to {fast:.1} cells a second. \
It wants the 1.5 to 4.5 band: below it a crab jumps a whole column \
every third of a second, and above it the body crosses a cell \
between every two leg positions"
);
}
#[test]
fn a_running_colony_covers_the_ground_its_speed_says() {
let mut crab = colony();
for _ in 0..30 {
crab.step(1.0 / 60.0);
}
let frames = 600u16;
let mut path = vec![0.0f32; crab.crabs.len()];
for _ in 0..frames {
let before: Vec<f32> =
crab.crabs.iter().map(|c| c.position.0).collect();
crab.step(1.0 / 60.0);
for (index, crab) in crab.crabs.iter().enumerate() {
path[index] += (crab.position.0 - before[index]).abs();
}
}
let seconds = f32::from(frames) / 60.0;
for (index, walked) in path.iter().enumerate() {
let per_second = walked / seconds;
assert!(
(1.5..=4.5).contains(&per_second),
"crab {index} covered {walked:.1} cells in ten seconds, which is \
{per_second:.1} cells a second rather than a scuttle"
);
}
}
#[test]
fn the_drawn_column_keeps_up_with_the_walk() {
let mut crab = colony();
for _ in 0..30 {
crab.step(1.0 / 60.0);
}
let mut changes = 0usize;
let mut previous: Vec<i64> = crab
.crabs
.iter()
.map(|c| c.position.0.round() as i64)
.collect();
let frames = 600;
for _ in 0..frames {
crab.step(1.0 / 60.0);
let now: Vec<i64> = crab
.crabs
.iter()
.map(|c| c.position.0.round() as i64)
.collect();
for (index, column) in now.iter().enumerate() {
if *column != previous[index] {
changes += 1;
}
}
previous = now;
}
let per_crab_second = changes as f64
/ (frames as f64 / 60.0)
/ crab.crabs.len().max(1) as f64;
assert!(
per_crab_second > 1.0,
"a crab changed drawn column {per_crab_second:.1} times a second, so \
it is standing still and twitching rather than walking; a vibrating \
colony measured 0.5"
);
assert!(
per_crab_second < 4.5,
"a crab changed drawn column {per_crab_second:.1} times a second, \
which is faster than the fastest crab in the colony is meant to walk; \
the gain of 5.0 measured 12.6"
);
}
#[test]
fn the_legs_and_the_body_move_at_the_same_time() {
let options = CrabOptions::default();
let cells_per_second = (WALK_SPEED_RANGE.0 + WALK_SPEED_RANGE.1)
* 0.5
* options.movement_speed
* WALK_GAIN;
let cells_per_pose = cells_per_second * options.animation_speed;
let poses_per_second = 1.0 / options.animation_speed;
assert!(
(0.25..3.0).contains(&cells_per_pose),
"a crab covers {cells_per_pose:.1} cells between poses, so the legs \
are either trailing a sliding body or pedalling on a crab that is \
not moving"
);
assert!(
(1.5..=4.0).contains(&poses_per_second),
"the legs cycle {poses_per_second:.1} times a second, which is not a \
scuttle"
);
assert!(
cells_per_second < 25.0,
"a crab covers {cells_per_second:.1} cells a second, which is a \
sprint rather than a scuttle"
);
}
#[test]
fn every_frame_is_a_rectangle_of_one_width_in_characters() {
let mut widths: HashSet<usize> = HashSet::new();
for frame in CRAB_FRAMES.iter() {
assert_eq!(frame.len(), SPRITE_ROWS, "a frame has the wrong height");
for line in frame {
widths.insert(line.chars().count());
}
}
assert_eq!(
widths.len(),
1,
"the sprite's rows are not all one width: {widths:?}"
);
assert_eq!(
sprite_width(&RIGHT_POSES[0]),
widths.iter().next().copied().unwrap(),
"sprite_width disagrees with the table it measures"
);
}
#[test]
fn the_sprite_width_is_measured_in_characters_not_bytes() {
let rows = ["¬▀¬▀", " ¬"];
assert_eq!(sprite_width(&rows), 4, "a byte count would be 10");
assert_eq!(rows[0].len(), 10, "the fixture is not the byte count");
}
#[test]
fn every_left_facing_frame_is_the_exact_reversal_of_its_counterpart() {
assert_eq!(CRAB_FRAMES.len(), POSES * 2);
for (right, left) in (0..POSES).map(|pose| (pose, pose + POSES)) {
for (row, (a, b)) in CRAB_FRAMES[right]
.iter()
.zip(CRAB_FRAMES[left].iter())
.enumerate()
{
let reversed: String = a.chars().rev().collect();
assert_eq!(
reversed, *b,
"right-facing pose {right} row {row} reverses to {reversed:?}, \
and the left-facing pose is {b:?}"
);
}
}
}
#[test]
fn the_walk_cycle_has_more_than_two_poses() {
let mut crab = colony();
let mut seen: HashSet<usize> = HashSet::new();
for entity in &mut crab.crabs {
entity.is_special = false;
entity.direction = Direction::Right;
for frame in 0..WALK_POSES * 3 {
entity.current_frame = frame;
seen.insert(entity.frame_index());
}
}
assert!(
seen.len() > 2,
"the walk cycle only reaches {} poses: {seen:?}",
seen.len()
);
}
#[test]
fn a_running_colony_uses_the_whole_walk_cycle() {
let mut crab = colony();
let mut seen: HashSet<String> = HashSet::new();
for _ in 0..200 {
crab.step(1.0 / 60.0);
for entity in &crab.crabs {
if !entity.is_special {
seen.insert(entity.frame_lines().join("\n"));
}
}
}
assert!(
seen.len() >= 3,
"a colony that has run for three seconds only shows {} walk poses, \
so the extra poses are not reachable",
seen.len()
);
}
#[test]
fn the_walk_poses_differ_by_more_than_one_glyph() {
let walk: Vec<String> = (0..WALK_POSES)
.map(|pose| CRAB_FRAMES[pose].join("\n"))
.collect();
for (index, a) in walk.iter().enumerate() {
for b in walk.iter().skip(index + 1) {
let differing =
a.chars().zip(b.chars()).filter(|(x, y)| x != y).count();
assert!(
differing >= 2,
"walk poses {index} and one other differ in only {differing} \
characters, so the third pose is the second one again"
);
}
}
}
#[test]
fn the_clap_duration_does_not_move_with_the_walk_rate() {
let slow_walk = CrabOptions {
animation_speed: 0.05,
..Default::default()
};
let fast_walk = CrabOptions {
animation_speed: 0.6,
..Default::default()
};
assert_eq!(slow_walk.clap_duration, fast_walk.clap_duration);
assert_eq!(slow_walk.clap_duration, 0.6);
assert_eq!(
slow_walk.clap_duration,
CrabOptions::default().clap_duration,
"the clap duration should not depend on the walk rate"
);
}
#[test]
fn crabs_stay_inside_the_canvas() {
for (width, height) in [
(1u16, 1u16),
(4, 4),
(6, 6),
(15, 5),
(20, 9),
(80, 24),
(200, 50),
] {
let mut crab = Crab::new(CrabOptions::default(), (width, height));
let (sprite_width, sprite_height) = sprite();
for _ in 0..240 {
crab.step(1.0 / 60.0);
let diff = crab.get_diff();
for (x, y, _) in diff {
assert!(
x < width as usize && y < height as usize,
"{width}x{height}: a cell at ({x}, {y}) is off screen"
);
}
for entity in &crab.crabs {
let x = entity.position.0.round();
let y = entity.position.1.round();
assert!(
x >= 0.0 && y >= 0.0,
"{width}x{height}: a crab is at ({x}, {y})"
);
assert!(
x <= width as f32 && y <= height as f32,
"{width}x{height}: a crab is at ({x}, {y}), past the edge"
);
assert!(
x + sprite_width as f32 <= width as f32 + 1.0
|| width < sprite_width as u16,
"{width}x{height}: a crab at {x} overhangs the right edge \
by {} columns",
x + sprite_width as f32 - width as f32
);
if height >= sprite_height as u16 {
assert!(
y + sprite_height as f32 <= height as f32,
"{width}x{height}: a crab at y={y} is below the screen"
);
}
}
}
}
}
#[test]
fn no_two_crabs_are_ever_drawn_in_the_same_column() {
for (width, height) in [
(20u16, 9u16),
(40, 12),
(80, 24),
(120, 40),
(200, 50),
(400, 200),
] {
let count =
((width as f32 * height as f32) / 800.0).clamp(3.0, 15.0) as u16;
let mut crab = Crab::new(
CrabOptions {
crab_count: count,
..Default::default()
},
(width, height),
);
assert!(
separation(width, crab.crabs.len()) >= 1.0,
"{width}x{height} is in this list but cannot hold {} crabs a \
column apart, so the assertion below would fail for a reason \
that has nothing to do with the separation",
crab.crabs.len()
);
for frame in 0..600 {
crab.step(1.0 / 60.0);
let columns: Vec<i64> = crab
.crabs
.iter()
.map(|c| c.position.0.round() as i64)
.collect();
let mut unique = HashSet::new();
for column in &columns {
assert!(
unique.insert(column),
"{width}x{height}, frame {frame}: two crabs are both \
drawn in column {column}, which is two crabs painted as \
one: {columns:?}"
);
}
}
}
for (width, height) in [(1u16, 1u16), (6, 6), (15, 5)] {
let mut crab = Crab::new(CrabOptions::default(), (width, height));
assert_eq!(
right_edge(width, sprite().0),
0.0,
"{width}x{height} now has a seabed, so the degenerate case has \
to move out of this comment and into the loop above"
);
for _ in 0..60 {
crab.step(1.0 / 60.0);
}
for entity in &crab.crabs {
assert_eq!(
entity.position.0, 0.0,
"{width}x{height}: a crab is at column {} where the only \
column is zero",
entity.position.0
);
}
}
}
#[test]
fn no_two_crabs_are_ever_within_the_separation() {
for (width, height) in [
(20u16, 9u16),
(40, 12),
(80, 24),
(120, 40),
(200, 50),
(400, 200),
] {
for count in [3u16, 5, 12, 15] {
let mut crab = Crab::new(
CrabOptions {
crab_count: count,
..Default::default()
},
(width, height),
);
let wanted = separation(width, crab.crabs.len());
for frame in 0..300 {
crab.step(1.0 / 60.0);
for (index, a) in crab.crabs.iter().enumerate() {
for (other, b) in
crab.crabs.iter().enumerate().skip(index + 1)
{
let gap = (a.position.0 - b.position.0).abs();
assert!(
gap >= wanted - 1.0e-3,
"{width}x{height} with {count} crabs, frame \
{frame}: crabs {index} and {other} are {gap:.3} \
cells apart, inside the {wanted:.3} the seabed \
can hold"
);
}
}
}
}
}
}
#[test]
fn the_gap_asked_for_never_exceeds_what_the_seabed_can_hold() {
for width in [1u16, 6, 15, 20, 40, 80, 120, 200, 400] {
let span = right_edge(width, sprite().0);
for count in [2usize, 3, 5, 9, 12, 15, 16] {
let wanted = separation(width, count);
assert!(
wanted as f64 * (count - 1) as f64 <= span as f64 + 1.0e-3,
"{count} crabs on a {width}-column screen ask for {wanted:.3} \
cells each, which needs {:.1} of the {span:.1} columns of \
seabed they have",
wanted as f64 * (count - 1) as f64
);
assert!(
wanted <= MIN_SEPARATION,
"the gap is {wanted:.3} on a {width}-column screen, so a \
screen wide enough is not getting the full \
{MIN_SEPARATION}"
);
}
}
assert_eq!(separation(200, 1), 0.0);
assert_eq!(separation(200, 0), 0.0);
}
#[test]
fn a_crab_following_a_slower_one_is_not_a_collision() {
fn facing(width: u16, first: (f32, f32), second: (f32, f32)) -> Crab {
let mut colony = Crab::new(CrabOptions::default(), (width, 24));
colony.crabs.truncate(2);
for (entity, (x, velocity)) in
colony.crabs.iter_mut().zip([first, second])
{
entity.position = (x, colony.seabed.row_at(x));
entity.velocity = (velocity, 0.0);
entity.hop_timer = HOP_INTERVAL.1;
entity.is_special = false;
entity.special_timer = 0.0;
entity.direction = if velocity >= 0.0 {
Direction::Right
} else {
Direction::Left
};
}
colony
}
let head_on = facing(80, (30.0, 1.0), (40.0, -1.0));
let following = facing(80, (30.0, 1.2), (40.0, 1.0));
for (label, mut crab) in [("head-on", head_on), ("following", following)] {
for _ in 0..5 {
crab.step(1.0 / 60.0);
}
let heading: Vec<f32> =
crab.crabs.iter().map(|c| c.velocity.0.signum()).collect();
if label == "head-on" {
assert_eq!(
heading,
vec![-1.0, 1.0],
"two crabs walking into each other ten columns apart did not \
turn around, so the collision response is not running"
);
} else {
assert_eq!(
heading,
vec![1.0, 1.0],
"a crab that was overtaking a slower one turned around \
instead: {heading:?}"
);
}
}
}
#[test]
fn separation_settles_rather_than_jittering() {
let mut crab = Crab::new(
CrabOptions {
crab_count: 8,
..Default::default()
},
(120, 24),
);
for entity in &mut crab.crabs {
entity.position.0 = 10.0;
}
crab.separate_crabs();
let after_first: Vec<f32> =
crab.crabs.iter().map(|c| c.position.0).collect();
let mut columns = after_first.clone();
columns.sort_by(f32::total_cmp);
for pair in columns.windows(2) {
assert!(
pair[1] - pair[0] >= MIN_SEPARATION - 1.0e-3,
"the first pass left a gap of {:.3}: {columns:?}",
pair[1] - pair[0]
);
}
crab.separate_crabs();
let after_second: Vec<f32> =
crab.crabs.iter().map(|c| c.position.0).collect();
for (index, (a, b)) in after_first.iter().zip(&after_second).enumerate() {
assert_eq!(
a, b,
"crab {index} moved again on the second pass, from {a} to {b}, so \
the correction is a force and will oscillate"
);
}
}
#[test]
fn a_crab_walks_rather_than_vibrating_in_place() {
for (width, height) in [(80u16, 24u16), (120, 40), (200, 50), (400, 200)] {
for count in [3u16, 5, 12, 15] {
let mut crab = Crab::new(
CrabOptions {
crab_count: count,
..Default::default()
},
(width, height),
);
let mut reversals = vec![0usize; crab.crabs.len()];
let mut previous: Vec<f32> =
crab.crabs.iter().map(|c| c.velocity.0).collect();
let frames = 600;
for _ in 0..frames {
crab.step(1.0 / 60.0);
for (index, entity) in crab.crabs.iter().enumerate() {
if entity.velocity.0 * previous[index] < 0.0 {
reversals[index] += 1;
}
previous[index] = entity.velocity.0;
}
}
let seconds = frames as f64 / 60.0;
for (index, turns) in reversals.iter().enumerate() {
let per_second = *turns as f64 / seconds;
assert!(
per_second < 10.0,
"{width}x{height} with {count} crabs: crab {index} turned \
itself around {per_second:.0} times a second, so it is \
vibrating rather than walking"
);
}
}
}
}
#[test]
fn the_colony_walks_on_a_seabed() {
let mut crab = colony();
let (_, sprite_height) = sprite();
let sand_row = SIZE.1 as usize - 1;
let ground = (sand_row - sprite_height) as f32;
let _ = ground;
for _ in 0..300 {
crab.step(1.0 / 60.0);
}
crab.get_diff();
let frame = crab.canvas.on_screen();
let bottom: HashSet<style::Color> = (0..frame.width)
.filter(|x| frame.get(*x, sand_row).symbol != ' ')
.map(|x| frame.get(x, sand_row).color)
.collect();
let covered = (0..frame.width)
.filter(|x| frame.get(*x, sand_row).symbol != ' ')
.count();
assert!(
covered > 8,
"the bottom row has only {covered} cells on it, so there is no seabed"
);
assert!(
bottom
.iter()
.all(|colour| *colour == SAND_COLOUR || *colour == SHADOW_COLOUR),
"the bottom row is not all sand and shadow: {bottom:?}"
);
for entity in &crab.crabs {
let y = entity.position.1;
assert!(
(0.0..=24.0).contains(&y),
"a crab at y={y} is not on the seabed, whose surface is row {ground}"
);
}
}
#[test]
fn a_crabs_shadow_is_under_it_and_shrinks_as_it_rises() {
let mut crab = colony();
for _ in 0..30 {
crab.step(1.0 / 60.0);
}
let diff = crab.get_diff();
let sand_rows: Vec<usize> = crab
.crabs
.iter()
.map(|c| crab.seabed.sand_at(c.position.0))
.collect();
let shadows: Vec<(usize, usize)> = diff
.iter()
.filter(|(_, y, cell)| {
sand_rows.contains(y)
&& cell.symbol == SHADOW_GLYPH
&& cell.color == SHADOW_COLOUR
})
.map(|(x, y, _)| (*x, *y))
.collect();
assert!(
!shadows.is_empty(),
"no shadow is on the sand under any of the {} crabs, so they are \
floating",
crab.crabs.len()
);
let crab_columns: Vec<f32> =
crab.crabs.iter().map(|c| c.position.0.round()).collect();
for (shadow, _) in &shadows {
assert!(
crab_columns
.iter()
.any(|c| (*shadow as f32 - c).abs() < 16.0),
"a shadow at column {shadow} is not under any crab: {crab_columns:?}"
);
}
let (width, _) = sprite();
let on_ground = shadow_span(width, 0.0);
let airborne = shadow_span(width, 2.0);
assert!(
airborne < on_ground,
"a shadow is {on_ground} cells wide on the ground and {airborne:.0} \
two cells up, so the crab's height is not reaching the ground"
);
}
#[test]
fn the_seabed_goes_up_and_down() {
let options = CrabOptions::default();
let span = options.seabed_period.ceil() as usize;
let mut lowest = f32::INFINITY;
let mut highest = f32::NEG_INFINITY;
for phase in 0..8 {
let seabed = Seabed {
offset: phase as f64 * options.seabed_period / 8.0,
..Seabed::new(&options, 24)
};
for x in 0..=span {
let row = seabed.row_at(x as f32);
lowest = lowest.min(row);
highest = highest.max(row);
}
}
assert!(
highest > lowest,
"the seabed is one flat row ({lowest}) across a whole period, so there \
is nowhere for a crab to go up to"
);
}
#[test]
fn the_colony_climbs_off_the_bottom_of_the_screen() {
let mut crab = colony();
let mut highest = f32::INFINITY;
for _ in 0..(45 * 60) {
crab.step(1.0 / 60.0);
highest = highest.min(
crab.crabs
.iter()
.map(|entity| entity.position.1)
.fold(f32::INFINITY, f32::min),
);
}
let floor = crab.seabed.base_row();
let rows_above_the_floor = floor - highest;
assert!(
rows_above_the_floor >= 4.0,
"over 45 seconds the highest a crab stood was row {highest:.1}, which \
is {rows_above_the_floor:.1} rows above the seabed's floor of \
{floor:.0} -- the colony is still hugging the bottom"
);
}
#[test]
fn the_crabs_walk_on_the_profile_rather_than_beside_it() {
let mut crab = colony();
for entity in &mut crab.crabs {
entity.velocity = (2.5, 0.0);
}
for _ in 0..200 {
crab.step(1.0 / 60.0);
}
let seated: Vec<f32> = crab
.crabs
.iter()
.filter(|c| !c.airborne)
.map(|c| (c.position.1 - crab.seabed.row_at(c.position.0)).abs())
.collect();
assert!(
!seated.is_empty(),
"every crab was airborne, so there was nothing to measure"
);
let worst = seated.iter().cloned().fold(0.0f32, f32::max);
assert!(
worst < 0.001,
"a seated crab is up to {worst:.4} of a row off the ground under it, \
so the colony is walking beside the seabed rather than on it"
);
}
#[test]
fn the_ground_scrolls_with_the_colony_rather_than_against_it() {
let size = (200u16, 24);
let mut crab = Crab::new(CrabOptions::default(), size);
crab.crabs.truncate(1);
let centre = f32::from(size.0) * 0.5;
for entity in &mut crab.crabs {
entity.position = (centre, crab.seabed.row_at(centre));
entity.velocity = (1.0, 0.0);
entity.hop_timer = f32::MAX;
}
let mut rows = Vec::new();
for _ in 0..100 {
crab.step(1.0 / 60.0);
assert!(
!crab.crabs[0].airborne,
"the crab left the ground, so there is no contour to hold"
);
rows.push(crab.crabs[0].position.1);
}
let swing = rows.iter().copied().fold(f32::NEG_INFINITY, f32::max)
- rows.iter().copied().fold(f32::INFINITY, f32::min);
assert!(
swing < 0.01,
"a crab walking in a straight line changed row by {swing:.4} over five \
cells of travel, so the seabed is sliding past it rather than \
travelling with it -- the scroll sign is reversed"
);
}
#[test]
fn the_profile_is_a_bank_and_not_a_cliff_or_a_ripple() {
let options = CrabOptions::default();
let span = options.seabed_period.ceil() as usize;
let mut lowest = f32::INFINITY;
let mut highest = f32::NEG_INFINITY;
for phase in 0..8 {
let seabed = Seabed {
offset: phase as f64 * options.seabed_period / 8.0,
..Seabed::new(&options, 24)
};
for x in 0..=span {
let row = seabed.row_at(x as f32);
lowest = lowest.min(row);
highest = highest.max(row);
}
}
let relief = (highest.round() - lowest.round()) as i32;
assert!(
(2..=12).contains(&relief),
"the seabed has {relief} rows of relief over a whole period on a 24 \
row screen, against 2 to 12; a profile that stops varying is the flat \
row this replaced, and past twelve it is a wall"
);
for (width, height) in [(1u16, 1u16), (4, 4), (6, 6), (16, 9), (20, 10)] {
let seabed = Seabed::new(&options, height as usize);
for x in 0..width {
let row = seabed.row_at(x as f32);
assert!(
row.is_finite() && (0.0..height as f32).contains(&row),
"on {width}x{height} the ground at column {x} is at row {row}, \
which is off the screen"
);
}
}
for bad in [f64::NAN, f64::INFINITY, -1.0] {
let options = CrabOptions {
seabed_amplitude: bad as f32,
..Default::default()
};
let seabed = Seabed::new(&options, 24);
let row = seabed.row_at(12.0);
assert!(
row.is_finite() && (0.0..=24.0).contains(&row),
"an amplitude of {bad} put the ground at row {row}"
);
let options = CrabOptions {
seabed_period: bad,
..Default::default()
};
let seabed = Seabed::new(&options, 24);
let row = seabed.row_at(12.0);
assert!(
row.is_finite() && (0.0..=24.0).contains(&row),
"a period of {bad} put the ground at row {row}"
);
}
}
#[test]
fn the_seabed_has_eight_rows_of_relief_and_a_slope_a_crab_can_stand_on() {
const HEIGHT: usize = 24;
const REQUESTED: i32 = 8;
const MAX_DRIFT: f32 = 1.0;
let options = CrabOptions::default();
let (sprite_width, _) = sprite();
let span = options.seabed_period.ceil() as usize;
let mut lowest = f32::INFINITY;
let mut highest = f32::NEG_INFINITY;
let mut worst_drift = 0.0f32;
for phase in 0..8 {
let seabed = Seabed {
offset: phase as f64 * options.seabed_period / 8.0,
..Seabed::new(&options, HEIGHT)
};
for x in 0..=span {
let row = seabed.row_at(x as f32);
lowest = lowest.min(row);
highest = highest.max(row);
worst_drift = worst_drift
.max((row - seabed.row_at((x + sprite_width) as f32)).abs());
}
}
let relief = (highest.round() - lowest.round()) as i32;
assert!(
(REQUESTED - 1..=REQUESTED + 1).contains(&relief),
"the seabed has {relief} rows of relief over its period, against the \
{REQUESTED} that were asked for (a band of {} to {}); the profile \
spans rows {lowest:.1} to {highest:.1}",
REQUESTED - 1,
REQUESTED + 1
);
assert!(
worst_drift <= MAX_DRIFT + 0.1,
"the ground moves {worst_drift:.2} rows across one sprite's \
{sprite_width} columns, so a crab is standing on a slope rather than \
on a bank; {MAX_DRIFT} is the bound"
);
assert!(
relief >= REQUESTED - 1,
"the drift of {worst_drift:.2} is meaningless on a seabed with no \
relief in it"
);
}
#[test]
fn no_row_is_shorter_than_the_sprite() {
let (width, height) = sprite();
for (pose, frame) in CRAB_FRAMES.iter().enumerate() {
assert_eq!(frame.len(), height, "pose {pose} has the wrong height");
for (row, line) in frame.iter().enumerate() {
assert_eq!(
line.chars().count(),
width,
"pose {pose} row {row} is {} characters, not {width}",
line.chars().count()
);
}
}
}
#[test]
fn the_seabed_does_not_churn() {
let mut crab = colony();
for _ in 0..60 {
crab.step(1.0 / 60.0);
}
crab.get_diff();
for entity in &mut crab.crabs {
entity.velocity = (0.0, 0.0);
}
let before = crab.get_diff();
let after = crab.get_diff();
let sand_row = SIZE.1 as usize - 1;
let churn: Vec<_> = after
.iter()
.filter(|(x, y, cell)| {
*y == sand_row && !before.contains(&(*x, *y, *cell))
})
.collect();
assert!(
churn.is_empty(),
"the sand changed {} cells in a frame where nothing moved",
churn.len()
);
}
#[test]
fn no_cell_is_bold_and_every_glyph_is_one_cell_wide() {
use crate::render::glyph_ramp;
let mut crab = colony();
let diff = crab.get_diff();
assert!(!diff.is_empty(), "the fixture drew nothing");
for (x, y, cell) in &diff {
assert_eq!(
cell.attr,
style::Attribute::Reset,
"cell ({x}, {y}) is bold, which brightens the crab's colour"
);
}
let mut glyphs: HashSet<char> = HashSet::new();
for frame in CRAB_FRAMES.iter() {
for line in frame {
glyphs.extend(line.chars().filter(|c| *c != ' '));
}
}
glyphs.extend(SAND.iter().copied());
glyphs.insert(SHADOW_GLYPH);
for glyph in glyphs {
assert!(
glyph_ramp::is_ambiguous_or_narrow(glyph),
"{glyph:?} (U+{:04X}) could shear a cell-indexed grid",
glyph as u32
);
}
}
#[test]
fn the_new_keys_round_trip_through_toml() {
let options: CrabOptions =
toml::from_str("clap_duration = 1.25\nanimation_speed = 0.3\n")
.expect("two keys parse");
assert_eq!(options.clap_duration, 1.25);
assert_eq!(options.animation_speed, 0.3);
assert_eq!(
options.movement_speed,
CrabOptions::default().movement_speed,
"two keys in the section silently reset the others"
);
let serialised = toml::to_string(&options).expect("the section serialises");
for key in [
"animation_speed",
"clap_duration",
"clap_chance",
"movement_speed",
"crab_coeff",
"seed",
] {
assert!(
serialised.contains(key),
"{key} is missing from the serialised form, so --print-config \
would not write it: {serialised}"
);
}
}
#[test]
fn movement_speed_is_unchanged_and_the_gain_carries_the_speed() {
assert_eq!(CrabOptions::default().movement_speed, 3.0);
const _: () = assert!(WALK_GAIN <= 1.5);
}
}