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
+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();