mirror of
https://github.com/Xevion/Pac-Man.git
synced 2025-12-10 14:07:59 -06:00
Compare commits
5 Commits
398d041d96
...
v0.48.5
| Author | SHA1 | Date | |
|---|---|---|---|
| da3c8e8284 | |||
| 9c0711a54c | |||
| 4598dc07e2 | |||
| 9c9dc5f423 | |||
| 12ee16faab |
25
src/app.rs
25
src/app.rs
@@ -12,6 +12,11 @@ use crate::constants::{CANVAS_SIZE, LOOP_TIME, SCALE};
|
|||||||
use crate::game::Game;
|
use crate::game::Game;
|
||||||
use crate::platform::get_platform;
|
use crate::platform::get_platform;
|
||||||
|
|
||||||
|
/// Main application wrapper that manages SDL initialization, window lifecycle, and the game loop.
|
||||||
|
///
|
||||||
|
/// Handles platform-specific setup, maintains consistent frame timing, and delegates
|
||||||
|
/// game logic to the contained `Game` instance. The app manages focus state to
|
||||||
|
/// optimize CPU usage when the window loses focus.
|
||||||
pub struct App {
|
pub struct App {
|
||||||
pub game: Game,
|
pub game: Game,
|
||||||
last_tick: Instant,
|
last_tick: Instant,
|
||||||
@@ -20,6 +25,16 @@ pub struct App {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl App {
|
impl App {
|
||||||
|
/// Initializes SDL subsystems, creates the game window, and sets up the game state.
|
||||||
|
///
|
||||||
|
/// Performs comprehensive initialization including video/audio subsystems, platform-specific
|
||||||
|
/// console setup, window creation with proper scaling, and canvas configuration. All SDL
|
||||||
|
/// resources are leaked to maintain 'static lifetimes required by the game architecture.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// Returns `GameError::Sdl` if any SDL initialization step fails, or propagates
|
||||||
|
/// errors from `Game::new()` during game state setup.
|
||||||
pub fn new() -> GameResult<Self> {
|
pub fn new() -> GameResult<Self> {
|
||||||
let sdl_context: &'static Sdl = Box::leak(Box::new(sdl2::init().map_err(|e| GameError::Sdl(e.to_string()))?));
|
let sdl_context: &'static Sdl = Box::leak(Box::new(sdl2::init().map_err(|e| GameError::Sdl(e.to_string()))?));
|
||||||
let video_subsystem: &'static VideoSubsystem =
|
let video_subsystem: &'static VideoSubsystem =
|
||||||
@@ -70,6 +85,16 @@ impl App {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Executes a single frame of the game loop with consistent timing and optional sleep.
|
||||||
|
///
|
||||||
|
/// Calculates delta time since the last frame, runs game logic via `game.tick()`,
|
||||||
|
/// and implements frame rate limiting by sleeping for remaining time if the frame
|
||||||
|
/// completed faster than the target `LOOP_TIME`. Sleep behavior varies based on
|
||||||
|
/// window focus to conserve CPU when the game is not active.
|
||||||
|
///
|
||||||
|
/// # Returns
|
||||||
|
///
|
||||||
|
/// `true` if the game should continue running, `false` if the game requested exit.
|
||||||
pub fn run(&mut self) -> bool {
|
pub fn run(&mut self) -> bool {
|
||||||
{
|
{
|
||||||
let start = Instant::now();
|
let start = Instant::now();
|
||||||
|
|||||||
23
src/asset.rs
23
src/asset.rs
@@ -5,17 +5,28 @@
|
|||||||
use std::borrow::Cow;
|
use std::borrow::Cow;
|
||||||
use strum_macros::EnumIter;
|
use strum_macros::EnumIter;
|
||||||
|
|
||||||
|
/// Enumeration of all game assets with cross-platform loading support.
|
||||||
|
///
|
||||||
|
/// Each variant corresponds to a specific file that can be loaded either from
|
||||||
|
/// binary-embedded data or embedded filesystem (Emscripten).
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, EnumIter)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, EnumIter)]
|
||||||
pub enum Asset {
|
pub enum Asset {
|
||||||
Wav1,
|
Wav1,
|
||||||
Wav2,
|
Wav2,
|
||||||
Wav3,
|
Wav3,
|
||||||
Wav4,
|
Wav4,
|
||||||
|
/// Main sprite atlas containing all game graphics (atlas.png)
|
||||||
AtlasImage,
|
AtlasImage,
|
||||||
|
/// Terminal Vector font for text rendering (TerminalVector.ttf)
|
||||||
Font,
|
Font,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Asset {
|
impl Asset {
|
||||||
|
/// Returns the relative file path for this asset within the game's asset directory.
|
||||||
|
///
|
||||||
|
/// Paths are consistent across platforms and used by the Emscripten backend
|
||||||
|
/// for filesystem loading. Desktop builds embed assets directly and don't
|
||||||
|
/// use these paths at runtime.
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub fn path(&self) -> &str {
|
pub fn path(&self) -> &str {
|
||||||
use Asset::*;
|
use Asset::*;
|
||||||
@@ -35,7 +46,17 @@ mod imp {
|
|||||||
use crate::error::AssetError;
|
use crate::error::AssetError;
|
||||||
use crate::platform::get_platform;
|
use crate::platform::get_platform;
|
||||||
|
|
||||||
/// Returns the raw bytes of the given asset.
|
/// Loads asset bytes using the appropriate platform-specific method.
|
||||||
|
///
|
||||||
|
/// On desktop platforms, returns embedded compile-time data via `include_bytes!`.
|
||||||
|
/// On Emscripten, loads from the filesystem using the asset's path. The returned
|
||||||
|
/// `Cow` allows zero-copy access to embedded data while supporting owned data
|
||||||
|
/// when loaded from disk.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// Returns `AssetError::NotFound` if the asset file cannot be located (Emscripten only),
|
||||||
|
/// or `AssetError::Io` for filesystem I/O failures.
|
||||||
pub fn get_asset_bytes(asset: Asset) -> Result<Cow<'static, [u8]>, AssetError> {
|
pub fn get_asset_bytes(asset: Asset) -> Result<Cow<'static, [u8]>, AssetError> {
|
||||||
get_platform().get_asset_bytes(asset)
|
get_platform().get_asset_bytes(asset)
|
||||||
}
|
}
|
||||||
|
|||||||
23
src/audio.rs
23
src/audio.rs
@@ -114,9 +114,11 @@ impl Audio {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Plays the "eat" sound effect.
|
/// Plays the next waka eating sound in the cycle of four variants.
|
||||||
///
|
///
|
||||||
/// If audio is disabled or muted, this function does nothing.
|
/// Automatically rotates through the four eating sound assets. The sound plays on channel 0 and the internal sound index
|
||||||
|
/// advances to the next variant. Silently returns if audio is disabled, muted,
|
||||||
|
/// or no sounds were loaded successfully.
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub fn eat(&mut self) {
|
pub fn eat(&mut self) {
|
||||||
if self.disabled || self.muted || self.sounds.is_empty() {
|
if self.disabled || self.muted || self.sounds.is_empty() {
|
||||||
@@ -136,9 +138,11 @@ impl Audio {
|
|||||||
self.next_sound_index = (self.next_sound_index + 1) % self.sounds.len();
|
self.next_sound_index = (self.next_sound_index + 1) % self.sounds.len();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Instantly mute or unmute all channels.
|
/// Instantly mutes or unmutes all audio channels by adjusting their volume.
|
||||||
///
|
///
|
||||||
/// If audio is disabled, this function does nothing.
|
/// Sets all 4 mixer channels to zero volume when muting, or restores them to
|
||||||
|
/// their default volume (32) when unmuting. The mute state is tracked internally
|
||||||
|
/// regardless of whether audio is disabled, allowing the state to be preserved.
|
||||||
pub fn set_mute(&mut self, mute: bool) {
|
pub fn set_mute(&mut self, mute: bool) {
|
||||||
if !self.disabled {
|
if !self.disabled {
|
||||||
let channels = 4;
|
let channels = 4;
|
||||||
@@ -151,12 +155,19 @@ impl Audio {
|
|||||||
self.muted = mute;
|
self.muted = mute;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns `true` if the audio is muted.
|
/// Returns the current mute state regardless of whether audio is functional.
|
||||||
|
///
|
||||||
|
/// This tracks the user's mute preference and will return `true` if muted
|
||||||
|
/// even when the audio system is disabled due to initialization failures.
|
||||||
pub fn is_muted(&self) -> bool {
|
pub fn is_muted(&self) -> bool {
|
||||||
self.muted
|
self.muted
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns `true` if the audio system is disabled.
|
/// Returns whether the audio system failed to initialize and is non-functional.
|
||||||
|
///
|
||||||
|
/// Audio can be disabled due to SDL2_mixer initialization failures, missing
|
||||||
|
/// audio device, or failure to load any sound assets. When disabled, all
|
||||||
|
/// audio operations become no-ops.
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub fn is_disabled(&self) -> bool {
|
pub fn is_disabled(&self) -> bool {
|
||||||
self.disabled
|
self.disabled
|
||||||
|
|||||||
@@ -4,6 +4,11 @@ use std::time::Duration;
|
|||||||
|
|
||||||
use glam::UVec2;
|
use glam::UVec2;
|
||||||
|
|
||||||
|
/// Target frame duration for 60 FPS game loop timing.
|
||||||
|
///
|
||||||
|
/// Calculated as 1/60th of a second (≈16.67ms).
|
||||||
|
///
|
||||||
|
/// Written out explicitly to satisfy const-eval constraints.
|
||||||
pub const LOOP_TIME: Duration = Duration::from_nanos((1_000_000_000.0 / 60.0) as u64);
|
pub const LOOP_TIME: Duration = Duration::from_nanos((1_000_000_000.0 / 60.0) as u64);
|
||||||
|
|
||||||
/// The size of each cell, in pixels.
|
/// The size of each cell, in pixels.
|
||||||
@@ -14,9 +19,16 @@ pub const BOARD_CELL_SIZE: UVec2 = UVec2::new(28, 31);
|
|||||||
/// The scale factor for the window (integer zoom)
|
/// The scale factor for the window (integer zoom)
|
||||||
pub const SCALE: f32 = 2.6;
|
pub const SCALE: f32 = 2.6;
|
||||||
|
|
||||||
/// The offset of the game board from the top-left corner of the window, in cells.
|
/// Game board offset from window origin to reserve space for HUD elements.
|
||||||
|
///
|
||||||
|
/// The 3-cell vertical offset (24 pixels) provides space at the top of the
|
||||||
|
/// screen for score display, player lives, and other UI elements.
|
||||||
pub const BOARD_CELL_OFFSET: UVec2 = UVec2::new(0, 3);
|
pub const BOARD_CELL_OFFSET: UVec2 = UVec2::new(0, 3);
|
||||||
/// The offset of the game board from the top-left corner of the window, in pixels.
|
|
||||||
|
/// Pixel-space equivalent of `BOARD_CELL_OFFSET` for rendering calculations.
|
||||||
|
///
|
||||||
|
/// Automatically calculated from the cell offset to maintain consistency
|
||||||
|
/// when the cell size changes. Used for positioning sprites and debug overlays.
|
||||||
pub const BOARD_PIXEL_OFFSET: UVec2 = UVec2::new(BOARD_CELL_OFFSET.x * CELL_SIZE, BOARD_CELL_OFFSET.y * CELL_SIZE);
|
pub const BOARD_PIXEL_OFFSET: UVec2 = UVec2::new(BOARD_CELL_OFFSET.x * CELL_SIZE, BOARD_CELL_OFFSET.y * CELL_SIZE);
|
||||||
/// The size of the canvas, in pixels.
|
/// The size of the canvas, in pixels.
|
||||||
pub const CANVAS_SIZE: UVec2 = UVec2::new(
|
pub const CANVAS_SIZE: UVec2 = UVec2::new(
|
||||||
@@ -24,22 +36,24 @@ pub const CANVAS_SIZE: UVec2 = UVec2::new(
|
|||||||
(BOARD_CELL_SIZE.y + BOARD_CELL_OFFSET.y) * CELL_SIZE,
|
(BOARD_CELL_SIZE.y + BOARD_CELL_OFFSET.y) * CELL_SIZE,
|
||||||
);
|
);
|
||||||
|
|
||||||
/// An enum representing the different types of tiles on the map.
|
/// Map tile types that define gameplay behavior and collision properties.
|
||||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||||
pub enum MapTile {
|
pub enum MapTile {
|
||||||
/// An empty tile.
|
/// Traversable space with no collectible items
|
||||||
Empty,
|
Empty,
|
||||||
/// A wall tile.
|
|
||||||
Wall,
|
Wall,
|
||||||
/// A regular pellet.
|
/// Small collectible. Implicitly a traversable tile.
|
||||||
Pellet,
|
Pellet,
|
||||||
/// A power pellet.
|
/// Large collectible. Implicitly a traversable tile.
|
||||||
PowerPellet,
|
PowerPellet,
|
||||||
/// A tunnel tile.
|
/// Special traversable tile that connects to tunnel portals.
|
||||||
Tunnel,
|
Tunnel,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The raw layout of the game board, as a 2D array of characters.
|
/// ASCII art representation of the classic Pac-Man maze layout.
|
||||||
|
///
|
||||||
|
/// Uses character symbols to define the game world. This layout is parsed by `MapTileParser`
|
||||||
|
/// to generate the navigable graph and collision geometry.
|
||||||
pub const RAW_BOARD: [&str; BOARD_CELL_SIZE.y as usize] = [
|
pub const RAW_BOARD: [&str; BOARD_CELL_SIZE.y as usize] = [
|
||||||
"############################",
|
"############################",
|
||||||
"#............##............#",
|
"#............##............#",
|
||||||
|
|||||||
@@ -2,19 +2,36 @@ use bevy_ecs::{entity::Entity, event::Event};
|
|||||||
|
|
||||||
use crate::map::direction::Direction;
|
use crate::map::direction::Direction;
|
||||||
|
|
||||||
|
/// Player input commands that trigger specific game actions.
|
||||||
|
///
|
||||||
|
/// Commands are generated by the input system in response to keyboard events
|
||||||
|
/// and processed by appropriate game systems to modify state or behavior.
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
pub enum GameCommand {
|
pub enum GameCommand {
|
||||||
|
/// Request immediate game shutdown
|
||||||
Exit,
|
Exit,
|
||||||
|
/// Set Pac-Man's movement direction
|
||||||
MovePlayer(Direction),
|
MovePlayer(Direction),
|
||||||
|
/// Cycle through debug visualization modes
|
||||||
ToggleDebug,
|
ToggleDebug,
|
||||||
|
/// Toggle audio mute state
|
||||||
MuteAudio,
|
MuteAudio,
|
||||||
|
/// Restart the current level with fresh entity positions and items
|
||||||
ResetLevel,
|
ResetLevel,
|
||||||
|
/// Pause or resume game ticking logic
|
||||||
TogglePause,
|
TogglePause,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Global events that flow through the ECS event system to coordinate game behavior.
|
||||||
|
///
|
||||||
|
/// Events enable loose coupling between systems - input generates commands, collision
|
||||||
|
/// detection reports overlaps, and various systems respond appropriately without
|
||||||
|
/// direct dependencies.
|
||||||
#[derive(Event, Clone, Copy, Debug, PartialEq, Eq)]
|
#[derive(Event, Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
pub enum GameEvent {
|
pub enum GameEvent {
|
||||||
|
/// Player input command to be processed by relevant game systems
|
||||||
Command(GameCommand),
|
Command(GameCommand),
|
||||||
|
/// Physical overlap detected between two entities requiring gameplay response
|
||||||
Collision(Entity, Entity),
|
Collision(Entity, Entity),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
50
src/game.rs
50
src/game.rs
@@ -48,16 +48,37 @@ use crate::{
|
|||||||
texture::sprite::{AtlasMapper, SpriteAtlas},
|
texture::sprite::{AtlasMapper, SpriteAtlas},
|
||||||
};
|
};
|
||||||
|
|
||||||
/// The `Game` struct is the main entry point for the game.
|
/// Core game state manager built on the Bevy ECS architecture.
|
||||||
///
|
///
|
||||||
/// It contains the game's state and logic, and is responsible for
|
/// Orchestrates all game systems through a centralized `World` containing entities,
|
||||||
/// handling user input, updating the game state, and rendering the game.
|
/// components, and resources, while a `Schedule` defines system execution order.
|
||||||
|
/// Handles initialization of graphics resources, entity spawning, and per-frame
|
||||||
|
/// game logic coordination. SDL2 resources are stored as `NonSend` to respect
|
||||||
|
/// thread safety requirements while integrating with the ECS.
|
||||||
pub struct Game {
|
pub struct Game {
|
||||||
pub world: World,
|
pub world: World,
|
||||||
pub schedule: Schedule,
|
pub schedule: Schedule,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Game {
|
impl Game {
|
||||||
|
/// Initializes the complete game state including ECS world, graphics, and entity spawning.
|
||||||
|
///
|
||||||
|
/// Performs extensive setup: creates render targets and debug textures, loads and parses
|
||||||
|
/// the sprite atlas, renders the static map to a cached texture, builds the navigation
|
||||||
|
/// graph from the board layout, spawns Pac-Man with directional animations, creates
|
||||||
|
/// all four ghosts with their AI behavior, and places collectible items throughout
|
||||||
|
/// the maze. Registers event types and configures the system execution schedule.
|
||||||
|
///
|
||||||
|
/// # Arguments
|
||||||
|
///
|
||||||
|
/// * `canvas` - SDL2 rendering context with static lifetime for ECS storage
|
||||||
|
/// * `texture_creator` - SDL2 texture factory for creating render targets
|
||||||
|
/// * `event_pump` - SDL2 event polling interface for input handling
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// Returns `GameError` for SDL2 failures, asset loading problems, atlas parsing
|
||||||
|
/// errors, or entity initialization issues.
|
||||||
pub fn new(
|
pub fn new(
|
||||||
canvas: &'static mut Canvas<Window>,
|
canvas: &'static mut Canvas<Window>,
|
||||||
texture_creator: &'static mut TextureCreator<WindowContext>,
|
texture_creator: &'static mut TextureCreator<WindowContext>,
|
||||||
@@ -289,7 +310,12 @@ impl Game {
|
|||||||
Ok(Game { world, schedule })
|
Ok(Game { world, schedule })
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Spowns all four ghosts at their starting positions with appropriate textures.
|
/// Creates and spawns all four ghosts with unique AI personalities and directional animations.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// Returns `GameError::Texture` if any ghost sprite cannot be found in the atlas,
|
||||||
|
/// typically indicating missing or misnamed sprite files.
|
||||||
fn spawn_ghosts(world: &mut World) -> GameResult<()> {
|
fn spawn_ghosts(world: &mut World) -> GameResult<()> {
|
||||||
// Extract the data we need first to avoid borrow conflicts
|
// Extract the data we need first to avoid borrow conflicts
|
||||||
let ghost_start_positions = {
|
let ghost_start_positions = {
|
||||||
@@ -394,9 +420,21 @@ impl Game {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Ticks the game state.
|
/// Executes one frame of game logic by running all scheduled ECS systems.
|
||||||
///
|
///
|
||||||
/// Returns true if the game should exit.
|
/// Updates the world's delta time resource and runs the complete system pipeline:
|
||||||
|
/// input processing, entity movement, collision detection, item collection,
|
||||||
|
/// audio playback, animation updates, and rendering. Each system operates on
|
||||||
|
/// relevant entities and modifies world state, with the schedule ensuring
|
||||||
|
/// proper execution order and data dependencies.
|
||||||
|
///
|
||||||
|
/// # Arguments
|
||||||
|
///
|
||||||
|
/// * `dt` - Frame delta time in seconds for time-based animations and movement
|
||||||
|
///
|
||||||
|
/// # Returns
|
||||||
|
///
|
||||||
|
/// `true` if the game should terminate (exit command received), `false` to continue
|
||||||
pub fn tick(&mut self, dt: f32) -> bool {
|
pub fn tick(&mut self, dt: f32) -> bool {
|
||||||
self.world.insert_resource(DeltaTime(dt));
|
self.world.insert_resource(DeltaTime(dt));
|
||||||
|
|
||||||
|
|||||||
@@ -11,25 +11,37 @@ use tracing::debug;
|
|||||||
|
|
||||||
use crate::error::{GameResult, MapError};
|
use crate::error::{GameResult, MapError};
|
||||||
|
|
||||||
/// The starting positions of the entities in the game.
|
/// Predefined spawn locations for all game entities within the navigation graph.
|
||||||
|
///
|
||||||
|
/// These positions are determined during map parsing and graph construction.
|
||||||
pub struct NodePositions {
|
pub struct NodePositions {
|
||||||
|
/// Pac-Man's starting position in the lower section of the maze
|
||||||
pub pacman: NodeId,
|
pub pacman: NodeId,
|
||||||
|
/// Blinky starts at the ghost house entrance
|
||||||
pub blinky: NodeId,
|
pub blinky: NodeId,
|
||||||
|
/// Pinky starts in the left area of the ghost house
|
||||||
pub pinky: NodeId,
|
pub pinky: NodeId,
|
||||||
|
/// Inky starts in the right area of the ghost house
|
||||||
pub inky: NodeId,
|
pub inky: NodeId,
|
||||||
|
/// Clyde starts in the center of the ghost house
|
||||||
pub clyde: NodeId,
|
pub clyde: NodeId,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The main map structure containing the game board and navigation graph.
|
/// Complete maze representation combining visual layout with navigation pathfinding.
|
||||||
|
///
|
||||||
|
/// Transforms the ASCII board layout into a fully connected navigation graph
|
||||||
|
/// while preserving tile-based collision and rendering data. The graph enables
|
||||||
|
/// smooth entity movement with proper pathfinding, while the grid mapping allows
|
||||||
|
/// efficient spatial queries and debug visualization.
|
||||||
#[derive(Resource)]
|
#[derive(Resource)]
|
||||||
pub struct Map {
|
pub struct Map {
|
||||||
/// The node map for entity movement.
|
/// Connected graph of navigable positions.
|
||||||
pub graph: Graph,
|
pub graph: Graph,
|
||||||
/// A mapping from grid positions to node IDs.
|
/// Bidirectional mapping between 2D grid coordinates and graph node indices.
|
||||||
pub grid_to_node: HashMap<IVec2, NodeId>,
|
pub grid_to_node: HashMap<IVec2, NodeId>,
|
||||||
/// A mapping of the starting positions of the entities.
|
/// Predetermined spawn locations for all game entities
|
||||||
pub start_positions: NodePositions,
|
pub start_positions: NodePositions,
|
||||||
/// The raw tile data for the map.
|
/// 2D array of tile types for collision detection and rendering
|
||||||
tiles: [[MapTile; BOARD_CELL_SIZE.y as usize]; BOARD_CELL_SIZE.x as usize],
|
tiles: [[MapTile; BOARD_CELL_SIZE.y as usize]; BOARD_CELL_SIZE.x as usize],
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -162,7 +174,18 @@ impl Map {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Builds the house structure in the graph.
|
/// Constructs the ghost house area with restricted access and internal navigation.
|
||||||
|
///
|
||||||
|
/// Creates a multi-level ghost house with entrance control, internal movement
|
||||||
|
/// areas, and starting positions for each ghost. The house entrance uses
|
||||||
|
/// ghost-only traversal flags to prevent Pac-Man from entering while allowing
|
||||||
|
/// ghosts to exit. Internal nodes are arranged in vertical lines to provide
|
||||||
|
/// distinct starting areas for each ghost character.
|
||||||
|
///
|
||||||
|
/// # Returns
|
||||||
|
///
|
||||||
|
/// Tuple of node IDs: (house_entrance, left_center, center_center, right_center)
|
||||||
|
/// representing the four key positions within the ghost house structure.
|
||||||
fn build_house(
|
fn build_house(
|
||||||
graph: &mut Graph,
|
graph: &mut Graph,
|
||||||
grid_to_node: &HashMap<IVec2, NodeId>,
|
grid_to_node: &HashMap<IVec2, NodeId>,
|
||||||
@@ -296,7 +319,10 @@ impl Map {
|
|||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Builds the tunnel connections in the graph.
|
/// Creates horizontal tunnel portals for instant teleportation across the maze.
|
||||||
|
///
|
||||||
|
/// Establishes the tunnel system that allows entities to instantly travel from the left edge of the maze to the right edge.
|
||||||
|
/// Creates hidden intermediate nodes beyond the visible tunnel entrances and connects them with zero-distance edges for instantaneous traversal.
|
||||||
fn build_tunnels(
|
fn build_tunnels(
|
||||||
graph: &mut Graph,
|
graph: &mut Graph,
|
||||||
grid_to_node: &HashMap<IVec2, NodeId>,
|
grid_to_node: &HashMap<IVec2, NodeId>,
|
||||||
|
|||||||
@@ -4,16 +4,21 @@ use crate::constants::{MapTile, BOARD_CELL_SIZE};
|
|||||||
use crate::error::ParseError;
|
use crate::error::ParseError;
|
||||||
use glam::IVec2;
|
use glam::IVec2;
|
||||||
|
|
||||||
/// Represents the parsed data from a raw board layout.
|
/// Structured representation of parsed ASCII board layout with extracted special positions.
|
||||||
|
///
|
||||||
|
/// Contains the complete board state after character-to-tile conversion, along with
|
||||||
|
/// the locations of special gameplay elements that require additional processing
|
||||||
|
/// during graph construction. Special positions are extracted during parsing to
|
||||||
|
/// enable proper map builder initialization.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct ParsedMap {
|
pub struct ParsedMap {
|
||||||
/// The parsed tile layout.
|
/// 2D array of tiles converted from ASCII characters
|
||||||
pub tiles: [[MapTile; BOARD_CELL_SIZE.y as usize]; BOARD_CELL_SIZE.x as usize],
|
pub tiles: [[MapTile; BOARD_CELL_SIZE.y as usize]; BOARD_CELL_SIZE.x as usize],
|
||||||
/// The positions of the house door tiles.
|
/// Two positions marking the ghost house entrance (represented by '=' characters)
|
||||||
pub house_door: [Option<IVec2>; 2],
|
pub house_door: [Option<IVec2>; 2],
|
||||||
/// The positions of the tunnel end tiles.
|
/// Two positions marking tunnel portals for wraparound teleportation ('T' characters)
|
||||||
pub tunnel_ends: [Option<IVec2>; 2],
|
pub tunnel_ends: [Option<IVec2>; 2],
|
||||||
/// Pac-Man's starting position.
|
/// Starting position for Pac-Man (marked by 'X' character in the layout)
|
||||||
pub pacman_start: Option<IVec2>,
|
pub pacman_start: Option<IVec2>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -21,15 +26,18 @@ pub struct ParsedMap {
|
|||||||
pub struct MapTileParser;
|
pub struct MapTileParser;
|
||||||
|
|
||||||
impl MapTileParser {
|
impl MapTileParser {
|
||||||
/// Parses a single character into a map tile.
|
/// Converts ASCII characters from the board layout into corresponding tile types.
|
||||||
///
|
///
|
||||||
/// # Arguments
|
/// Interprets the character-based maze representation: walls (`#`), collectible
|
||||||
|
/// pellets (`.` and `o`), traversable spaces (` `), tunnel entrances (`T`),
|
||||||
|
/// ghost house doors (`=`), and entity spawn markers (`X`). Special characters
|
||||||
|
/// that don't represent tiles in the final map (like spawn markers) are
|
||||||
|
/// converted to `Empty` tiles while their positions are tracked separately.
|
||||||
///
|
///
|
||||||
/// * `c` - The character to parse
|
/// # Errors
|
||||||
///
|
///
|
||||||
/// # Returns
|
/// Returns `ParseError::UnknownCharacter` for any character not defined
|
||||||
///
|
/// in the game's ASCII art vocabulary.
|
||||||
/// The parsed map tile, or an error if the character is unknown.
|
|
||||||
pub fn parse_character(c: char) -> Result<MapTile, ParseError> {
|
pub fn parse_character(c: char) -> Result<MapTile, ParseError> {
|
||||||
match c {
|
match c {
|
||||||
'#' => Ok(MapTile::Wall),
|
'#' => Ok(MapTile::Wall),
|
||||||
|
|||||||
@@ -10,29 +10,29 @@ mod desktop;
|
|||||||
#[cfg(target_os = "emscripten")]
|
#[cfg(target_os = "emscripten")]
|
||||||
mod emscripten;
|
mod emscripten;
|
||||||
|
|
||||||
/// Platform abstraction trait that defines cross-platform functionality.
|
/// Cross-platform abstraction layer providing unified APIs for platform-specific operations.
|
||||||
pub trait CommonPlatform {
|
pub trait CommonPlatform {
|
||||||
/// Sleep for the specified duration using platform-appropriate method.
|
/// Platform-specific sleep function (required due to Emscripten's non-standard sleep requirements).
|
||||||
|
///
|
||||||
|
/// Provides access to current window focus state, useful for changing sleep algorithm conditionally.
|
||||||
fn sleep(&self, duration: Duration, focused: bool);
|
fn sleep(&self, duration: Duration, focused: bool);
|
||||||
|
|
||||||
/// Get the current time in seconds since some reference point.
|
|
||||||
/// This is available for future use in timing and performance monitoring.
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
fn get_time(&self) -> f64;
|
fn get_time(&self) -> f64;
|
||||||
|
|
||||||
/// Initialize platform-specific console functionality.
|
/// Configures platform-specific console and debugging output capabilities.
|
||||||
fn init_console(&self) -> Result<(), PlatformError>;
|
fn init_console(&self) -> Result<(), PlatformError>;
|
||||||
|
|
||||||
/// Get canvas size for platforms that need it (e.g., Emscripten).
|
/// Retrieves the actual display canvas dimensions.
|
||||||
/// This is available for future use in responsive design.
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
fn get_canvas_size(&self) -> Option<(u32, u32)>;
|
fn get_canvas_size(&self) -> Option<(u32, u32)>;
|
||||||
|
|
||||||
/// Load asset bytes using platform-appropriate method.
|
/// Loads raw asset data using the appropriate platform-specific method.
|
||||||
|
|
||||||
fn get_asset_bytes(&self, asset: Asset) -> Result<Cow<'static, [u8]>, AssetError>;
|
fn get_asset_bytes(&self, asset: Asset) -> Result<Cow<'static, [u8]>, AssetError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the current platform implementation.
|
/// Returns the appropriate platform implementation based on compile-time target.
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub fn get_platform() -> &'static dyn CommonPlatform {
|
pub fn get_platform() -> &'static dyn CommonPlatform {
|
||||||
#[cfg(not(target_os = "emscripten"))]
|
#[cfg(not(target_os = "emscripten"))]
|
||||||
|
|||||||
@@ -9,6 +9,13 @@ use crate::map::builder::Map;
|
|||||||
use crate::systems::components::{Collider, ItemCollider, PacmanCollider};
|
use crate::systems::components::{Collider, ItemCollider, PacmanCollider};
|
||||||
use crate::systems::movement::Position;
|
use crate::systems::movement::Position;
|
||||||
|
|
||||||
|
/// Detects overlapping entities and generates collision events for gameplay systems.
|
||||||
|
///
|
||||||
|
/// Performs distance-based collision detection between Pac-Man and collectible items
|
||||||
|
/// using each entity's position and collision radius. When entities overlap, emits
|
||||||
|
/// a `GameEvent::Collision` for the item system to handle scoring and removal.
|
||||||
|
/// Collision detection accounts for both entities being in motion and supports
|
||||||
|
/// circular collision boundaries for accurate gameplay feel.
|
||||||
pub fn collision_system(
|
pub fn collision_system(
|
||||||
map: Res<Map>,
|
map: Res<Map>,
|
||||||
pacman_query: Query<(Entity, &Position, &Collider), With<PacmanCollider>>,
|
pacman_query: Query<(Entity, &Position, &Collider), With<PacmanCollider>>,
|
||||||
|
|||||||
@@ -14,10 +14,7 @@ use crate::{
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Ghost AI system that handles randomized movement decisions.
|
/// Autonomous ghost AI system implementing randomized movement with backtracking avoidance.
|
||||||
///
|
|
||||||
/// This system runs on all ghosts and makes periodic decisions about
|
|
||||||
/// which direction to move in when they reach intersections.
|
|
||||||
pub fn ghost_movement_system(
|
pub fn ghost_movement_system(
|
||||||
map: Res<Map>,
|
map: Res<Map>,
|
||||||
delta_time: Res<DeltaTime>,
|
delta_time: Res<DeltaTime>,
|
||||||
|
|||||||
@@ -4,7 +4,10 @@ use crate::map::graph::Graph;
|
|||||||
use bevy_ecs::component::Component;
|
use bevy_ecs::component::Component;
|
||||||
use glam::Vec2;
|
use glam::Vec2;
|
||||||
|
|
||||||
/// A unique identifier for a node, represented by its index in the graph's storage.
|
/// Zero-based index identifying a specific node in the navigation graph.
|
||||||
|
///
|
||||||
|
/// Nodes represent discrete movement targets in the maze. The index directly corresponds to the node's position in the
|
||||||
|
/// graph's internal storage arrays.
|
||||||
pub type NodeId = usize;
|
pub type NodeId = usize;
|
||||||
|
|
||||||
/// A component that represents the speed and cardinal direction of an entity.
|
/// A component that represents the speed and cardinal direction of an entity.
|
||||||
@@ -24,15 +27,19 @@ pub enum BufferedDirection {
|
|||||||
Some { direction: Direction, remaining_time: f32 },
|
Some { direction: Direction, remaining_time: f32 },
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Pure spatial position component - works for both static and dynamic entities.
|
/// Entity position state that handles both stationary entities and moving entities.
|
||||||
|
///
|
||||||
|
/// Supports precise positioning during movement between discrete navigation nodes.
|
||||||
|
/// When moving, entities smoothly interpolate along edges while tracking exact distance remaining to the target node.
|
||||||
#[derive(Component, Debug, Copy, Clone, PartialEq)]
|
#[derive(Component, Debug, Copy, Clone, PartialEq)]
|
||||||
pub enum Position {
|
pub enum Position {
|
||||||
Stopped {
|
/// Entity is stationary at a specific graph node.
|
||||||
node: NodeId,
|
Stopped { node: NodeId },
|
||||||
},
|
/// Entity is traveling between two nodes.
|
||||||
Moving {
|
Moving {
|
||||||
from: NodeId,
|
from: NodeId,
|
||||||
to: NodeId,
|
to: NodeId,
|
||||||
|
/// Distance remaining to reach the target node.
|
||||||
remaining_distance: f32,
|
remaining_distance: f32,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -82,9 +89,21 @@ impl Position {
|
|||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Moves the position by a given distance towards it's current target node.
|
/// Advances movement progress by the specified distance with overflow handling.
|
||||||
///
|
///
|
||||||
/// Returns the overflow distance, if any.
|
/// For moving entities, decreases the remaining distance to the target node.
|
||||||
|
/// If the distance would overshoot the target, the entity transitions to
|
||||||
|
/// `Stopped` state and returns the excess distance for chaining movement
|
||||||
|
/// to the next edge in the same frame.
|
||||||
|
///
|
||||||
|
/// # Arguments
|
||||||
|
///
|
||||||
|
/// * `distance` - Distance to travel this frame (typically speed × delta_time)
|
||||||
|
///
|
||||||
|
/// # Returns
|
||||||
|
///
|
||||||
|
/// `Some(overflow)` if the target was reached with distance remaining,
|
||||||
|
/// `None` if still moving or already stopped.
|
||||||
pub fn tick(&mut self, distance: f32) -> Option<f32> {
|
pub fn tick(&mut self, distance: f32) -> Option<f32> {
|
||||||
if distance <= 0.0 || self.is_at_node() {
|
if distance <= 0.0 || self.is_at_node() {
|
||||||
return None;
|
return None;
|
||||||
@@ -127,159 +146,3 @@ impl Position {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// pub fn movement_system(
|
|
||||||
// map: Res<Map>,
|
|
||||||
// delta_time: Res<DeltaTime>,
|
|
||||||
// mut entities: Query<(&mut Position, &mut Movable, &EntityType)>,
|
|
||||||
// mut errors: EventWriter<GameError>,
|
|
||||||
// ) {
|
|
||||||
// for (mut position, mut movable, entity_type) in entities.iter_mut() {
|
|
||||||
// let distance = movable.speed * 60.0 * delta_time.0;
|
|
||||||
|
|
||||||
// match *position {
|
|
||||||
// Position::Stopped { .. } => {
|
|
||||||
// // Check if we have a requested direction to start moving
|
|
||||||
// if let Some(requested_direction) = movable.requested_direction {
|
|
||||||
// if let Some(edge) = map.graph.find_edge_in_direction(position.current_node(), requested_direction) {
|
|
||||||
// if can_traverse(*entity_type, edge) {
|
|
||||||
// // Start moving in the requested direction
|
|
||||||
// let progress = if edge.distance > 0.0 {
|
|
||||||
// distance / edge.distance
|
|
||||||
// } else {
|
|
||||||
// // Zero-distance edge (tunnels) - immediately teleport
|
|
||||||
// tracing::debug!(
|
|
||||||
// "Entity entering tunnel from node {} to node {}",
|
|
||||||
// position.current_node(),
|
|
||||||
// edge.target
|
|
||||||
// );
|
|
||||||
// 1.0
|
|
||||||
// };
|
|
||||||
|
|
||||||
// *position = Position::Moving {
|
|
||||||
// from: position.current_node(),
|
|
||||||
// to: edge.target,
|
|
||||||
// remaining_distance: progress,
|
|
||||||
// };
|
|
||||||
// movable.current_direction = requested_direction;
|
|
||||||
// movable.requested_direction = None;
|
|
||||||
// }
|
|
||||||
// } else {
|
|
||||||
// errors.write(
|
|
||||||
// EntityError::InvalidMovement(format!(
|
|
||||||
// "No edge found in direction {:?} from node {}",
|
|
||||||
// requested_direction,
|
|
||||||
// position.current_node()
|
|
||||||
// ))
|
|
||||||
// .into(),
|
|
||||||
// );
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// Position::Moving {
|
|
||||||
// from,
|
|
||||||
// to,
|
|
||||||
// remaining_distance,
|
|
||||||
// } => {
|
|
||||||
// // Continue moving or handle node transitions
|
|
||||||
// let current_node = *from;
|
|
||||||
// if let Some(edge) = map.graph.find_edge(current_node, *to) {
|
|
||||||
// // Extract target node before mutable operations
|
|
||||||
// let target_node = *to;
|
|
||||||
|
|
||||||
// // Get the current edge for distance calculation
|
|
||||||
// let edge = map.graph.find_edge(current_node, target_node);
|
|
||||||
|
|
||||||
// if let Some(edge) = edge {
|
|
||||||
// // Update progress along the edge
|
|
||||||
// if edge.distance > 0.0 {
|
|
||||||
// *remaining_distance += distance / edge.distance;
|
|
||||||
// } else {
|
|
||||||
// // Zero-distance edge (tunnels) - immediately complete
|
|
||||||
// *remaining_distance = 1.0;
|
|
||||||
// }
|
|
||||||
|
|
||||||
// if *remaining_distance >= 1.0 {
|
|
||||||
// // Reached the target node
|
|
||||||
// let overflow = if edge.distance > 0.0 {
|
|
||||||
// (*remaining_distance - 1.0) * edge.distance
|
|
||||||
// } else {
|
|
||||||
// // Zero-distance edge - use remaining distance for overflow
|
|
||||||
// distance
|
|
||||||
// };
|
|
||||||
// *position = Position::Stopped { node: target_node };
|
|
||||||
|
|
||||||
// let mut continued_moving = false;
|
|
||||||
|
|
||||||
// // Try to use requested direction first
|
|
||||||
// if let Some(requested_direction) = movable.requested_direction {
|
|
||||||
// if let Some(next_edge) = map.graph.find_edge_in_direction(position.node, requested_direction) {
|
|
||||||
// if can_traverse(*entity_type, next_edge) {
|
|
||||||
// let next_progress = if next_edge.distance > 0.0 {
|
|
||||||
// overflow / next_edge.distance
|
|
||||||
// } else {
|
|
||||||
// // Zero-distance edge - immediately complete
|
|
||||||
// 1.0
|
|
||||||
// };
|
|
||||||
|
|
||||||
// *position = Position::Moving {
|
|
||||||
// from: position.current_node(),
|
|
||||||
// to: next_edge.target,
|
|
||||||
// remaining_distance: next_progress,
|
|
||||||
// };
|
|
||||||
// movable.current_direction = requested_direction;
|
|
||||||
// movable.requested_direction = None;
|
|
||||||
// continued_moving = true;
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
// // If no requested direction or it failed, try to continue in current direction
|
|
||||||
// if !continued_moving {
|
|
||||||
// if let Some(next_edge) = map.graph.find_edge_in_direction(position.node, direction) {
|
|
||||||
// if can_traverse(*entity_type, next_edge) {
|
|
||||||
// let next_progress = if next_edge.distance > 0.0 {
|
|
||||||
// overflow / next_edge.distance
|
|
||||||
// } else {
|
|
||||||
// // Zero-distance edge - immediately complete
|
|
||||||
// 1.0
|
|
||||||
// };
|
|
||||||
|
|
||||||
// *position = Position::Moving {
|
|
||||||
// from: position.current_node(),
|
|
||||||
// to: next_edge.target,
|
|
||||||
// remaining_distance: next_progress,
|
|
||||||
// };
|
|
||||||
// // Keep current direction and movement state
|
|
||||||
// continued_moving = true;
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
// // If we couldn't continue moving, stop
|
|
||||||
// if !continued_moving {
|
|
||||||
// *movement_state = MovementState::Stopped;
|
|
||||||
// movable.requested_direction = None;
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// } else {
|
|
||||||
// // Edge not found - this is an inconsistent state
|
|
||||||
// errors.write(
|
|
||||||
// EntityError::InvalidMovement(format!(
|
|
||||||
// "Inconsistent state: Moving on non-existent edge from {} to {}",
|
|
||||||
// current_node, target_node
|
|
||||||
// ))
|
|
||||||
// .into(),
|
|
||||||
// );
|
|
||||||
// *movement_state = MovementState::Stopped;
|
|
||||||
// position.edge_progress = None;
|
|
||||||
// }
|
|
||||||
// } else {
|
|
||||||
// // Movement state says moving but no edge progress - this shouldn't happen
|
|
||||||
// errors.write(EntityError::InvalidMovement("Entity in Moving state but no edge progress".to_string()).into());
|
|
||||||
// *movement_state = MovementState::Stopped;
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|||||||
@@ -17,7 +17,12 @@ use crate::{
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
// Handles player input and control
|
/// Processes player input commands and updates game state accordingly.
|
||||||
|
///
|
||||||
|
/// Handles keyboard-driven commands like movement direction changes, debug mode
|
||||||
|
/// toggling, audio muting, and game exit requests. Movement commands are buffered
|
||||||
|
/// to allow direction changes before reaching intersections, improving gameplay
|
||||||
|
/// responsiveness. Non-movement commands immediately modify global game state.
|
||||||
pub fn player_control_system(
|
pub fn player_control_system(
|
||||||
mut events: EventReader<GameEvent>,
|
mut events: EventReader<GameEvent>,
|
||||||
mut state: ResMut<GlobalState>,
|
mut state: ResMut<GlobalState>,
|
||||||
@@ -64,11 +69,16 @@ pub fn player_control_system(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn can_traverse(entity_type: EntityType, edge: Edge) -> bool {
|
pub fn can_traverse(entity_type: EntityType, edge: Edge) -> bool {
|
||||||
let entity_flags = entity_type.traversal_flags();
|
let entity_flags = entity_type.traversal_flags();
|
||||||
edge.traversal_flags.contains(entity_flags)
|
edge.traversal_flags.contains(entity_flags)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Executes frame-by-frame movement for Pac-Man.
|
||||||
|
///
|
||||||
|
/// Handles movement logic including buffered direction changes, edge traversal validation, and continuous movement between nodes.
|
||||||
|
/// When stopped, prioritizes buffered directions for responsive controls, falling back to current direction.
|
||||||
|
/// Supports movement chaining within a single frame when traveling at high speeds.
|
||||||
pub fn player_movement_system(
|
pub fn player_movement_system(
|
||||||
map: Res<Map>,
|
map: Res<Map>,
|
||||||
delta_time: Res<DeltaTime>,
|
delta_time: Res<DeltaTime>,
|
||||||
|
|||||||
@@ -1,11 +1,19 @@
|
|||||||
use crate::error::{AnimatedTextureError, GameError, GameResult, TextureError};
|
use crate::error::{AnimatedTextureError, GameError, GameResult, TextureError};
|
||||||
use crate::texture::sprite::AtlasTile;
|
use crate::texture::sprite::AtlasTile;
|
||||||
|
|
||||||
|
/// Frame-based animation system for cycling through multiple sprite tiles.
|
||||||
|
///
|
||||||
|
/// Manages automatic frame progression based on elapsed time.
|
||||||
|
/// Uses a time banking system to ensure consistent animation speed regardless of frame rate variations.
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct AnimatedTexture {
|
pub struct AnimatedTexture {
|
||||||
|
/// Sequence of sprite tiles that make up the animation frames
|
||||||
tiles: Vec<AtlasTile>,
|
tiles: Vec<AtlasTile>,
|
||||||
|
/// Duration each frame should be displayed (in seconds)
|
||||||
frame_duration: f32,
|
frame_duration: f32,
|
||||||
|
/// Index of the currently active frame in the tiles vector
|
||||||
current_frame: usize,
|
current_frame: usize,
|
||||||
|
/// Accumulated time since the last frame change (for smooth timing)
|
||||||
time_bank: f32,
|
time_bank: f32,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -25,6 +33,16 @@ impl AnimatedTexture {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Advances the animation by the specified time delta with automatic frame cycling.
|
||||||
|
///
|
||||||
|
/// Accumulates time in the time bank and progresses through frames when enough
|
||||||
|
/// time has elapsed. Supports frame rates independent of game frame rate by
|
||||||
|
/// potentially advancing multiple frames in a single call if `dt` is large.
|
||||||
|
/// Animation loops automatically when reaching the final frame.
|
||||||
|
///
|
||||||
|
/// # Arguments
|
||||||
|
///
|
||||||
|
/// * `dt` - Time elapsed since the last tick (typically frame delta time)
|
||||||
pub fn tick(&mut self, dt: f32) {
|
pub fn tick(&mut self, dt: f32) {
|
||||||
self.time_bank += dt;
|
self.time_bank += dt;
|
||||||
while self.time_bank >= self.frame_duration {
|
while self.time_bank >= self.frame_duration {
|
||||||
|
|||||||
@@ -8,8 +8,10 @@ use std::collections::HashMap;
|
|||||||
|
|
||||||
use crate::error::TextureError;
|
use crate::error::TextureError;
|
||||||
|
|
||||||
|
/// Atlas frame mapping data loaded from JSON metadata files.
|
||||||
#[derive(Clone, Debug, Deserialize)]
|
#[derive(Clone, Debug, Deserialize)]
|
||||||
pub struct AtlasMapper {
|
pub struct AtlasMapper {
|
||||||
|
/// Mapping from sprite name to frame bounds within the atlas texture
|
||||||
pub frames: HashMap<String, MapperFrame>,
|
pub frames: HashMap<String, MapperFrame>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -72,10 +74,19 @@ impl AtlasTile {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// High-performance sprite atlas providing fast texture region lookups and rendering.
|
||||||
|
///
|
||||||
|
/// Combines a single large texture with metadata mapping to enable efficient
|
||||||
|
/// sprite rendering without texture switching. Caches color modulation state
|
||||||
|
/// to minimize redundant SDL2 calls and supports both named sprite lookups
|
||||||
|
/// and optional default color modulation configuration.
|
||||||
pub struct SpriteAtlas {
|
pub struct SpriteAtlas {
|
||||||
|
/// The combined texture containing all sprite frames
|
||||||
texture: Texture<'static>,
|
texture: Texture<'static>,
|
||||||
|
/// Mapping from sprite names to their pixel coordinates within the texture
|
||||||
tiles: HashMap<String, MapperFrame>,
|
tiles: HashMap<String, MapperFrame>,
|
||||||
default_color: Option<Color>,
|
default_color: Option<Color>,
|
||||||
|
/// Cached color modulation state to avoid redundant SDL2 calls
|
||||||
last_modulation: Option<Color>,
|
last_modulation: Option<Color>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,6 +100,12 @@ impl SpriteAtlas {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Retrieves a sprite tile by name from the atlas with fast HashMap lookup.
|
||||||
|
///
|
||||||
|
/// Returns an `AtlasTile` containing the texture coordinates and dimensions
|
||||||
|
/// for the named sprite, or `None` if the sprite name is not found in the
|
||||||
|
/// atlas. The returned tile can be used for immediate rendering or stored
|
||||||
|
/// for repeated use in animations and entity sprites.
|
||||||
pub fn get_tile(&self, name: &str) -> Option<AtlasTile> {
|
pub fn get_tile(&self, name: &str) -> Option<AtlasTile> {
|
||||||
self.tiles.get(name).map(|frame| AtlasTile {
|
self.tiles.get(name).map(|frame| AtlasTile {
|
||||||
pos: U16Vec2::new(frame.x, frame.y),
|
pos: U16Vec2::new(frame.x, frame.y),
|
||||||
|
|||||||
@@ -1,14 +0,0 @@
|
|||||||
use pacman::asset::Asset;
|
|
||||||
use std::path::Path;
|
|
||||||
use strum::IntoEnumIterator;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_asset_paths_valid() {
|
|
||||||
let base_path = Path::new("assets/game/");
|
|
||||||
|
|
||||||
for asset in Asset::iter() {
|
|
||||||
let path = base_path.join(asset.path());
|
|
||||||
assert!(path.exists(), "Asset path does not exist: {:?}", path);
|
|
||||||
assert!(path.is_file(), "Asset path is not a file: {:?}", path);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -2,27 +2,34 @@ use pacman::constants::*;
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_raw_board_structure() {
|
fn test_raw_board_structure() {
|
||||||
|
// Test board dimensions match expected size
|
||||||
assert_eq!(RAW_BOARD.len(), BOARD_CELL_SIZE.y as usize);
|
assert_eq!(RAW_BOARD.len(), BOARD_CELL_SIZE.y as usize);
|
||||||
|
|
||||||
for row in RAW_BOARD.iter() {
|
for row in RAW_BOARD.iter() {
|
||||||
assert_eq!(row.len(), BOARD_CELL_SIZE.x as usize);
|
assert_eq!(row.len(), BOARD_CELL_SIZE.x as usize);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Test boundaries
|
// Test boundaries are properly walled
|
||||||
assert!(RAW_BOARD[0].chars().all(|c| c == '#'));
|
assert!(RAW_BOARD[0].chars().all(|c| c == '#'));
|
||||||
assert!(RAW_BOARD[RAW_BOARD.len() - 1].chars().all(|c| c == '#'));
|
assert!(RAW_BOARD[RAW_BOARD.len() - 1].chars().all(|c| c == '#'));
|
||||||
|
|
||||||
// Test tunnel row
|
|
||||||
let tunnel_row = RAW_BOARD[14];
|
|
||||||
assert_eq!(tunnel_row.chars().next().unwrap(), 'T');
|
|
||||||
assert_eq!(tunnel_row.chars().last().unwrap(), 'T');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_raw_board_content() {
|
fn test_raw_board_contains_required_elements() {
|
||||||
let power_pellet_count = RAW_BOARD.iter().flat_map(|row| row.chars()).filter(|&c| c == 'o').count();
|
// Test that essential game elements are present
|
||||||
assert_eq!(power_pellet_count, 4);
|
assert!(
|
||||||
|
RAW_BOARD.iter().any(|row| row.contains('X')),
|
||||||
assert!(RAW_BOARD.iter().any(|row| row.contains('X')));
|
"Board should contain Pac-Man start position"
|
||||||
assert!(RAW_BOARD.iter().any(|row| row.contains("==")));
|
);
|
||||||
|
assert!(
|
||||||
|
RAW_BOARD.iter().any(|row| row.contains("==")),
|
||||||
|
"Board should contain ghost house door"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
RAW_BOARD.iter().any(|row| row.chars().any(|c| c == 'T')),
|
||||||
|
"Board should contain tunnel entrances"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
RAW_BOARD.iter().any(|row| row.chars().any(|c| c == 'o')),
|
||||||
|
"Board should contain power pellets"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
158
tests/error.rs
Normal file
158
tests/error.rs
Normal file
@@ -0,0 +1,158 @@
|
|||||||
|
use pacman::error::{
|
||||||
|
AnimatedTextureError, AssetError, EntityError, GameError, GameResult, IntoGameError, MapError, OptionExt, ParseError,
|
||||||
|
ResultExt, TextureError,
|
||||||
|
};
|
||||||
|
use std::io;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_game_error_from_asset_error() {
|
||||||
|
let asset_error = AssetError::NotFound("test.png".to_string());
|
||||||
|
let game_error: GameError = asset_error.into();
|
||||||
|
assert!(matches!(game_error, GameError::Asset(_)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_game_error_from_parse_error() {
|
||||||
|
let parse_error = ParseError::UnknownCharacter('Z');
|
||||||
|
let game_error: GameError = parse_error.into();
|
||||||
|
assert!(matches!(game_error, GameError::MapParse(_)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_game_error_from_map_error() {
|
||||||
|
let map_error = MapError::NodeNotFound(42);
|
||||||
|
let game_error: GameError = map_error.into();
|
||||||
|
assert!(matches!(game_error, GameError::Map(_)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_game_error_from_texture_error() {
|
||||||
|
let texture_error = TextureError::LoadFailed("Failed to load".to_string());
|
||||||
|
let game_error: GameError = texture_error.into();
|
||||||
|
assert!(matches!(game_error, GameError::Texture(_)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_game_error_from_entity_error() {
|
||||||
|
let entity_error = EntityError::NodeNotFound(10);
|
||||||
|
let game_error: GameError = entity_error.into();
|
||||||
|
assert!(matches!(game_error, GameError::Entity(_)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_game_error_from_io_error() {
|
||||||
|
let io_error = io::Error::new(io::ErrorKind::NotFound, "File not found");
|
||||||
|
let game_error: GameError = io_error.into();
|
||||||
|
assert!(matches!(game_error, GameError::Io(_)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_texture_error_from_animated_error() {
|
||||||
|
let animated_error = AnimatedTextureError::InvalidFrameDuration(-1.0);
|
||||||
|
let texture_error: TextureError = animated_error.into();
|
||||||
|
assert!(matches!(texture_error, TextureError::Animated(_)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_asset_error_from_io_error() {
|
||||||
|
let io_error = io::Error::new(io::ErrorKind::PermissionDenied, "Permission denied");
|
||||||
|
let asset_error: AssetError = io_error.into();
|
||||||
|
assert!(matches!(asset_error, AssetError::Io(_)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_parse_error_display() {
|
||||||
|
let error = ParseError::UnknownCharacter('!');
|
||||||
|
assert_eq!(error.to_string(), "Unknown character in board: !");
|
||||||
|
|
||||||
|
let error = ParseError::InvalidHouseDoorCount(3);
|
||||||
|
assert_eq!(error.to_string(), "House door must have exactly 2 positions, found 3");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_entity_error_display() {
|
||||||
|
let error = EntityError::NodeNotFound(42);
|
||||||
|
assert_eq!(error.to_string(), "Node not found in graph: 42");
|
||||||
|
|
||||||
|
let error = EntityError::EdgeNotFound { from: 1, to: 2 };
|
||||||
|
assert_eq!(error.to_string(), "Edge not found: from 1 to 2");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_animated_texture_error_display() {
|
||||||
|
let error = AnimatedTextureError::InvalidFrameDuration(0.0);
|
||||||
|
assert_eq!(error.to_string(), "Frame duration must be positive, got 0");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_into_game_error_trait() {
|
||||||
|
let result: Result<i32, io::Error> = Err(io::Error::new(io::ErrorKind::Other, "test error"));
|
||||||
|
let game_result: GameResult<i32> = result.into_game_error();
|
||||||
|
|
||||||
|
assert!(game_result.is_err());
|
||||||
|
if let Err(GameError::InvalidState(msg)) = game_result {
|
||||||
|
assert!(msg.contains("test error"));
|
||||||
|
} else {
|
||||||
|
panic!("Expected InvalidState error");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_into_game_error_trait_success() {
|
||||||
|
let result: Result<i32, io::Error> = Ok(42);
|
||||||
|
let game_result: GameResult<i32> = result.into_game_error();
|
||||||
|
|
||||||
|
assert_eq!(game_result.unwrap(), 42);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_option_ext_some() {
|
||||||
|
let option: Option<i32> = Some(42);
|
||||||
|
let result: GameResult<i32> = option.ok_or_game_error(|| GameError::InvalidState("Not found".to_string()));
|
||||||
|
|
||||||
|
assert_eq!(result.unwrap(), 42);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_option_ext_none() {
|
||||||
|
let option: Option<i32> = None;
|
||||||
|
let result: GameResult<i32> = option.ok_or_game_error(|| GameError::InvalidState("Not found".to_string()));
|
||||||
|
|
||||||
|
assert!(result.is_err());
|
||||||
|
if let Err(GameError::InvalidState(msg)) = result {
|
||||||
|
assert_eq!(msg, "Not found");
|
||||||
|
} else {
|
||||||
|
panic!("Expected InvalidState error");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_result_ext_success() {
|
||||||
|
let result: Result<i32, io::Error> = Ok(42);
|
||||||
|
let game_result: GameResult<i32> = result.with_context(|_| GameError::InvalidState("Context".to_string()));
|
||||||
|
|
||||||
|
assert_eq!(game_result.unwrap(), 42);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_result_ext_error() {
|
||||||
|
let result: Result<i32, io::Error> = Err(io::Error::new(io::ErrorKind::Other, "original error"));
|
||||||
|
let game_result: GameResult<i32> = result.with_context(|_| GameError::InvalidState("Context error".to_string()));
|
||||||
|
|
||||||
|
assert!(game_result.is_err());
|
||||||
|
if let Err(GameError::InvalidState(msg)) = game_result {
|
||||||
|
assert_eq!(msg, "Context error");
|
||||||
|
} else {
|
||||||
|
panic!("Expected InvalidState error");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_error_chain_conversions() {
|
||||||
|
// Test that we can convert through multiple levels
|
||||||
|
let animated_error = AnimatedTextureError::InvalidFrameDuration(-5.0);
|
||||||
|
let texture_error: TextureError = animated_error.into();
|
||||||
|
let game_error: GameError = texture_error.into();
|
||||||
|
|
||||||
|
assert!(matches!(game_error, GameError::Texture(TextureError::Animated(_))));
|
||||||
|
}
|
||||||
117
tests/events.rs
Normal file
117
tests/events.rs
Normal file
@@ -0,0 +1,117 @@
|
|||||||
|
use pacman::events::{GameCommand, GameEvent};
|
||||||
|
use pacman::map::direction::Direction;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_game_command_variants() {
|
||||||
|
// Test that all GameCommand variants can be created
|
||||||
|
let commands = vec![
|
||||||
|
GameCommand::Exit,
|
||||||
|
GameCommand::MovePlayer(Direction::Up),
|
||||||
|
GameCommand::MovePlayer(Direction::Down),
|
||||||
|
GameCommand::MovePlayer(Direction::Left),
|
||||||
|
GameCommand::MovePlayer(Direction::Right),
|
||||||
|
GameCommand::ToggleDebug,
|
||||||
|
GameCommand::MuteAudio,
|
||||||
|
GameCommand::ResetLevel,
|
||||||
|
GameCommand::TogglePause,
|
||||||
|
];
|
||||||
|
|
||||||
|
// Just verify they can be created and compared
|
||||||
|
assert_eq!(commands.len(), 9);
|
||||||
|
assert_eq!(commands[0], GameCommand::Exit);
|
||||||
|
assert_eq!(commands[1], GameCommand::MovePlayer(Direction::Up));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_game_command_equality() {
|
||||||
|
assert_eq!(GameCommand::Exit, GameCommand::Exit);
|
||||||
|
assert_eq!(GameCommand::ToggleDebug, GameCommand::ToggleDebug);
|
||||||
|
assert_eq!(
|
||||||
|
GameCommand::MovePlayer(Direction::Left),
|
||||||
|
GameCommand::MovePlayer(Direction::Left)
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_ne!(GameCommand::Exit, GameCommand::ToggleDebug);
|
||||||
|
assert_ne!(
|
||||||
|
GameCommand::MovePlayer(Direction::Left),
|
||||||
|
GameCommand::MovePlayer(Direction::Right)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_game_command_copy_clone() {
|
||||||
|
let original = GameCommand::MovePlayer(Direction::Up);
|
||||||
|
let copied = original;
|
||||||
|
let cloned = original.clone();
|
||||||
|
|
||||||
|
assert_eq!(original, copied);
|
||||||
|
assert_eq!(original, cloned);
|
||||||
|
assert_eq!(copied, cloned);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_game_event_variants() {
|
||||||
|
let command_event = GameEvent::Command(GameCommand::Exit);
|
||||||
|
let collision_event = GameEvent::Collision(bevy_ecs::entity::Entity::from_raw(1), bevy_ecs::entity::Entity::from_raw(2));
|
||||||
|
|
||||||
|
// Test that events can be created and compared
|
||||||
|
assert_eq!(command_event, GameEvent::Command(GameCommand::Exit));
|
||||||
|
assert_ne!(command_event, collision_event);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_game_command_to_game_event_conversion() {
|
||||||
|
let command = GameCommand::ToggleDebug;
|
||||||
|
let event: GameEvent = command.into();
|
||||||
|
|
||||||
|
assert_eq!(event, GameEvent::Command(GameCommand::ToggleDebug));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_game_command_to_game_event_conversion_all_variants() {
|
||||||
|
let commands = vec![
|
||||||
|
GameCommand::Exit,
|
||||||
|
GameCommand::MovePlayer(Direction::Up),
|
||||||
|
GameCommand::ToggleDebug,
|
||||||
|
GameCommand::MuteAudio,
|
||||||
|
GameCommand::ResetLevel,
|
||||||
|
GameCommand::TogglePause,
|
||||||
|
];
|
||||||
|
|
||||||
|
for command in commands {
|
||||||
|
let event: GameEvent = command.into();
|
||||||
|
assert_eq!(event, GameEvent::Command(command));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_move_player_all_directions() {
|
||||||
|
let directions = [Direction::Up, Direction::Down, Direction::Left, Direction::Right];
|
||||||
|
|
||||||
|
for direction in directions {
|
||||||
|
let command = GameCommand::MovePlayer(direction);
|
||||||
|
let event: GameEvent = command.into();
|
||||||
|
|
||||||
|
if let GameEvent::Command(GameCommand::MovePlayer(dir)) = event {
|
||||||
|
assert_eq!(dir, direction);
|
||||||
|
} else {
|
||||||
|
panic!("Expected MovePlayer command with direction {:?}", direction);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_game_event_debug_format() {
|
||||||
|
let event = GameEvent::Command(GameCommand::Exit);
|
||||||
|
let debug_str = format!("{:?}", event);
|
||||||
|
assert!(debug_str.contains("Command"));
|
||||||
|
assert!(debug_str.contains("Exit"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_game_command_debug_format() {
|
||||||
|
let command = GameCommand::MovePlayer(Direction::Left);
|
||||||
|
let debug_str = format!("{:?}", command);
|
||||||
|
assert!(debug_str.contains("MovePlayer"));
|
||||||
|
assert!(debug_str.contains("Left"));
|
||||||
|
}
|
||||||
@@ -19,7 +19,7 @@ fn get_formatted_output() -> impl IntoIterator<Item = String> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_formatting_alignment() {
|
fn test_complex_formatting_alignment() {
|
||||||
let mut colon_positions = vec![];
|
let mut colon_positions = vec![];
|
||||||
let mut first_decimal_positions = vec![];
|
let mut first_decimal_positions = vec![];
|
||||||
let mut second_decimal_positions = vec![];
|
let mut second_decimal_positions = vec![];
|
||||||
@@ -93,3 +93,80 @@ fn test_formatting_alignment() {
|
|||||||
second_unit_positions
|
second_unit_positions
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_format_timing_display_basic() {
|
||||||
|
let timing_data = vec![
|
||||||
|
("render".to_string(), Duration::from_micros(1500), Duration::from_micros(200)),
|
||||||
|
("input".to_string(), Duration::from_micros(300), Duration::from_micros(50)),
|
||||||
|
("physics".to_string(), Duration::from_nanos(750), Duration::from_nanos(100)),
|
||||||
|
];
|
||||||
|
|
||||||
|
let formatted = format_timing_display(timing_data);
|
||||||
|
|
||||||
|
// Should have 3 lines (one for each system)
|
||||||
|
assert_eq!(formatted.len(), 3);
|
||||||
|
|
||||||
|
// Each line should contain the system name
|
||||||
|
assert!(formatted.iter().any(|line| line.contains("render")));
|
||||||
|
assert!(formatted.iter().any(|line| line.contains("input")));
|
||||||
|
assert!(formatted.iter().any(|line| line.contains("physics")));
|
||||||
|
|
||||||
|
// Each line should contain timing information with proper units
|
||||||
|
for line in formatted.iter() {
|
||||||
|
assert!(line.contains(":"), "Line should contain colon separator: {}", line);
|
||||||
|
assert!(line.contains("±"), "Line should contain ± symbol: {}", line);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_format_timing_display_empty() {
|
||||||
|
let timing_data = vec![];
|
||||||
|
let formatted = format_timing_display(timing_data);
|
||||||
|
assert!(formatted.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_format_timing_display_units() {
|
||||||
|
let timing_data = vec![
|
||||||
|
("seconds".to_string(), Duration::from_secs(2), Duration::from_millis(100)),
|
||||||
|
("millis".to_string(), Duration::from_millis(15), Duration::from_micros(200)),
|
||||||
|
("micros".to_string(), Duration::from_micros(500), Duration::from_nanos(50)),
|
||||||
|
("nanos".to_string(), Duration::from_nanos(250), Duration::from_nanos(25)),
|
||||||
|
];
|
||||||
|
|
||||||
|
let formatted = format_timing_display(timing_data);
|
||||||
|
|
||||||
|
// Check that appropriate units are used
|
||||||
|
let all_lines = formatted.join(" ");
|
||||||
|
assert!(all_lines.contains("s"), "Should contain seconds unit");
|
||||||
|
assert!(all_lines.contains("ms"), "Should contain milliseconds unit");
|
||||||
|
assert!(all_lines.contains("µs"), "Should contain microseconds unit");
|
||||||
|
assert!(all_lines.contains("ns"), "Should contain nanoseconds unit");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_format_timing_display_alignment() {
|
||||||
|
let timing_data = vec![
|
||||||
|
("short".to_string(), Duration::from_micros(100), Duration::from_micros(10)),
|
||||||
|
(
|
||||||
|
"very_long_name".to_string(),
|
||||||
|
Duration::from_micros(200),
|
||||||
|
Duration::from_micros(20),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
|
||||||
|
let formatted = format_timing_display(timing_data);
|
||||||
|
|
||||||
|
// Find colon positions - they should be aligned
|
||||||
|
let colon_positions: Vec<usize> = formatted.iter().map(|line| line.find(':').unwrap_or(0)).collect();
|
||||||
|
|
||||||
|
// All colons should be at the same position (aligned)
|
||||||
|
if colon_positions.len() > 1 {
|
||||||
|
let first_pos = colon_positions[0];
|
||||||
|
assert!(
|
||||||
|
colon_positions.iter().all(|&pos| pos == first_pos),
|
||||||
|
"Colons should be aligned at the same position"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
100
tests/player.rs
Normal file
100
tests/player.rs
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
use pacman::map::direction::Direction;
|
||||||
|
use pacman::map::graph::{Edge, TraversalFlags};
|
||||||
|
use pacman::systems::components::EntityType;
|
||||||
|
use pacman::systems::player::can_traverse;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_can_traverse_player_on_all_edges() {
|
||||||
|
let edge = Edge {
|
||||||
|
target: 1,
|
||||||
|
distance: 10.0,
|
||||||
|
direction: Direction::Up,
|
||||||
|
traversal_flags: TraversalFlags::ALL,
|
||||||
|
};
|
||||||
|
|
||||||
|
assert!(can_traverse(EntityType::Player, edge));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_can_traverse_player_on_pacman_only_edges() {
|
||||||
|
let edge = Edge {
|
||||||
|
target: 1,
|
||||||
|
distance: 10.0,
|
||||||
|
direction: Direction::Right,
|
||||||
|
traversal_flags: TraversalFlags::PACMAN,
|
||||||
|
};
|
||||||
|
|
||||||
|
assert!(can_traverse(EntityType::Player, edge));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_can_traverse_player_blocked_on_ghost_only_edges() {
|
||||||
|
let edge = Edge {
|
||||||
|
target: 1,
|
||||||
|
distance: 10.0,
|
||||||
|
direction: Direction::Left,
|
||||||
|
traversal_flags: TraversalFlags::GHOST,
|
||||||
|
};
|
||||||
|
|
||||||
|
assert!(!can_traverse(EntityType::Player, edge));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_can_traverse_ghost_on_all_edges() {
|
||||||
|
let edge = Edge {
|
||||||
|
target: 2,
|
||||||
|
distance: 15.0,
|
||||||
|
direction: Direction::Down,
|
||||||
|
traversal_flags: TraversalFlags::ALL,
|
||||||
|
};
|
||||||
|
|
||||||
|
assert!(can_traverse(EntityType::Ghost, edge));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_can_traverse_ghost_on_ghost_only_edges() {
|
||||||
|
let edge = Edge {
|
||||||
|
target: 2,
|
||||||
|
distance: 15.0,
|
||||||
|
direction: Direction::Up,
|
||||||
|
traversal_flags: TraversalFlags::GHOST,
|
||||||
|
};
|
||||||
|
|
||||||
|
assert!(can_traverse(EntityType::Ghost, edge));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_can_traverse_ghost_blocked_on_pacman_only_edges() {
|
||||||
|
let edge = Edge {
|
||||||
|
target: 2,
|
||||||
|
distance: 15.0,
|
||||||
|
direction: Direction::Right,
|
||||||
|
traversal_flags: TraversalFlags::PACMAN,
|
||||||
|
};
|
||||||
|
|
||||||
|
assert!(!can_traverse(EntityType::Ghost, edge));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_can_traverse_static_entities_flags() {
|
||||||
|
let edge = Edge {
|
||||||
|
target: 3,
|
||||||
|
distance: 8.0,
|
||||||
|
direction: Direction::Left,
|
||||||
|
traversal_flags: TraversalFlags::ALL,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Static entities have empty traversal flags but can still "traverse"
|
||||||
|
// in the sense that empty flags are contained in any flag set
|
||||||
|
// This is the expected behavior since empty ⊆ any set
|
||||||
|
assert!(can_traverse(EntityType::Pellet, edge));
|
||||||
|
assert!(can_traverse(EntityType::PowerPellet, edge));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_entity_type_traversal_flags() {
|
||||||
|
assert_eq!(EntityType::Player.traversal_flags(), TraversalFlags::PACMAN);
|
||||||
|
assert_eq!(EntityType::Ghost.traversal_flags(), TraversalFlags::GHOST);
|
||||||
|
assert_eq!(EntityType::Pellet.traversal_flags(), TraversalFlags::empty());
|
||||||
|
assert_eq!(EntityType::PowerPellet.traversal_flags(), TraversalFlags::empty());
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user