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(
+20
View File
@@ -44,6 +44,26 @@ impl LogLine {
}
}
/// Creates an error line: a single span in red on black, used for surfacing
/// nonfatal problems (e.g. recoverable map-load errors).
pub fn error(text: impl Into<String>) -> Self {
Self::new().push(
text,
Some(Rgba8 {
r: 255,
g: 0,
b: 0,
a: 255,
}),
Some(Rgba8 {
r: 0,
g: 0,
b: 0,
a: 255,
}),
)
}
/// Appends a styled span and returns `self`, so calls can be chained when
/// building a multi-color line.
pub fn push(mut self, text: impl Into<String>, fg: Option<Rgba8>, bg: Option<Rgba8>) -> Self {
+233 -45
View File
@@ -1,4 +1,5 @@
use crate::game::{Archetype, Board, FontSpec, Glyph, ObjectDef, Player, PortalDef};
use crate::log::LogLine;
use color::Rgba8;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
@@ -45,8 +46,9 @@ pub struct MapHeader {
pub width: usize,
/// Height of the board in cells. Must match the number of rows in `[grid] content`.
pub height: usize,
/// Starting position of the player as `[x, y]` (0-indexed, origin top-left).
pub player_start: [i32; 2],
/// Where the player starts: either explicit `[x, y]` coordinates or a single
/// grid character to locate (e.g. `"@"`). See [`PlayerStart`].
pub player_start: PlayerStart,
/// Name of the board-level script in the `[scripts]` table, if any.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub board_script_name: Option<String>,
@@ -92,6 +94,22 @@ impl TileIndex {
}
}
/// Where the player starts in a map file: explicit coordinates or a single grid
/// character to locate.
///
/// Untagged like [`TileIndex`], so `player_start = [30, 12]` parses as
/// [`PlayerStart::Coord`] and `player_start = "@"` as [`PlayerStart::Char`]
/// (`Coord` is listed first, so a TOML array matches it and a string falls
/// through to `Char`).
#[derive(Deserialize, Serialize)]
#[serde(untagged)]
pub enum PlayerStart {
/// Explicit `[x, y]` coordinates (0-indexed, origin top-left).
Coord([i32; 2]),
/// A single grid character marking the player's cell (its cell loads `Empty`).
Char(char),
}
/// One entry in the `[palette]` table.
///
/// Each entry is keyed by a single character (e.g. `"#"` or `" "`).
@@ -220,6 +238,16 @@ impl TryFrom<MapFile> for Board {
let w = mf.map.width;
let h = mf.map.height;
// Nonfatal problems collected as we load; surfaced on the Board so callers
// can read `Board::is_valid`. Only grid-dimension mismatch (below) is fatal.
let mut load_errors: Vec<LogLine> = Vec::new();
// If the player is placed by a grid char, this is that char (e.g. '@').
let player_char = match mf.map.player_start {
PlayerStart::Char(c) => Some(c),
PlayerStart::Coord(_) => None,
};
// Pass 1: build a char → (Glyph, Archetype) lookup from the palette.
let mut palette: HashMap<char, (Glyph, Archetype)> = HashMap::new();
@@ -236,7 +264,7 @@ impl TryFrom<MapFile> for Board {
palette.insert(key_char, (glyph, archetype));
}
Err(e) => {
eprintln!("{e}");
load_errors.push(LogLine::error(e));
palette.insert(
key_char,
(Archetype::ErrorBlock.default_glyph(), Archetype::ErrorBlock),
@@ -277,36 +305,45 @@ impl TryFrom<MapFile> for Board {
};
// `palette` is mutually exclusive with explicit `x`/`y`.
if e.x.is_some() || e.y.is_some() {
eprintln!("object {i}: specify either x/y or palette, not both; skipping object");
load_errors.push(LogLine::error(format!(
"object {i}: specify either x/y or palette, not both; skipping object"
)));
skip[i] = true;
continue;
}
// It must be exactly one character.
let mut chs = p.chars();
let (Some(ch), None) = (chs.next(), chs.next()) else {
eprintln!(
load_errors.push(LogLine::error(format!(
"object {i}: palette must be a single character (got {p:?}); skipping object"
);
)));
skip[i] = true;
continue;
};
// It can't reuse a terrain palette key.
if palette.contains_key(&ch) {
eprintln!(
"object {i}: palette char '{ch}' is already a [palette] key; skipping object"
);
// The player's char (e.g. '@') is reserved.
if Some(ch) == player_char {
load_errors.push(LogLine::error(format!(
"object {i}: palette char '{ch}' is reserved for the player; skipping object"
)));
skip[i] = true;
continue;
}
// It must be unique across objects — a clash drops both owners.
// It can't reuse a terrain palette key.
if palette.contains_key(&ch) {
load_errors.push(LogLine::error(format!(
"object {i}: palette char '{ch}' is already a [palette] key; skipping object"
)));
skip[i] = true;
continue;
}
// It must be unique across objects — keep the first claimant, drop later ones.
use std::collections::hash_map::Entry;
match palette_char_owner.entry(ch) {
Entry::Occupied(o) => {
eprintln!(
"object palette char '{ch}' is used by more than one object; skipping both"
);
Entry::Occupied(_) => {
load_errors.push(LogLine::error(format!(
"object {i}: palette char '{ch}' is already used by another object; skipping object"
)));
skip[i] = true;
skip[*o.get()] = true;
}
Entry::Vacant(v) => {
v.insert(i);
@@ -321,33 +358,48 @@ impl TryFrom<MapFile> for Board {
let mut cells: Vec<(Glyph, Archetype)> = Vec::with_capacity(w * h);
let mut obj_palette_pos: HashMap<char, (usize, usize)> = HashMap::new();
let mut obj_palette_count: HashMap<char, usize> = HashMap::new();
// Where the player's char was first seen, and how many times (for recovery).
let mut player_grid_pos: Option<(usize, usize)> = None;
let mut player_grid_count: usize = 0;
for (y, line) in rows.iter().enumerate() {
for (x, ch) in line.chars().enumerate() {
if let Some(&cell) = palette.get(&ch) {
cells.push(cell);
} else if Some(ch) == player_char {
// Player placeholder: floor underneath; keep the first sighting.
cells.push(canonical_empty);
player_grid_pos.get_or_insert((x, y));
player_grid_count += 1;
} else if palette_char_owner.contains_key(&ch) {
cells.push(canonical_empty);
obj_palette_pos.insert(ch, (x, y));
obj_palette_pos.entry(ch).or_insert((x, y));
*obj_palette_count.entry(ch).or_insert(0) += 1;
} else {
eprintln!("unknown grid character '{ch}' at ({x}, {y}); using error block");
load_errors.push(LogLine::error(format!(
"unknown grid character '{ch}' at ({x}, {y}); using error block"
)));
cells.push((Archetype::ErrorBlock.default_glyph(), Archetype::ErrorBlock));
}
}
}
// Each surviving object palette char must appear in the grid exactly once.
// Resolve each surviving object palette char: missing → drop; multiple →
// keep the object at the first occurrence (already recorded) and report.
for (&ch, &owner) in &palette_char_owner {
if skip[owner] {
continue;
}
let n = obj_palette_count.get(&ch).copied().unwrap_or(0);
if n != 1 {
eprintln!(
"object palette char '{ch}' appears {n} times in the grid \
(must be exactly once); skipping object"
);
skip[owner] = true;
match obj_palette_count.get(&ch).copied().unwrap_or(0) {
0 => {
load_errors.push(LogLine::error(format!(
"object palette char '{ch}' not found in the grid; skipping object"
)));
skip[owner] = true;
}
1 => {}
n => load_errors.push(LogLine::error(format!(
"object palette char '{ch}' appears {n} times in the grid; using the first"
))),
}
}
@@ -361,6 +413,44 @@ impl TryFrom<MapFile> for Board {
// `solid_occupied` is seeded from the grid (solid archetypes); each solid
// object then claims its cell, and a second solid on a cell is dropped.
let mut solid_occupied: Vec<bool> = cells.iter().map(|(_, a)| a.behavior().solid).collect();
// Resolve the player's cell (nonfatal; fall back to (0, 0) on any problem),
// then let the player *win* its cell: clear solid terrain under it and claim
// the cell so a solid object placed here is dropped by the loop below.
let (px, py) = match mf.map.player_start {
PlayerStart::Coord([x, y])
if x >= 0 && y >= 0 && (x as usize) < w && (y as usize) < h =>
{
(x as usize, y as usize)
}
PlayerStart::Coord([x, y]) => {
load_errors.push(LogLine::error(format!(
"player_start ({x}, {y}) is out of bounds; placing player at (0, 0)"
)));
(0, 0)
}
PlayerStart::Char(c) => match (player_grid_pos, player_grid_count) {
(Some(pos), 1) => pos,
(Some(pos), n) => {
load_errors.push(LogLine::error(format!(
"player char '{c}' appears {n} times in the grid; using the first"
)));
pos
}
_ => {
load_errors.push(LogLine::error(format!(
"player char '{c}' not found in the grid; placing player at (0, 0)"
)));
(0, 0)
}
},
};
let pidx = py * w + px;
if solid_occupied[pidx] {
cells[pidx] = canonical_empty;
}
solid_occupied[pidx] = true;
let mut objects: Vec<ObjectDef> = Vec::new();
for (i, e) in mf.objects.into_iter().enumerate() {
if skip[i] {
@@ -374,13 +464,15 @@ impl TryFrom<MapFile> for Board {
match (e.x, e.y) {
(Some(x), Some(y)) if x < w && y < h => (x, y),
(Some(x), Some(y)) => {
eprintln!("object {i}: x/y ({x}, {y}) out of bounds; skipping object");
load_errors.push(LogLine::error(format!(
"object {i}: x/y ({x}, {y}) out of bounds; skipping object"
)));
continue;
}
_ => {
eprintln!(
load_errors.push(LogLine::error(format!(
"object {i}: must specify both x and y (or a palette char); skipping object"
);
)));
continue;
}
}
@@ -402,9 +494,13 @@ impl TryFrom<MapFile> for Board {
if obj.solid {
let idx = y * w + x;
if solid_occupied[idx] {
eprintln!(
"object {i}: solid object at ({x}, {y}) conflicts with an existing solid; skipping object"
);
// The player silently wins its own cell (by design); any other
// solid collision is a reportable mistake.
if idx != pidx {
load_errors.push(LogLine::error(format!(
"object {i}: solid object at ({x}, {y}) conflicts with an existing solid; skipping object"
)));
}
continue;
}
solid_occupied[idx] = true;
@@ -418,8 +514,8 @@ impl TryFrom<MapFile> for Board {
height: h,
cells,
player: Player {
x: mf.map.player_start[0],
y: mf.map.player_start[1],
x: px as i32,
y: py as i32,
},
objects,
portals: mf.portals,
@@ -427,6 +523,7 @@ impl TryFrom<MapFile> for Board {
zoom: mf.map.zoom,
scripts: mf.scripts,
board_script_name: mf.map.board_script_name,
load_errors,
})
}
}
@@ -544,7 +641,7 @@ impl From<&Board> for MapFile {
name: board.name.clone(),
width: board.width,
height: board.height,
player_start: [board.player.x, board.player.y],
player_start: PlayerStart::Coord([board.player.x, board.player.y]),
board_script_name: board.board_script_name.clone(),
zoom: board.zoom,
},
@@ -602,7 +699,7 @@ mod tests {
name = "Test"
width = 3
height = 1
player_start = [0, 0]
player_start = [2, 0]
[palette]
"." = {{ archetype = "empty", tile = 46, fg = "#000000", bg = "#000000" }}
@@ -638,19 +735,26 @@ content = """
fn palette_char_absent_from_grid_drops_object() {
let board = load_board(&map_3x1("...", &obj_palette("G", "")));
assert!(board.objects.is_empty());
assert!(!board.is_valid()); // a dropped object is a recoverable error
}
#[test]
fn palette_char_appearing_twice_drops_object() {
fn palette_char_appearing_twice_uses_first() {
// `G` appears at (0,0) and (2,0): the object lands at the first, and the
// map is flagged invalid (an extra appearance was reported).
let board = load_board(&map_3x1("G.G", &obj_palette("G", "")));
assert!(board.objects.is_empty());
assert_eq!(board.objects.len(), 1);
assert_eq!((board.objects[0].x, board.objects[0].y), (0, 0));
assert!(!board.is_valid());
}
#[test]
fn palette_char_reused_by_two_objects_drops_both() {
fn palette_char_reused_by_two_objects_keeps_first() {
// Two objects claim `G`: the first keeps it, the later one is dropped.
let two = format!("{}\n{}", obj_palette("G", ""), obj_palette("G", ""));
let board = load_board(&map_3x1("G..", &two));
assert!(board.objects.is_empty());
assert_eq!(board.objects.len(), 1);
assert!(!board.is_valid());
}
#[test]
@@ -678,6 +782,88 @@ content = """
let obj = "[[objects]]\nx = 1\ny = 0\ntile = 64\nfg = \"#00FFFF\"\nbg = \"#000000\"\n";
let board = load_board(&map_3x1("...", &format!("{obj}{obj}")));
assert_eq!(board.objects.len(), 1);
assert!(!board.is_valid());
}
/// A 1-row map of the given `width` with a raw `player_start` TOML value
/// (`start`, e.g. `[1, 0]` or `"@"`), grid, and objects block.
fn player_map(width: usize, start: &str, grid: &str, objects: &str) -> String {
format!(
r##"
[map]
name = "Test"
width = {width}
height = 1
player_start = {start}
[palette]
"." = {{ archetype = "empty", tile = 46, fg = "#000000", bg = "#000000" }}
"#" = {{ archetype = "wall", tile = 35, fg = "#808080", bg = "#606060" }}
[grid]
content = """
{grid}
"""
{objects}
"##
)
}
#[test]
fn player_coords_place_the_player() {
let b = load_board(&player_map(3, "[1, 0]", "...", ""));
assert_eq!((b.player.x, b.player.y), (1, 0));
assert!(b.is_valid());
}
#[test]
fn player_char_places_on_empty_floor() {
let b = load_board(&player_map(3, "\"@\"", ".@.", ""));
assert_eq!((b.player.x, b.player.y), (1, 0));
assert_eq!(b.get(1, 0).1, Archetype::Empty);
assert!(b.is_valid());
}
#[test]
fn player_wins_solid_terrain_silently() {
// Player coords land on a wall: the wall is cleared, no error reported.
let b = load_board(&player_map(3, "[0, 0]", "#..", ""));
assert_eq!((b.player.x, b.player.y), (0, 0));
assert_eq!(b.get(0, 0).1, Archetype::Empty);
assert!(b.is_valid());
}
#[test]
fn player_wins_against_a_solid_object_silently() {
// A solid object on the player's cell is dropped, silently (player wins).
let obj = "[[objects]]\nx = 1\ny = 0\ntile = 64\nfg = \"#00FFFF\"\nbg = \"#000000\"\n";
let b = load_board(&player_map(3, "[1, 0]", "...", obj));
assert!(b.objects.is_empty());
assert!(b.is_valid());
}
#[test]
fn player_char_is_reserved_from_objects() {
// An object trying to use '@' is dropped; the player is still placed.
let obj = "[[objects]]\npalette = \"@\"\ntile = 64\nfg = \"#00FFFF\"\nbg = \"#000000\"\n";
let b = load_board(&player_map(3, "\"@\"", "@..", obj));
assert_eq!((b.player.x, b.player.y), (0, 0));
assert!(b.objects.is_empty());
assert!(!b.is_valid());
}
#[test]
fn player_char_appearing_twice_uses_first() {
let b = load_board(&player_map(3, "\"@\"", "@.@", ""));
assert_eq!((b.player.x, b.player.y), (0, 0));
assert!(!b.is_valid());
}
#[test]
fn player_char_missing_falls_back_to_origin() {
let b = load_board(&player_map(3, "\"@\"", "...", ""));
assert_eq!((b.player.x, b.player.y), (0, 0));
assert!(!b.is_valid());
}
/// Minimal valid TOML with a configurable grid, used as a base for dimension tests.
@@ -742,20 +928,22 @@ content = """
#[test]
fn object_archetype_in_palette_produces_error_block() {
// "object" is no longer a valid palette archetype; it should produce ErrorBlock.
// "object" is no longer a valid palette archetype; it should produce
// ErrorBlock. Player is placed away from the O cell so it isn't cleared.
let toml = r##"
[map]
name = "Test"
width = 1
width = 2
height = 1
player_start = [0, 0]
player_start = [1, 0]
[palette]
"O" = { archetype = "object", tile = 64, fg = "#00FFFF", bg = "#000000" }
"." = { archetype = "empty", tile = 46, fg = "#000000", bg = "#000000" }
[grid]
content = """
O
O.
"""
"##;
let mf: MapFile = toml::from_str(toml).unwrap();