more scripting, objects moving

This commit is contained in:
2026-06-06 17:36:00 -05:00
parent 8ac6da184c
commit a5f60e22e1
5 changed files with 781 additions and 240 deletions
+392 -65
View File
@@ -1,5 +1,5 @@
use crate::log::LogLine;
use crate::script::{Direction, GameCommand, ScriptHost};
use crate::script::{Action, Direction, ScriptHost};
use color::Rgba8;
use serde::{Deserialize, Serialize};
use std::cell::{Ref, RefCell, RefMut};
@@ -352,10 +352,13 @@ impl ObjectDef {
/// The single solid occupant of a board cell, returned by [`Board::solid_at`].
///
/// At most one solid — a grid [`Archetype`] *or* an [`ObjectDef`] — may occupy a
/// cell (the invariant enforced at load time), so this represents the one thing a
/// mover would collide with there.
/// At most one solid — the player, a grid [`Archetype`], *or* an [`ObjectDef`] — may
/// occupy a cell (the invariant enforced at load time), so this represents the one
/// thing a mover would collide with there.
pub enum Solid<'a> {
/// The player occupies the cell. The player is solid (it blocks movers) and
/// pushable in any direction (see [`Board::is_pushable`]).
Player,
/// The cell's grid archetype is itself solid (e.g. [`Archetype::Wall`]).
Cell(Archetype),
/// A solid [`ObjectDef`] occupies the cell.
@@ -510,6 +513,10 @@ impl Board {
/// [`crate::map_file`]), this returns that one occupant or `None`.
/// Panics if `x` or `y` are out of bounds.
pub fn solid_at(&self, x: usize, y: usize) -> Option<Solid<'_>> {
// The player wins its cell (load-time invariant), so it is the solid there.
if self.player.x == x as i32 && self.player.y == y as i32 {
return Some(Solid::Player);
}
// A solid object shadows the grid cell it sits on.
if let Some(obj) = self.object_at(x, y)
&& obj.solid
@@ -539,6 +546,7 @@ impl Board {
/// 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::Player) => true, // the player is pushable in any direction
Some(Solid::Cell(a)) => a.behavior().pushable.allows(dir),
Some(Solid::Object(o)) => o.pushable,
None => false,
@@ -606,7 +614,11 @@ impl Board {
/// 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)
// The player owns its cell, so move it before considering objects/grid.
if self.player.x == x as i32 && self.player.y == y as i32 {
self.player.x = tx as i32;
self.player.y = ty as i32;
} else if let Some(idx) = self.object_index_at(x, y)
&& self.objects[idx].solid
{
self.objects[idx].x = tx;
@@ -662,7 +674,7 @@ impl GameState {
scripts,
};
// Surface any compile-time script errors collected during ScriptHost::new.
state.apply_commands();
state.drain_errors();
state
}
@@ -681,86 +693,135 @@ impl GameState {
self.log.push(line);
}
/// Runs the `init()` hook of every scripted object, then applies the commands
/// they queued. Call once, after the whole map is loaded and the game is about
/// to start — never during map deserialization, since a script may inspect the
/// board.
/// Runs the `init()` hook of every scripted object, pumps their queues, and
/// resolves the resulting actions. Call once, after the whole map is loaded and
/// the game is about to start — never during map deserialization, since a script
/// may inspect the board.
pub fn run_init(&mut self) {
self.scripts.run_init();
self.apply_commands();
self.resolve();
}
/// Advances real-time game state by `dt` (the elapsed time since the last
/// tick). Called once per frame by the front-end's game loop; drives every
/// scripted object's `tick(dt)` hook, then applies the commands they queued.
/// Advances real-time game state by `dt` (the elapsed time since the last tick).
/// Called once per frame by the front-end's game loop. Counts down object
/// cooldowns, drives every scripted object's `tick(dt)` hook (pumping each queue),
/// then resolves the actions that were promoted onto the board queue.
pub fn tick(&mut self, dt: Duration) {
self.scripts.run_tick(dt.as_secs_f64());
self.apply_commands();
let secs = dt.as_secs_f64();
self.scripts.advance_timers(secs);
self.scripts.run_tick(secs);
self.resolve();
}
/// Drains the script command queue and applies each command. Runs *after* a
/// script batch, when nothing holds a borrow of the board — so the mutations
/// here can't conflict with the read getters scripts use during execution.
fn apply_commands(&mut self) {
for cmd in self.scripts.take_commands() {
match cmd.kind {
GameCommand::Log(line) => self.log.push(line),
// TODO: errors are only logged for now. This is the place to halt
// execution / set an error state when a script faults.
GameCommand::Error(msg) => self.log.push(LogLine::raw(msg)),
GameCommand::SetTile(tile) => {
if let Some(obj) = self.board_mut().objects.get_mut(cmd.source) {
obj.glyph.tile = tile;
/// Drains errors collected by the script host into the game log.
fn drain_errors(&mut self) {
// TODO: errors are only logged for now. This is the place to halt execution /
// set an error state when a script faults.
let errors = self.scripts.take_errors();
self.log.extend(errors);
}
/// Resolves the board queue: applies each promoted action to the board, then fires
/// the `bump` hooks the moves triggered.
///
/// Done in two phases so no `board_mut` borrow is held while `bump` scripts run
/// (they read the board through its getters): phase A mutates the board and records
/// `(bumped_object, bumper)` pairs; phase B fires the bumps after the borrow drops.
fn resolve(&mut self) {
let actions = self.scripts.take_board_queue();
// Logs are collected here rather than pushed inline, since the board borrow
// below also borrows `self`.
let mut logs: Vec<LogLine> = Vec::new();
let mut bumps: Vec<(usize, i64)> = Vec::new();
{
let mut board = self.board_mut();
for ba in actions {
match ba.action {
Action::Move(dir) => {
if let Some(bumped) = step_object(&mut board, ba.source, dir) {
bumps.push((bumped, ba.source as i64));
}
}
Action::SetTile(tile) => {
if let Some(obj) = board.objects.get_mut(ba.source) {
obj.glyph.tile = tile;
}
}
Action::Log(line) => logs.push(line),
}
GameCommand::Move(dir) => self.move_object(cmd.source, dir),
}
}
}
/// 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 target = (ox as i32 + dx, oy as i32 + 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
let obj = &mut board.objects[idx];
obj.x = nx;
obj.y = ny;
self.log.extend(logs);
for (bumped, bumper) in bumps {
self.scripts.run_bump(bumped, bumper);
}
self.drain_errors();
}
/// Attempts to move the player one cell in `dir`.
///
/// 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).
/// passable nor a pushable solid that can be shoved aside. No-ops silently (the
/// caller does not need to check). If the target cell holds a solid object, that
/// object's `bump(-1)` hook fires (whether or not the player ends up moving).
pub fn try_move(&mut self, dir: Direction) {
let (dx, dy): (i32, i32) = dir.into();
let mut board = self.board_mut();
let target = (board.player.x + dx, board.player.y + dy);
if !board.in_bounds(target) {
return;
let bumped;
{
let (dx, dy): (i32, i32) = dir.into();
let mut board = self.board_mut();
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);
// A solid object in the way is bumped by the player (id -1).
bumped = match board.solid_at(nx, ny) {
Some(Solid::Object(_)) => board.object_index_at(nx, ny),
_ => None,
};
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;
}
}
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;
if let Some(idx) = bumped {
self.scripts.run_bump(idx, -1);
self.drain_errors();
}
}
}
/// Moves object `idx` one cell in `dir` on `board`, returning the index of a solid
/// object it bumped (its target cell was occupied by that object), if any.
///
/// The move itself proceeds only 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`]). The
/// bump is recorded whenever a solid object occupies the target — whether it gets
/// pushed aside or blocks the move — since something tried to move into it. Walls and
/// crates carry no script, so only solid objects yield a bump.
fn step_object(board: &mut Board, idx: usize, dir: Direction) -> Option<usize> {
let (dx, dy): (i32, i32) = dir.into();
let (ox, oy) = board.objects.get(idx).map(|o| (o.x, o.y))?;
let target = (ox as i32 + dx, oy as i32 + dy);
if !board.in_bounds(target) {
return None;
}
let (nx, ny) = (target.0 as usize, target.1 as usize);
// Capture the bumped object before any push relocates it (its index is stable).
let bumped = match board.solid_at(nx, ny) {
Some(Solid::Object(_)) => board.object_index_at(nx, ny),
_ => None,
};
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;
}
bumped
}
#[cfg(test)]
mod tests {
use super::*;
@@ -838,8 +899,9 @@ mod tests {
#[test]
fn solid_at_reports_wall_object_and_empty() {
// A 3×1 board: empty floor, a wall, and an empty cell holding one object.
let mut board = open_board(3, 1, (0, 0), vec![], &[]);
// A 4×1 board: empty floor, a wall, an object, and the player parked at (3,0)
// (kept off the asserted cells, since the player is itself solid).
let mut board = open_board(4, 1, (3, 0), vec![], &[]);
board.cells[1] = (Archetype::Wall.default_glyph(), Archetype::Wall);
// A solid object on the otherwise-empty cell (2, 0).
board.objects.push(ObjectDef::new(2, 0)); // solid by default
@@ -1249,4 +1311,269 @@ mod tests {
assert_eq!(b.objects[0].x, 1); // moved east from 0
assert_eq!(b.objects[1].x, 3); // moved west from 4
}
#[test]
fn move_cost_rate_limits_repeated_moves() {
// init queues two moves; only the first resolves immediately, the second must
// wait the full 250 ms cooldown.
let board = open_board(
5,
1,
(0, 0), // player to the west, out of the object's path
vec![scripted_object(1, 0, "m")],
&[("m", "fn init() { move(East); move(East); }")],
);
let mut game = GameState::new(board);
game.run_init();
assert_eq!(game.board().objects[0].x, 2); // first move applied (1 -> 2)
// 200 ms of ticks: still inside the cooldown, no further movement.
game.tick(Duration::from_millis(100));
game.tick(Duration::from_millis(100));
assert_eq!(game.board().objects[0].x, 2);
// Crossing the 250 ms mark releases the queued second move.
game.tick(Duration::from_millis(100));
assert_eq!(game.board().objects[0].x, 3);
}
#[test]
fn blocked_move_still_costs_cooldown() {
// A move into a wall fails but still charges the 250 ms cooldown, so a second
// queued move (into open space) is delayed just as a successful move would be.
let mut board = open_board(
3,
3,
(0, 0),
vec![scripted_object(1, 1, "m")],
&[("m", "fn init() { move(East); move(South); }")],
);
wall_at(&mut board, 2, 1); // blocks the eastward move
let mut game = GameState::new(board);
game.run_init();
// First (eastward) move is blocked by the wall: object hasn't moved.
assert_eq!((game.board().objects[0].x, game.board().objects[0].y), (1, 1));
// The blocked move charged the cooldown, so South is still pending here.
game.tick(Duration::from_millis(100));
game.tick(Duration::from_millis(100));
assert_eq!((game.board().objects[0].x, game.board().objects[0].y), (1, 1));
// Past 250 ms the queued South move resolves.
game.tick(Duration::from_millis(100));
assert_eq!((game.board().objects[0].x, game.board().objects[0].y), (1, 2));
}
#[test]
fn queue_length_reports_pending_actions() {
// Two zero-cost actions are queued before the length is read, then all three
// (incl. the log) drain in one pump.
let board = open_board(
3,
1,
(0, 0),
vec![scripted_object(1, 0, "q")],
&[("q", "fn init() { set_tile(5); set_tile(6); log(`len=${Queue.length()}`); }")],
);
let mut game = GameState::new(board);
game.run_init();
assert!(log_texts(&game).iter().any(|t| t == "len=2"));
assert_eq!(game.board().objects[0].glyph.tile, 6); // last set_tile won
}
#[test]
fn queue_clear_drops_pending_actions() {
// clear() empties the output queue mid-script, so the queued moves never run.
let board = open_board(
5,
1,
(0, 0),
vec![scripted_object(1, 0, "c")],
&[("c", "fn init() { move(East); move(East); Queue.clear(); }")],
);
let mut game = GameState::new(board);
game.run_init();
game.tick(Duration::from_millis(300));
assert_eq!(game.board().objects[0].x, 1); // never moved
}
#[test]
fn blocked_reports_solid_and_clear() {
// Solid ahead (a wall): blocked() is true.
let mut board = open_board(
3,
1,
(0, 0),
vec![scripted_object(1, 0, "b")],
&[("b", "fn init() { if blocked(East) { set_tile(9); } else { set_tile(7); } }")],
);
wall_at(&mut board, 2, 0);
let mut game = GameState::new(board);
game.run_init();
assert_eq!(game.board().objects[0].glyph.tile, 9);
// Open ahead, nothing pending: blocked() is false.
let board = open_board(
3,
1,
(0, 0),
vec![scripted_object(1, 0, "b")],
&[("b", "fn init() { if blocked(East) { set_tile(9); } else { set_tile(7); } }")],
);
let mut game = GameState::new(board);
game.run_init();
assert_eq!(game.board().objects[0].glyph.tile, 7);
}
#[test]
fn blocked_sees_earlier_objects_pending_move() {
// obj0 (earlier in the array) queues a move into (2,1); obj1 checks blocked()
// toward that same cell and must see the pending move.
let board = open_board(
5,
3,
(0, 0),
vec![
scripted_object(1, 1, "mover"),
scripted_object(3, 1, "checker"),
],
&[
("mover", "fn tick(dt) { move(East); }"),
(
"checker",
"fn tick(dt) { if blocked(West) { set_tile(1); } else { set_tile(2); } }",
),
],
);
let mut game = GameState::new(board);
game.tick(Duration::from_millis(16));
let b = game.board();
assert_eq!((b.objects[0].x, b.objects[0].y), (2, 1)); // mover advanced
assert_eq!(b.objects[1].glyph.tile, 1); // checker saw the pending move
}
#[test]
fn collision_priority_resolves_in_array_order_and_bumps() {
// Two objects move into the same empty cell (1,0). obj0 (earlier) wins it;
// obj1 is blocked and bumps obj0. obj1 itself receives no bump.
let board = open_board(
3,
2,
(0, 1), // player off the contested row
vec![scripted_object(0, 0, "e"), scripted_object(2, 0, "w")],
&[
(
"e",
"fn init() { move(East); } fn bump(id) { log(`o0 by ${id}`); }",
),
(
"w",
"fn init() { move(West); } fn bump(id) { log(`o1 by ${id}`); }",
),
],
);
let mut game = GameState::new(board);
game.run_init();
// The bump fires during resolution but its log is emitted into obj0's queue;
// a later tick (past both objects' move cooldown) flushes it to the game log.
game.tick(Duration::from_millis(300));
{
let b = game.board();
assert_eq!((b.objects[0].x, b.objects[0].y), (1, 0)); // obj0 won the cell
assert_eq!((b.objects[1].x, b.objects[1].y), (2, 0)); // obj1 blocked
}
let logs = log_texts(&game);
assert!(logs.iter().any(|t| t == "o0 by 1")); // obj0 bumped by obj1
assert!(!logs.iter().any(|t| t.starts_with("o1 by"))); // obj1 not bumped
}
#[test]
fn player_bump_fires_with_negative_one() {
// The player walks into a solid scripted object; the object is bumped with -1
// and the player does not move onto it.
let board = open_board(
3,
1,
(0, 0),
vec![scripted_object(1, 0, "b")],
&[("b", "fn bump(id) { log(`bumped by ${id}`); }")],
);
let mut game = GameState::new(board);
game.run_init();
game.try_move(Direction::East);
assert_eq!((game.board().player.x, game.board().player.y), (0, 0)); // blocked
// bump's log is emitted into the object's queue; a tick flushes it.
game.tick(Duration::from_millis(16));
assert!(log_texts(&game).iter().any(|t| t == "bumped by -1"));
}
#[test]
fn solid_at_reports_player() {
// The player's own cell is solid (and thus impassable to movers).
let board = open_board(3, 1, (1, 0), vec![], &[]);
match board.solid_at(1, 0) {
Some(Solid::Player) => {}
_ => panic!("expected Solid::Player at the player's cell"),
}
assert!(!board.is_passable(1, 0));
}
#[test]
fn push_into_player_pushes_player() {
// Crate shoved east into the player slides the player along into open space.
let mut board = open_board(4, 1, (2, 0), vec![], &[]);
crate_at(&mut board, 1, 0);
assert!(board.can_push(1, 0, Direction::East));
board.push(1, 0, Direction::East);
assert_eq!(board.get(1, 0).1, Archetype::Empty); // crate left its cell
assert_eq!(board.get(2, 0).1, Archetype::Crate); // crate took the player's old cell
assert_eq!((board.player.x, board.player.y), (3, 0)); // player shoved east
}
#[test]
fn push_into_player_blocked_by_wall() {
// Player backed against a wall: the push has nowhere to go, so nothing moves
// and the player is never overlapped.
let mut board = open_board(4, 1, (2, 0), vec![], &[]);
crate_at(&mut board, 1, 0);
wall_at(&mut board, 3, 0);
assert!(!board.can_push(1, 0, Direction::East));
board.push(1, 0, Direction::East); // no-op
assert_eq!(board.get(1, 0).1, Archetype::Crate);
assert_eq!((board.player.x, board.player.y), (2, 0));
}
#[test]
fn object_push_into_player() {
// A scripted object moving into the player pushes the player when there's room.
let board = open_board(
5,
1,
(2, 0),
vec![scripted_object(1, 0, "m")],
&[("m", "fn init() { move(East); }")],
);
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 took player's cell
assert_eq!((b.player.x, b.player.y), (3, 0)); // player shoved east
}
// With a wall behind the player, the object is blocked and nothing moves.
let mut board = open_board(
4,
1,
(2, 0),
vec![scripted_object(1, 0, "m")],
&[("m", "fn init() { move(East); }")],
);
wall_at(&mut board, 3, 0);
let mut game = GameState::new(board);
game.run_init();
let b = game.board();
assert_eq!((b.objects[0].x, b.objects[0].y), (1, 0)); // object blocked
assert_eq!((b.player.x, b.player.y), (2, 0)); // player not pushed
}
}