Files
kiln/src/game.rs
T

298 lines
12 KiB
Rust
Raw Normal View History

use eframe::egui::Color32;
use serde::Deserialize;
/// The visual representation of a single board cell.
///
/// `Glyph` holds everything needed to draw one cell on screen: which character
/// to display and what colors to use. It is stored per-cell (not per archetype),
/// so individual cells can vary their appearance independently — for example,
/// a field of "fire" tiles where each flame has a slightly different color
/// while all sharing the same [`Archetype`] behavior.
///
/// `Glyph` values come from the map file palette and are set at load time.
/// The player is the only entity whose glyph is hardcoded at runtime
/// (see [`Glyph::player`]).
#[derive(Clone, Copy)]
pub struct Glyph {
/// The character to display in this cell.
pub ch: char,
/// Foreground (text) color.
pub fg: Color32,
/// Background color, drawn as a filled rectangle behind the character.
pub bg: Color32,
}
impl Glyph {
/// Returns the glyph used to render the player: `@` in light blue on black.
///
/// This is the only hardcoded glyph; all other glyphs come from the map
/// file palette. It will be removed once the player becomes a scripted
/// object with its own palette entry.
pub fn player() -> Self {
Self { ch: '@', fg: Color32::LIGHT_BLUE, bg: Color32::BLACK }
}
}
/// The behavioral properties of a board cell at runtime.
///
/// `Behavior` is a plain data struct returned by [`Archetype::behavior`]. It
/// contains the properties the engine needs to simulate a cell — currently
/// passability and opacity. Future properties (pushable, shootable, etc.) can
/// be added here without changing call sites.
///
/// For scripted objects (`Archetype::Object`), the behavior will eventually be
/// determined by the Rhai script rather than this struct. See the Object variant
/// for details.
#[derive(Copy, Clone, Debug)]
pub struct Behavior {
/// Whether an entity can walk through this cell.
pub passable: bool,
/// Whether this cell blocks line of sight (reserved for future rendering).
pub opaque: bool,
}
/// A class of board cell, encoding its default behavior and appearance.
///
/// `Archetype` is an enum of the element types the engine knows about. Each
/// variant provides a default [`Behavior`] (via [`Archetype::behavior`]) and a
/// default [`Glyph`] (via [`Archetype::default_glyph`]) used when the editor
/// stamps a cell.
///
/// Map files reference archetypes by [`name`](Archetype::name) (e.g. `"wall"`),
/// so the list of variants can be reordered without breaking saved games.
///
/// ## Object special case
///
/// `Archetype::Object` currently returns a static default `Behavior`.
/// TODO: In the future, Object passability and opacity will come from the cell's Rhai script
/// rather than from this enum. [`Board::is_passable`] will need a special branch
/// at that point. `ErrorBlock` is used as a sentinel for unrecognized archetype
/// names in map files — it should never appear in a valid board.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Archetype {
/// An open cell; the player and other entities can pass through it.
Empty,
/// A solid wall; impassable and opaque.
Wall,
/// A scripted object. Behavior defaults to impassable until script-driven.
Object,
/// Sentinel for map files that reference an unknown archetype name.
/// Renders as a yellow `?` on red to make the error visible in-game.
ErrorBlock,
}
impl Archetype {
/// Returns the default [`Behavior`] for this archetype.
///
/// For `Object`, this is a placeholder until Rhai scripts drive the behavior.
pub fn behavior(&self) -> Behavior {
match self {
Archetype::Empty => Behavior { passable: true, opaque: false },
Archetype::Wall => Behavior { passable: false, opaque: true },
Archetype::Object => Behavior { passable: false, opaque: false },
Archetype::ErrorBlock => Behavior { passable: false, opaque: true },
}
}
/// Returns the canonical name used to reference this archetype in map files.
pub fn name(&self) -> &'static str {
match self {
Archetype::Empty => "empty",
Archetype::Wall => "wall",
Archetype::Object => "object",
Archetype::ErrorBlock => "error_block",
}
}
/// Returns the default glyph painted when the editor stamps this archetype.
///
/// This glyph is used only for new cells created in the editor; existing
/// cells retain their own per-cell glyph.
pub fn default_glyph(&self) -> Glyph {
match self {
Archetype::Empty => Glyph { ch: ' ', fg: Color32::BLACK, bg: Color32::BLACK },
Archetype::Wall => Glyph { ch: '#', fg: Color32::from_rgb(0x80, 0x80, 0x80), bg: Color32::from_rgb(0x60, 0x60, 0x60) },
Archetype::Object => Glyph { ch: '?', fg: Color32::YELLOW, bg: Color32::BLACK },
// Visually distinct so malformed map files are immediately obvious.
Archetype::ErrorBlock => Glyph { ch: '?', fg: Color32::YELLOW, bg: Color32::RED },
}
}
}
impl TryFrom<&str> for Archetype {
type Error = String;
/// Parses an archetype by its map-file name.
///
/// Returns an error for unrecognized names; the caller should substitute
/// [`Archetype::ErrorBlock`] and log the error so the problem is visible.
fn try_from(name: &str) -> Result<Self, Self::Error> {
match name {
"empty" => Ok(Archetype::Empty),
"wall" => Ok(Archetype::Wall),
"object" => Ok(Archetype::Object),
_ => Err(format!("unknown archetype: {name}")),
}
}
}
/// The archetypes available for placement in the editor, in display order.
///
/// `ErrorBlock` is excluded — it is a sentinel for load errors, not a valid
/// editing choice.
pub const ALL_ARCHETYPES: &[Archetype] = &[Archetype::Empty, Archetype::Wall, Archetype::Object];
/// A scripted object placed on the board, loaded from a map file.
///
/// `ObjectDef` represents a tile that has Rhai script attached to it.
/// Scripts can respond to events like the player touching or shooting the
/// tile. Objects are parsed from `[[objects]]` entries in `.toml` map files
/// and stored on [`Board`].
///
/// **Not yet runtime-wired.** Objects are loaded and stored but their scripts
/// are not yet executed. Scripting dispatch is a future feature.
#[derive(Deserialize)]
#[allow(dead_code)]
pub struct ObjectDef {
/// Column of this object on the board (0-indexed).
pub x: usize,
/// Row of this object on the board (0-indexed).
pub y: usize,
/// The Rhai script source for this object.
pub script: String,
}
/// A portal that teleports the player to a named entry point on another board.
///
/// Portals are loaded from `[[portals]]` entries in `.toml` map files and
/// stored on [`Board`]. When the player steps onto a portal's cell, they
/// should be moved to `target_entry` on the board named by `target_map`.
///
/// **Not yet runtime-wired.** Portal navigation (multi-board loading and
/// switching) is a future feature.
#[derive(Deserialize)]
#[allow(dead_code)]
pub struct PortalDef {
/// Column of this portal on the board (0-indexed).
pub x: usize,
/// Row of this portal on the board (0-indexed).
pub y: usize,
/// File name (without extension) of the target board, e.g. `"cave"`.
pub target_map: String,
/// Named entry point on the target board where the player arrives.
pub target_entry: String,
}
/// The player's current position on the board.
///
/// The player is currently a special entity rendered on top of the board
/// 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.
#[derive(Copy, Clone)]
pub struct Player {
/// Column position (0-indexed, increasing rightward).
pub x: i32,
/// Row position (0-indexed, increasing downward).
pub y: i32,
}
/// The complete state of one game board (a single room or screen).
///
/// `Board` is the central data structure of the engine, equivalent to a
/// "board" in ZZT. It contains everything needed to represent and run one
/// self-contained area of the game world:
///
/// - A grid of cells, each with a visual representation ([`Glyph`]) and an [`Archetype`]
/// - The current player position
/// - Scripted objects and portals (loaded but not yet active)
///
/// ## Cell storage
///
/// Cells are stored as `(Glyph, Archetype)` tuples in a row-major `Vec`.
/// Each cell directly owns its visual and behavioral class — there is no
/// separate element palette or index indirection. Access cells with
/// [`Board::get`] and [`Board::get_mut`] using `(x, y)` coordinates.
/// Use [`Board::is_passable`] for collision checks.
#[allow(dead_code)]
pub struct Board {
/// Width of the board in cells.
pub width: usize,
/// Height of the board in cells.
pub height: usize,
/// Row-major grid of `(Glyph, Archetype)` pairs. Use [`Board::get`] to
/// access by `(x, y)` coordinates.
pub(crate) cells: Vec<(Glyph, Archetype)>,
/// Current player position. See [`Player`] for caveats about its future.
pub player: Player,
/// Scripted objects on this board. Parsed from the map file; not yet active.
pub objects: Vec<ObjectDef>,
/// Portals on this board. Parsed from the map file; not yet active.
pub portals: Vec<PortalDef>,
}
impl Board {
/// Returns a reference to the cell at `(x, y)`.
///
/// The cell is a `(Glyph, Archetype)` tuple. Panics if `x` or `y` are
/// out of bounds.
pub fn get(&self, x: usize, y: usize) -> &(Glyph, Archetype) {
&self.cells[y * self.width + x]
}
/// 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 the archetype at `(x, y)` allows entities to pass through.
///
/// Panics if `x` or `y` are out of bounds.
pub fn is_passable(&self, x: usize, y: usize) -> bool {
let (_, arch) = self.get(x, y);
// Derive passability from the archetype's behavior.
// Object cells will need special handling here once scripts are wired.
arch.behavior().passable
}
}
/// Holds the active game board and provides game-logic operations.
///
/// `GameState` is the boundary between the engine (rendering, input) and the
/// game data ([`Board`]). It owns the current board and exposes methods for
/// actions that involve game rules — currently just player movement.
///
/// As scripting and event dispatch are added, `GameState` will grow to handle
/// routing input events to the appropriate Rhai scripts.
pub struct GameState {
/// The currently active board.
pub board: Board,
}
impl GameState {
/// Creates a `GameState` from a pre-loaded [`Board`].
pub fn new(board: Board) -> Self {
Self { board }
}
/// Attempts to move the player by `(dx, dy)` cells.
///
/// 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) {
let nx = self.board.player.x + dx;
let ny = self.board.player.y + dy;
if nx >= 0 && ny >= 0 {
let nx = nx as usize;
let ny = ny as usize;
if nx < self.board.width && ny < self.board.height && self.board.is_passable(nx, ny) {
self.board.player.x = nx as i32;
self.board.player.y = ny as i32;
}
}
}
}