crates, player coords, arch.md gone

This commit is contained in:
2026-06-06 14:11:20 -05:00
parent 05c9fdbde9
commit 8ac6da184c
7 changed files with 744 additions and 484 deletions
+442 -29
View File
@@ -69,6 +69,35 @@ pub struct FontSpec {
pub tile_h: u32,
}
/// Which directions a solid may be pushed in.
///
/// Only meaningful for `solid` cells (a non-solid cell is passable, so nothing is
/// ever pushed into it). `Crate` is [`Pushable::Any`]; the directional crates
/// constrain pushes to one axis.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Pushable {
/// Cannot be pushed.
No,
/// Pushable in any direction.
Any,
/// Pushable east/west only.
Horizontal,
/// Pushable north/south only.
Vertical,
}
impl Pushable {
/// Whether a push in `dir` is allowed.
pub fn allows(self, dir: Direction) -> bool {
match self {
Pushable::No => false,
Pushable::Any => true,
Pushable::Horizontal => matches!(dir, Direction::East | Direction::West),
Pushable::Vertical => matches!(dir, Direction::North | Direction::South),
}
}
}
/// The behavioral properties of a board cell at runtime.
///
/// `Behavior` is a plain data struct returned by [`Archetype::behavior`]. It
@@ -86,9 +115,8 @@ pub struct Behavior {
pub solid: bool,
/// Whether this cell blocks line of sight (reserved for future rendering).
pub opaque: bool,
/// Whether a mover can shove this cell. Unused for now — every archetype is
/// `false`; the push mechanic is future work.
pub pushable: bool,
/// Which directions a mover can shove this cell in (only meaningful when `solid`).
pub pushable: Pushable,
}
/// A class of board cell, encoding its default behavior and appearance.
@@ -114,6 +142,13 @@ pub enum Archetype {
Empty,
/// A solid wall; impassable and opaque.
Wall,
/// A solid, pushable box. Walking into it shoves it one cell in the same
/// direction (cascading through a chain of crates) if there is open space.
Crate,
/// A crate that can only be pushed east/west (horizontal axis). Glyph ↔.
HCrate,
/// A crate that can only be pushed north/south (vertical axis). Glyph ↕.
VCrate,
/// Sentinel for map files that reference an unknown archetype name.
/// Renders as a yellow `?` on red to make the error visible in-game.
ErrorBlock,
@@ -128,17 +163,32 @@ impl Archetype {
Archetype::Empty => Behavior {
solid: false,
opaque: false,
pushable: false,
pushable: Pushable::No,
},
Archetype::Wall => Behavior {
solid: true,
opaque: true,
pushable: false,
pushable: Pushable::No,
},
Archetype::Crate => Behavior {
solid: true,
opaque: true,
pushable: Pushable::Any,
},
Archetype::HCrate => Behavior {
solid: true,
opaque: true,
pushable: Pushable::Horizontal,
},
Archetype::VCrate => Behavior {
solid: true,
opaque: true,
pushable: Pushable::Vertical,
},
Archetype::ErrorBlock => Behavior {
solid: true,
opaque: true,
pushable: false,
pushable: Pushable::No,
},
}
}
@@ -148,6 +198,9 @@ impl Archetype {
match self {
Archetype::Empty => "empty",
Archetype::Wall => "wall",
Archetype::Crate => "crate",
Archetype::HCrate => "hcrate",
Archetype::VCrate => "vcrate",
Archetype::ErrorBlock => "error_block",
}
}
@@ -169,6 +222,21 @@ impl Archetype {
fg: Rgba8 { r: 0x80, g: 0x80, b: 0x80, a: 255 },
bg: Rgba8 { r: 0x60, g: 0x60, b: 0x60, a: 255 },
},
Archetype::Crate => Glyph {
tile: 254, // CP437 ■ (small filled square)
fg: Rgba8 { r: 0xAA, g: 0xAA, b: 0xAA, a: 255 }, // light gray on black
bg: Rgba8 { r: 0, g: 0, b: 0, a: 255 },
},
Archetype::HCrate => Glyph {
tile: 29, // CP437 ↔ (left-right arrow) — pushable east/west
fg: Rgba8 { r: 0xAA, g: 0xAA, b: 0xAA, a: 255 }, // same colors as Crate
bg: Rgba8 { r: 0, g: 0, b: 0, a: 255 },
},
Archetype::VCrate => Glyph {
tile: 18, // CP437 ↕ (up-down arrow) — pushable north/south
fg: Rgba8 { r: 0xAA, g: 0xAA, b: 0xAA, a: 255 }, // same colors as Crate
bg: Rgba8 { r: 0, g: 0, b: 0, a: 255 },
},
// Visually distinct so malformed map files are immediately obvious.
Archetype::ErrorBlock => Glyph {
tile: 63,
@@ -190,6 +258,9 @@ impl TryFrom<&str> for Archetype {
match name {
"empty" => Ok(Archetype::Empty),
"wall" => Ok(Archetype::Wall),
"crate" => Ok(Archetype::Crate),
"hcrate" => Ok(Archetype::HCrate),
"vcrate" => Ok(Archetype::VCrate),
// "object" is intentionally absent: objects are not valid palette
// entries in map files. They live in [[objects]] with their own glyph.
_ => Err(format!("unknown archetype: {name}")),
@@ -201,7 +272,13 @@ impl TryFrom<&str> for Archetype {
///
/// `ErrorBlock` is excluded — it is a sentinel for load errors, not a valid
/// editing choice.
pub const ALL_ARCHETYPES: &[Archetype] = &[Archetype::Empty, Archetype::Wall];
pub const ALL_ARCHETYPES: &[Archetype] = &[
Archetype::Empty,
Archetype::Wall,
Archetype::Crate,
Archetype::HCrate,
Archetype::VCrate,
];
/// A scripted object placed on the board, loaded from a map file.
///
@@ -311,7 +388,8 @@ pub struct PortalDef {
/// rather than being stored as a board cell. This is expected to change:
/// the player will eventually become a scripted object that responds to
/// input events, at which point this struct may be removed or made optional.
/// See `ARCHITECTURE.md` for details.
/// See the "player may become an object" notes in `CLAUDE.md` for the design
/// tensions this implies.
#[derive(Copy, Clone)]
pub struct Player {
/// Column position (0-indexed, increasing rightward).
@@ -368,6 +446,11 @@ pub struct Board {
/// A board script runs on the board as a whole (e.g. `on_enter`, `on_tick`)
/// rather than being tied to a specific object cell.
pub board_script_name: Option<String>,
/// Nonfatal problems collected while loading this map (e.g. unknown
/// archetypes, dropped objects, recovered placement chars), as red-on-black
/// [`LogLine`]s. Empty for a clean load; see [`Board::is_valid`]. Not part of
/// the map file (purely a load diagnostic).
pub(crate) load_errors: Vec<LogLine>,
}
impl Board {
@@ -382,11 +465,37 @@ impl Board {
/// Returns a mutable reference to the cell at `(x, y)`.
///
/// Panics if `x` or `y` are out of bounds.
#[allow(dead_code)]
pub fn get_mut(&mut self, x: usize, y: usize) -> &mut (Glyph, Archetype) {
&mut self.cells[y * self.width + x]
}
/// Returns `true` if `(x, y)` is a valid cell coordinate on this board.
///
/// Takes signed coords so callers can pass a raw `pos + delta` without first
/// checking for negatives.
pub fn in_bounds(&self, pos: (i32, i32)) -> bool {
let (x, y) = pos;
x >= 0 && y >= 0 && (x as usize) < self.width && (y as usize) < self.height
}
/// Records a nonfatal error: appends `message` as a red-on-black line to the
/// board's [`load_errors`](Board::load_errors). Used by the map loader (and
/// available at runtime) to surface recoverable problems.
pub fn report_error(&mut self, message: impl Into<String>) {
self.load_errors.push(LogLine::error(message));
}
/// Returns `true` if the map loaded with no nonfatal errors (the error list
/// is empty).
pub fn is_valid(&self) -> bool {
self.load_errors.is_empty()
}
/// The nonfatal errors collected while loading this board, newest last.
pub fn load_errors(&self) -> &[LogLine] {
&self.load_errors
}
/// Returns a slice of all cells in row-major order.
///
/// Useful for iterating over the full board (e.g. to collect unique glyphs).
@@ -423,6 +532,92 @@ impl Board {
self.solid_at(x, y).is_none()
}
/// Whether the cell's single solid occupant (if any) can be pushed in `dir`.
///
/// Non-solid things are never pushable: `pushable` only matters for solids.
/// Grid archetypes may restrict the axis (see [`Pushable`]); pushable objects
/// can be shoved in any direction.
fn is_pushable(&self, x: usize, y: usize, dir: Direction) -> bool {
match self.solid_at(x, y) {
Some(Solid::Cell(a)) => a.behavior().pushable.allows(dir),
Some(Solid::Object(o)) => o.pushable,
None => false,
}
}
/// Whether the chain of pushable solids starting at `(x, y)` can be shoved one
/// step in `dir` — i.e. the chain ends at a passable cell rather than the board
/// edge or a non-pushable solid.
///
/// Read-only (`&self`); pairs with [`push`](Board::push). Returns `false` when
/// `(x, y)` itself holds no pushable solid, so it doubles as the "is the cell
/// ahead shovable?" half of a "can I move here?" query.
pub fn can_push(&self, x: usize, y: usize, dir: Direction) -> bool {
let (dx, dy): (i32, i32) = dir.into();
let (mut cx, mut cy) = (x, y);
loop {
// This cell must hold a solid pushable in `dir` to advance the chain.
if !self.is_pushable(cx, cy, dir) {
return false;
}
let next = (cx as i32 + dx, cy as i32 + dy);
if !self.in_bounds(next) {
return false; // chain runs off the board
}
let (nx, ny) = (next.0 as usize, next.1 as usize);
if self.is_passable(nx, ny) {
return true; // open space at the end: the whole chain can move
}
// Next cell holds a solid too; continue (it must itself be pushable).
cx = nx;
cy = ny;
}
}
/// Shoves the chain of pushable solids starting at `(x, y)` one step in `dir`,
/// leaving `Empty` floor behind each moved cell.
///
/// No-op when the chain can't move (it self-checks via [`can_push`](Board::can_push)),
/// so it is safe to call unconditionally.
pub fn push(&mut self, x: usize, y: usize, dir: Direction) {
if !self.can_push(x, y, dir) {
return;
}
let (dx, dy): (i32, i32) = dir.into();
// can_push guaranteed the chain ends at an in-bounds passable cell, so
// re-walk it (no bounds checks needed) and shift the far end first, which
// keeps each destination cell vacated before its occupant arrives.
let mut chain: Vec<(usize, usize)> = Vec::new();
let (mut cx, mut cy) = (x, y);
while !self.is_passable(cx, cy) {
chain.push((cx, cy));
cx = (cx as i32 + dx) as usize;
cy = (cy as i32 + dy) as usize;
}
for &(px, py) in chain.iter().rev() {
self.shift_solid(px, py, dx, dy);
}
}
/// Moves the single solid occupant of `(x, y)` one step by `(dx, dy)`.
///
/// A solid object is relocated; otherwise the grid archetype (a crate) is
/// moved, leaving `Empty` floor behind (the grid has no separate floor layer).
/// The caller guarantees the destination is already clear.
fn shift_solid(&mut self, x: usize, y: usize, dx: i32, dy: i32) {
let (tx, ty) = ((x as i32 + dx) as usize, (y as i32 + dy) as usize);
if let Some(idx) = self.object_index_at(x, y)
&& self.objects[idx].solid
{
self.objects[idx].x = tx;
self.objects[idx].y = ty;
} else {
let moved = *self.get(x, y);
*self.get_mut(tx, ty) = moved;
*self.get_mut(x, y) = (Archetype::Empty.default_glyph(), Archetype::Empty);
}
}
/// Returns the index into [`Board::objects`] of the object at `(x, y)`, if any.
pub fn object_index_at(&self, x: usize, y: usize) -> Option<usize> {
self.objects.iter().position(|o| o.x == x && o.y == y)
@@ -523,42 +718,45 @@ impl GameState {
}
}
/// Moves object `idx` one cell in `dir`, if the target is in bounds and
/// passable. This is where movement rules live (a no-op when blocked).
/// Moves object `idx` one cell in `dir`. The move proceeds if the target is in
/// bounds and either passable or a pushable solid the object can shove out of
/// the way (see [`Board::can_push`]). A no-op when blocked.
fn move_object(&mut self, idx: usize, dir: Direction) {
let (dx, dy): (i32, i32) = dir.into();
let mut board = self.board_mut();
let Some((ox, oy)) = board.objects.get(idx).map(|o| (o.x, o.y)) else {
return;
};
let nx = ox as i32 + dx;
let ny = oy as i32 + dy;
if nx < 0 || ny < 0 {
let target = (ox as i32 + dx, oy as i32 + dy);
if !board.in_bounds(target) {
return;
}
let (nx, ny) = (nx as usize, ny as usize);
if nx < board.width && ny < board.height && board.is_passable(nx, ny) {
let (nx, ny) = (target.0 as usize, target.1 as usize);
if board.is_passable(nx, ny) || board.can_push(nx, ny, dir) {
board.push(nx, ny, dir); // shoves a crate/object out of the way; no-op otherwise
let obj = &mut board.objects[idx];
obj.x = nx;
obj.y = ny;
}
}
/// Attempts to move the player by `(dx, dy)` cells.
/// Attempts to move the player one cell in `dir`.
///
/// The move is ignored if the target cell is out of bounds or its behavior
/// is not passable. No-ops silently (the caller does not need to check).
pub fn try_move(&mut self, dx: i32, dy: i32) {
/// The move is ignored if the target cell is out of bounds, or it is neither
/// passable nor a pushable solid that can be shoved aside. No-ops silently
/// (the caller does not need to check).
pub fn try_move(&mut self, dir: Direction) {
let (dx, dy): (i32, i32) = dir.into();
let mut board = self.board_mut();
let nx = board.player.x + dx;
let ny = board.player.y + dy;
if nx >= 0 && ny >= 0 {
let nx = nx as usize;
let ny = ny as usize;
if nx < board.width && ny < board.height && board.is_passable(nx, ny) {
board.player.x = nx as i32;
board.player.y = ny as i32;
}
let target = (board.player.x + dx, board.player.y + dy);
if !board.in_bounds(target) {
return;
}
let (nx, ny) = (target.0 as usize, target.1 as usize);
if board.is_passable(nx, ny) || board.can_push(nx, ny, dir) {
board.push(nx, ny, dir); // shoves a crate/object out of the way; no-op otherwise
board.player.x = nx as i32;
board.player.y = ny as i32;
}
}
}
@@ -587,6 +785,7 @@ mod tests {
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect(),
board_script_name: None,
load_errors: Vec::new(),
}
}
@@ -625,6 +824,7 @@ mod tests {
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect(),
board_script_name: None,
load_errors: Vec::new(),
}
}
@@ -673,6 +873,219 @@ mod tests {
assert!(board.is_passable(1, 0));
}
/// Stamps a crate cell onto an otherwise-open board.
fn crate_at(board: &mut Board, x: usize, y: usize) {
*board.get_mut(x, y) = (Archetype::Crate.default_glyph(), Archetype::Crate);
}
/// Stamps a wall cell onto an otherwise-open board.
fn wall_at(board: &mut Board, x: usize, y: usize) {
*board.get_mut(x, y) = (Archetype::Wall.default_glyph(), Archetype::Wall);
}
#[test]
fn in_bounds_checks_grid_boundaries() {
let board = open_board(3, 2, (0, 0), vec![], &[]);
assert!(board.in_bounds((0, 0)));
assert!(board.in_bounds((2, 1)));
assert!(!board.in_bounds((-1, 0)));
assert!(!board.in_bounds((0, -1)));
assert!(!board.in_bounds((3, 0))); // x == width
assert!(!board.in_bounds((0, 2))); // y == height
}
#[test]
fn can_push_is_read_only_and_correct() {
// Crate with empty space beyond: pushable, and the board is left untouched.
let mut board = open_board(3, 1, (0, 0), vec![], &[]);
crate_at(&mut board, 1, 0);
assert!(board.can_push(1, 0, Direction::East));
assert_eq!(board.get(1, 0).1, Archetype::Crate); // no mutation
assert_eq!(board.get(2, 0).1, Archetype::Empty);
// Crate against a wall: not pushable.
let mut board = open_board(3, 1, (0, 0), vec![], &[]);
crate_at(&mut board, 1, 0);
wall_at(&mut board, 2, 0);
assert!(!board.can_push(1, 0, Direction::East));
}
#[test]
fn player_pushes_single_crate() {
let mut board = open_board(4, 1, (0, 0), vec![], &[]);
crate_at(&mut board, 1, 0);
let mut game = GameState::new(board);
game.try_move(Direction::East);
let b = game.board();
assert_eq!((b.player.x, b.player.y), (1, 0)); // player advanced onto crate's old cell
assert_eq!(b.get(1, 0).1, Archetype::Empty); // crate left this cell
assert_eq!(b.get(2, 0).1, Archetype::Crate); // crate moved one east
}
#[test]
fn push_blocked_by_wall_moves_nothing() {
let mut board = open_board(4, 1, (0, 0), vec![], &[]);
crate_at(&mut board, 1, 0);
wall_at(&mut board, 2, 0);
let mut game = GameState::new(board);
game.try_move(Direction::East);
let b = game.board();
assert_eq!((b.player.x, b.player.y), (0, 0)); // blocked
assert_eq!(b.get(1, 0).1, Archetype::Crate); // crate didn't move
assert_eq!(b.get(2, 0).1, Archetype::Wall); // wall didn't move
}
#[test]
fn push_blocked_by_edge_moves_nothing() {
// Crate on the last column; player pushes it toward the board edge.
let mut board = open_board(2, 1, (0, 0), vec![], &[]);
crate_at(&mut board, 1, 0);
let mut game = GameState::new(board);
game.try_move(Direction::East);
let b = game.board();
assert_eq!((b.player.x, b.player.y), (0, 0));
assert_eq!(b.get(1, 0).1, Archetype::Crate);
}
#[test]
fn cascade_pushes_two_crates() {
let mut board = open_board(5, 1, (0, 0), vec![], &[]);
crate_at(&mut board, 1, 0);
crate_at(&mut board, 2, 0);
let mut game = GameState::new(board);
game.try_move(Direction::East);
let b = game.board();
assert_eq!((b.player.x, b.player.y), (1, 0));
assert_eq!(b.get(1, 0).1, Archetype::Empty);
assert_eq!(b.get(2, 0).1, Archetype::Crate);
assert_eq!(b.get(3, 0).1, Archetype::Crate);
}
#[test]
fn cascade_blocked_by_wall_moves_nothing() {
let mut board = open_board(5, 1, (0, 0), vec![], &[]);
crate_at(&mut board, 1, 0);
crate_at(&mut board, 2, 0);
wall_at(&mut board, 3, 0);
let mut game = GameState::new(board);
game.try_move(Direction::East);
let b = game.board();
assert_eq!((b.player.x, b.player.y), (0, 0));
assert_eq!(b.get(1, 0).1, Archetype::Crate);
assert_eq!(b.get(2, 0).1, Archetype::Crate);
}
#[test]
fn player_pushes_pushable_solid_object() {
// A solid, pushable object is shoved exactly like a crate.
let mut obj = ObjectDef::new(1, 0); // solid by default
obj.pushable = true;
let board = open_board(4, 1, (0, 0), vec![obj], &[]);
let mut game = GameState::new(board);
game.try_move(Direction::East);
let b = game.board();
assert_eq!((b.player.x, b.player.y), (1, 0));
assert_eq!((b.objects[0].x, b.objects[0].y), (2, 0)); // object shoved east
}
#[test]
fn object_pushes_crate_on_init() {
// A scripted object moving east into a crate shoves it (move_object path).
let mut board = open_board(
4,
1,
(0, 0), // player behind the object, out of the push path
vec![scripted_object(1, 0, "m")],
&[("m", "fn init() { move(East); }")],
);
crate_at(&mut board, 2, 0);
let mut game = GameState::new(board);
game.run_init();
let b = game.board();
assert_eq!((b.objects[0].x, b.objects[0].y), (2, 0)); // object advanced
assert_eq!(b.get(2, 0).1, Archetype::Empty); // crate left (2,0)
assert_eq!(b.get(3, 0).1, Archetype::Crate); // crate pushed to (3,0)
}
#[test]
fn pushable_allows_only_its_axis() {
use Direction::*;
for d in [North, South, East, West] {
assert!(!Pushable::No.allows(d));
assert!(Pushable::Any.allows(d));
}
assert!(Pushable::Horizontal.allows(East) && Pushable::Horizontal.allows(West));
assert!(!Pushable::Horizontal.allows(North) && !Pushable::Horizontal.allows(South));
assert!(Pushable::Vertical.allows(North) && Pushable::Vertical.allows(South));
assert!(!Pushable::Vertical.allows(East) && !Pushable::Vertical.allows(West));
}
/// Stamps an archetype cell onto an otherwise-open board.
fn stamp(board: &mut Board, x: usize, y: usize, arch: Archetype) {
*board.get_mut(x, y) = (arch.default_glyph(), arch);
}
#[test]
fn hcrate_pushes_east_but_not_north() {
// Pushing east: the HCrate slides.
let mut board = open_board(4, 1, (0, 0), vec![], &[]);
stamp(&mut board, 1, 0, Archetype::HCrate);
let mut game = GameState::new(board);
game.try_move(Direction::East);
let b = game.board();
assert_eq!((b.player.x, b.player.y), (1, 0));
assert_eq!(b.get(1, 0).1, Archetype::Empty);
assert_eq!(b.get(2, 0).1, Archetype::HCrate);
drop(b);
// Pushing north into an HCrate: blocked, nothing moves.
let mut board = open_board(1, 4, (0, 3), vec![], &[]);
stamp(&mut board, 0, 2, Archetype::HCrate);
let mut game = GameState::new(board);
game.try_move(Direction::North);
let b = game.board();
assert_eq!((b.player.x, b.player.y), (0, 3)); // blocked
assert_eq!(b.get(0, 2).1, Archetype::HCrate); // didn't move
}
#[test]
fn vcrate_pushes_north_but_not_east() {
// Pushing north: the VCrate slides.
let mut board = open_board(1, 4, (0, 3), vec![], &[]);
stamp(&mut board, 0, 2, Archetype::VCrate);
let mut game = GameState::new(board);
game.try_move(Direction::North);
let b = game.board();
assert_eq!((b.player.x, b.player.y), (0, 2));
assert_eq!(b.get(0, 2).1, Archetype::Empty);
assert_eq!(b.get(0, 1).1, Archetype::VCrate);
drop(b);
// Pushing east into a VCrate: blocked, nothing moves.
let mut board = open_board(4, 1, (0, 0), vec![], &[]);
stamp(&mut board, 1, 0, Archetype::VCrate);
let mut game = GameState::new(board);
game.try_move(Direction::East);
let b = game.board();
assert_eq!((b.player.x, b.player.y), (0, 0)); // blocked
assert_eq!(b.get(1, 0).1, Archetype::VCrate); // didn't move
}
#[test]
fn fresh_board_is_valid_and_reports_errors() {
let mut board = open_board(1, 1, (0, 0), vec![], &[]);
assert!(board.is_valid());
board.report_error("something went wrong");
assert!(!board.is_valid());
assert_eq!(board.load_errors().len(), 1);
}
#[test]
fn directional_crate_default_glyph_tiles() {
assert_eq!(Archetype::HCrate.default_glyph().tile, 29);
assert_eq!(Archetype::VCrate.default_glyph().tile, 18);
}
#[test]
fn init_runs_only_on_run_init_not_at_construction() {
let board = board_with_object(