mirror of
https://github.com/Xevion/Pac-Man.git
synced 2025-12-06 15:15:48 -06:00
Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9c9dc5f423 | |||
| 12ee16faab | |||
| 398d041d96 | |||
| 7a02d6b0b5 | |||
| d47d70ff5b |
@@ -20,3 +20,15 @@ repos:
|
||||
language: system
|
||||
types: [rust]
|
||||
pass_filenames: false
|
||||
- id: cargo-check
|
||||
name: cargo check
|
||||
entry: cargo check --all-targets
|
||||
language: system
|
||||
types_or: [rust, cargo, cargo-lock]
|
||||
pass_filenames: false
|
||||
- id: cargo-check-wasm
|
||||
name: cargo check for wasm32-unknown-emscripten
|
||||
entry: cargo check --all-targets --target=wasm32-unknown-emscripten
|
||||
language: system
|
||||
types_or: [rust, cargo, cargo-lock]
|
||||
pass_filenames: false
|
||||
|
||||
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::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 game: Game,
|
||||
last_tick: Instant,
|
||||
@@ -20,6 +25,16 @@ pub struct 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> {
|
||||
let sdl_context: &'static Sdl = Box::leak(Box::new(sdl2::init().map_err(|e| GameError::Sdl(e.to_string()))?));
|
||||
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 {
|
||||
{
|
||||
let start = Instant::now();
|
||||
|
||||
23
src/asset.rs
23
src/asset.rs
@@ -5,17 +5,28 @@
|
||||
use std::borrow::Cow;
|
||||
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)]
|
||||
pub enum Asset {
|
||||
Wav1,
|
||||
Wav2,
|
||||
Wav3,
|
||||
Wav4,
|
||||
/// Main sprite atlas containing all game graphics (atlas.png)
|
||||
AtlasImage,
|
||||
/// Terminal Vector font for text rendering (TerminalVector.ttf)
|
||||
Font,
|
||||
}
|
||||
|
||||
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)]
|
||||
pub fn path(&self) -> &str {
|
||||
use Asset::*;
|
||||
@@ -35,7 +46,17 @@ mod imp {
|
||||
use crate::error::AssetError;
|
||||
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> {
|
||||
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)]
|
||||
pub fn eat(&mut self) {
|
||||
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();
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
if !self.disabled {
|
||||
let channels = 4;
|
||||
@@ -151,12 +155,19 @@ impl Audio {
|
||||
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 {
|
||||
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)]
|
||||
pub fn is_disabled(&self) -> bool {
|
||||
self.disabled
|
||||
|
||||
@@ -4,6 +4,11 @@ use std::time::Duration;
|
||||
|
||||
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);
|
||||
|
||||
/// 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)
|
||||
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);
|
||||
/// 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);
|
||||
/// The size of the canvas, in pixels.
|
||||
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,
|
||||
);
|
||||
|
||||
/// 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)]
|
||||
pub enum MapTile {
|
||||
/// An empty tile.
|
||||
/// Traversable space with no collectible items
|
||||
Empty,
|
||||
/// A wall tile.
|
||||
Wall,
|
||||
/// A regular pellet.
|
||||
/// Small collectible. Implicitly a traversable tile.
|
||||
Pellet,
|
||||
/// A power pellet.
|
||||
/// Large collectible. Implicitly a traversable tile.
|
||||
PowerPellet,
|
||||
/// A tunnel tile.
|
||||
/// Special traversable tile that connects to tunnel portals.
|
||||
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] = [
|
||||
"############################",
|
||||
"#............##............#",
|
||||
|
||||
@@ -1,128 +0,0 @@
|
||||
// use smallvec::SmallVec;
|
||||
// use std::collections::HashMap;
|
||||
|
||||
// use crate::entity::{graph::NodeId, traversal::Position};
|
||||
|
||||
// /// Trait for entities that can participate in collision detection.
|
||||
// pub trait Collidable {
|
||||
// /// Returns the current position of this entity.
|
||||
// fn position(&self) -> Position;
|
||||
|
||||
// /// Checks if this entity is colliding with another entity.
|
||||
// #[allow(dead_code)]
|
||||
// fn is_colliding_with(&self, other: &dyn Collidable) -> bool {
|
||||
// positions_overlap(&self.position(), &other.position())
|
||||
// }
|
||||
// }
|
||||
|
||||
// /// System for tracking entities by their positions for efficient collision detection.
|
||||
// #[derive(Default)]
|
||||
// pub struct CollisionSystem {
|
||||
// /// Maps node IDs to lists of entity IDs that are at that node
|
||||
// node_entities: HashMap<NodeId, Vec<EntityId>>,
|
||||
// /// Maps entity IDs to their current positions
|
||||
// entity_positions: HashMap<EntityId, Position>,
|
||||
// /// Next available entity ID
|
||||
// next_id: EntityId,
|
||||
// }
|
||||
|
||||
// /// Unique identifier for an entity in the collision system
|
||||
// pub type EntityId = u32;
|
||||
|
||||
// impl CollisionSystem {
|
||||
// /// Registers an entity with the collision system and returns its ID
|
||||
// pub fn register_entity(&mut self, position: Position) -> EntityId {
|
||||
// let id = self.next_id;
|
||||
// self.next_id += 1;
|
||||
|
||||
// self.entity_positions.insert(id, position);
|
||||
// self.update_node_entities(id, position);
|
||||
|
||||
// id
|
||||
// }
|
||||
|
||||
// /// Updates an entity's position
|
||||
// pub fn update_position(&mut self, entity_id: EntityId, new_position: Position) {
|
||||
// if let Some(old_position) = self.entity_positions.get(&entity_id) {
|
||||
// // Remove from old nodes
|
||||
// self.remove_from_nodes(entity_id, *old_position);
|
||||
// }
|
||||
|
||||
// // Update position and add to new nodes
|
||||
// self.entity_positions.insert(entity_id, new_position);
|
||||
// self.update_node_entities(entity_id, new_position);
|
||||
// }
|
||||
|
||||
// /// Removes an entity from the collision system
|
||||
// #[allow(dead_code)]
|
||||
// pub fn remove_entity(&mut self, entity_id: EntityId) {
|
||||
// if let Some(position) = self.entity_positions.remove(&entity_id) {
|
||||
// self.remove_from_nodes(entity_id, position);
|
||||
// }
|
||||
// }
|
||||
|
||||
// /// Gets all entity IDs at a specific node
|
||||
// pub fn entities_at_node(&self, node: NodeId) -> &[EntityId] {
|
||||
// self.node_entities.get(&node).map(|v| v.as_slice()).unwrap_or(&[])
|
||||
// }
|
||||
|
||||
// /// Gets all entity IDs that could collide with an entity at the given position
|
||||
// pub fn potential_collisions(&self, position: &Position) -> Vec<EntityId> {
|
||||
// let mut collisions = Vec::new();
|
||||
// let nodes = get_nodes(position);
|
||||
|
||||
// for node in nodes {
|
||||
// collisions.extend(self.entities_at_node(node));
|
||||
// }
|
||||
|
||||
// // Remove duplicates
|
||||
// collisions.sort_unstable();
|
||||
// collisions.dedup();
|
||||
// collisions
|
||||
// }
|
||||
|
||||
// /// Updates the node_entities map when an entity's position changes
|
||||
// fn update_node_entities(&mut self, entity_id: EntityId, position: Position) {
|
||||
// let nodes = get_nodes(&position);
|
||||
// for node in nodes {
|
||||
// self.node_entities.entry(node).or_default().push(entity_id);
|
||||
// }
|
||||
// }
|
||||
|
||||
// /// Removes an entity from all nodes it was previously at
|
||||
// fn remove_from_nodes(&mut self, entity_id: EntityId, position: Position) {
|
||||
// let nodes = get_nodes(&position);
|
||||
// for node in nodes {
|
||||
// if let Some(entities) = self.node_entities.get_mut(&node) {
|
||||
// entities.retain(|&id| id != entity_id);
|
||||
// if entities.is_empty() {
|
||||
// self.node_entities.remove(&node);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// /// Checks if two positions overlap (entities are at the same location).
|
||||
// fn positions_overlap(a: &Position, b: &Position) -> bool {
|
||||
// let a_nodes = get_nodes(a);
|
||||
// let b_nodes = get_nodes(b);
|
||||
|
||||
// // Check if any nodes overlap
|
||||
// a_nodes.iter().any(|a_node| b_nodes.contains(a_node))
|
||||
|
||||
// // TODO: More complex overlap detection, the above is a simple check, but it could become an early filter for more precise calculations later
|
||||
// }
|
||||
|
||||
// /// Gets all nodes that an entity is currently at or between.
|
||||
// fn get_nodes(pos: &Position) -> SmallVec<[NodeId; 2]> {
|
||||
// let mut nodes = SmallVec::new();
|
||||
// match pos {
|
||||
// Position::AtNode(node) => nodes.push(*node),
|
||||
// Position::BetweenNodes { from, to, .. } => {
|
||||
// nodes.push(*from);
|
||||
// nodes.push(*to);
|
||||
// }
|
||||
// }
|
||||
// nodes
|
||||
// }
|
||||
@@ -1,254 +0,0 @@
|
||||
// //! Ghost entity implementation.
|
||||
// //!
|
||||
// //! This module contains the ghost character logic, including movement,
|
||||
// //! animation, and rendering. Ghosts move through the game graph using
|
||||
// //! a traverser and display directional animated textures.
|
||||
|
||||
// use pathfinding::prelude::dijkstra;
|
||||
// use rand::prelude::*;
|
||||
// use smallvec::SmallVec;
|
||||
// use tracing::error;
|
||||
|
||||
// use crate::entity::{
|
||||
// collision::Collidable,
|
||||
// direction::Direction,
|
||||
// graph::{Edge, EdgePermissions, Graph, NodeId},
|
||||
// r#trait::Entity,
|
||||
// traversal::Traverser,
|
||||
// };
|
||||
// use crate::texture::animated::AnimatedTexture;
|
||||
// use crate::texture::directional::DirectionalAnimatedTexture;
|
||||
// use crate::texture::sprite::SpriteAtlas;
|
||||
|
||||
// use crate::error::{EntityError, GameError, GameResult, TextureError};
|
||||
|
||||
// /// Determines if a ghost can traverse a given edge.
|
||||
// ///
|
||||
// /// Ghosts can move through edges that allow all entities or ghost-only edges.
|
||||
// fn can_ghost_traverse(edge: Edge) -> bool {
|
||||
// matches!(edge.permissions, EdgePermissions::All | EdgePermissions::GhostsOnly)
|
||||
// }
|
||||
|
||||
// /// The four classic ghost types.
|
||||
// #[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
// pub enum GhostType {
|
||||
// Blinky,
|
||||
// Pinky,
|
||||
// Inky,
|
||||
// Clyde,
|
||||
// }
|
||||
|
||||
// impl GhostType {
|
||||
// /// Returns the ghost type name for atlas lookups.
|
||||
// pub fn as_str(self) -> &'static str {
|
||||
// match self {
|
||||
// GhostType::Blinky => "blinky",
|
||||
// GhostType::Pinky => "pinky",
|
||||
// GhostType::Inky => "inky",
|
||||
// GhostType::Clyde => "clyde",
|
||||
// }
|
||||
// }
|
||||
|
||||
// /// Returns the base movement speed for this ghost type.
|
||||
// pub fn base_speed(self) -> f32 {
|
||||
// match self {
|
||||
// GhostType::Blinky => 1.0,
|
||||
// GhostType::Pinky => 0.95,
|
||||
// GhostType::Inky => 0.9,
|
||||
// GhostType::Clyde => 0.85,
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// /// A ghost entity that roams the game world.
|
||||
// ///
|
||||
// /// Ghosts move through the game world using a graph-based navigation system
|
||||
// /// and display directional animated sprites. They randomly choose directions
|
||||
// /// at each intersection.
|
||||
// pub struct Ghost {
|
||||
// /// Handles movement through the game graph
|
||||
// pub traverser: Traverser,
|
||||
// /// The type of ghost (affects appearance and speed)
|
||||
// pub ghost_type: GhostType,
|
||||
// /// Manages directional animated textures for different movement states
|
||||
// texture: DirectionalAnimatedTexture,
|
||||
// /// Current movement speed
|
||||
// speed: f32,
|
||||
// }
|
||||
|
||||
// impl Entity for Ghost {
|
||||
// fn traverser(&self) -> &Traverser {
|
||||
// &self.traverser
|
||||
// }
|
||||
|
||||
// fn traverser_mut(&mut self) -> &mut Traverser {
|
||||
// &mut self.traverser
|
||||
// }
|
||||
|
||||
// fn texture(&self) -> &DirectionalAnimatedTexture {
|
||||
// &self.texture
|
||||
// }
|
||||
|
||||
// fn texture_mut(&mut self) -> &mut DirectionalAnimatedTexture {
|
||||
// &mut self.texture
|
||||
// }
|
||||
|
||||
// fn speed(&self) -> f32 {
|
||||
// self.speed
|
||||
// }
|
||||
|
||||
// fn can_traverse(&self, edge: Edge) -> bool {
|
||||
// can_ghost_traverse(edge)
|
||||
// }
|
||||
|
||||
// fn tick(&mut self, dt: f32, graph: &Graph) {
|
||||
// // Choose random direction when at a node
|
||||
// if self.traverser.position.is_at_node() {
|
||||
// self.choose_random_direction(graph);
|
||||
// }
|
||||
|
||||
// if let Err(e) = self.traverser.advance(graph, dt * 60.0 * self.speed, &can_ghost_traverse) {
|
||||
// error!("Ghost movement error: {}", e);
|
||||
// }
|
||||
// self.texture.tick(dt);
|
||||
// }
|
||||
// }
|
||||
|
||||
// impl Ghost {
|
||||
// /// Creates a new ghost instance at the specified starting node.
|
||||
// ///
|
||||
// /// Sets up animated textures for all four directions with moving and stopped states.
|
||||
// /// The moving animation cycles through two sprite variants.
|
||||
// pub fn new(graph: &Graph, start_node: NodeId, ghost_type: GhostType, atlas: &SpriteAtlas) -> GameResult<Self> {
|
||||
// let mut textures = [None, None, None, None];
|
||||
// let mut stopped_textures = [None, None, None, None];
|
||||
|
||||
// for direction in Direction::DIRECTIONS {
|
||||
// let moving_prefix = match direction {
|
||||
// Direction::Up => "up",
|
||||
// Direction::Down => "down",
|
||||
// Direction::Left => "left",
|
||||
// Direction::Right => "right",
|
||||
// };
|
||||
// let moving_tiles = vec![
|
||||
// SpriteAtlas::get_tile(atlas, &format!("ghost/{}/{}_{}.png", ghost_type.as_str(), moving_prefix, "a"))
|
||||
// .ok_or_else(|| {
|
||||
// GameError::Texture(TextureError::AtlasTileNotFound(format!(
|
||||
// "ghost/{}/{}_{}.png",
|
||||
// ghost_type.as_str(),
|
||||
// moving_prefix,
|
||||
// "a"
|
||||
// )))
|
||||
// })?,
|
||||
// SpriteAtlas::get_tile(atlas, &format!("ghost/{}/{}_{}.png", ghost_type.as_str(), moving_prefix, "b"))
|
||||
// .ok_or_else(|| {
|
||||
// GameError::Texture(TextureError::AtlasTileNotFound(format!(
|
||||
// "ghost/{}/{}_{}.png",
|
||||
// ghost_type.as_str(),
|
||||
// moving_prefix,
|
||||
// "b"
|
||||
// )))
|
||||
// })?,
|
||||
// ];
|
||||
|
||||
// let stopped_tiles =
|
||||
// vec![
|
||||
// SpriteAtlas::get_tile(atlas, &format!("ghost/{}/{}_{}.png", ghost_type.as_str(), moving_prefix, "a"))
|
||||
// .ok_or_else(|| {
|
||||
// GameError::Texture(TextureError::AtlasTileNotFound(format!(
|
||||
// "ghost/{}/{}_{}.png",
|
||||
// ghost_type.as_str(),
|
||||
// moving_prefix,
|
||||
// "a"
|
||||
// )))
|
||||
// })?,
|
||||
// ];
|
||||
|
||||
// textures[direction.as_usize()] = Some(AnimatedTexture::new(moving_tiles, 0.2)?);
|
||||
// stopped_textures[direction.as_usize()] = Some(AnimatedTexture::new(stopped_tiles, 0.1)?);
|
||||
// }
|
||||
|
||||
// Ok(Self {
|
||||
// traverser: Traverser::new(graph, start_node, Direction::Left, &can_ghost_traverse),
|
||||
// ghost_type,
|
||||
// texture: DirectionalAnimatedTexture::new(textures, stopped_textures),
|
||||
// speed: ghost_type.base_speed(),
|
||||
// })
|
||||
// }
|
||||
|
||||
// /// Chooses a random available direction at the current intersection.
|
||||
// fn choose_random_direction(&mut self, graph: &Graph) {
|
||||
// let current_node = self.traverser.position.from_node_id();
|
||||
// let intersection = &graph.adjacency_list[current_node];
|
||||
|
||||
// // Collect all available directions
|
||||
// let mut available_directions = SmallVec::<[_; 4]>::new();
|
||||
// for direction in Direction::DIRECTIONS {
|
||||
// if let Some(edge) = intersection.get(direction) {
|
||||
// if can_ghost_traverse(edge) {
|
||||
// available_directions.push(direction);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// // Choose a random direction (avoid reversing unless necessary)
|
||||
// if !available_directions.is_empty() {
|
||||
// let mut rng = SmallRng::from_os_rng();
|
||||
|
||||
// // Filter out the opposite direction if possible, but allow it if we have limited options
|
||||
// let opposite = self.traverser.direction.opposite();
|
||||
// let filtered_directions: Vec<_> = available_directions
|
||||
// .iter()
|
||||
// .filter(|&&dir| dir != opposite || available_directions.len() <= 2)
|
||||
// .collect();
|
||||
|
||||
// if let Some(&random_direction) = filtered_directions.choose(&mut rng) {
|
||||
// self.traverser.set_next_direction(*random_direction);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// /// Calculates the shortest path from the ghost's current position to a target node using Dijkstra's algorithm.
|
||||
// ///
|
||||
// /// Returns a vector of NodeIds representing the path, or an error if pathfinding fails.
|
||||
// /// The path includes the current node and the target node.
|
||||
// pub fn calculate_path_to_target(&self, graph: &Graph, target: NodeId) -> GameResult<Vec<NodeId>> {
|
||||
// let start_node = self.traverser.position.from_node_id();
|
||||
|
||||
// // Use Dijkstra's algorithm to find the shortest path
|
||||
// let result = dijkstra(
|
||||
// &start_node,
|
||||
// |&node_id| {
|
||||
// // Get all edges from the current node
|
||||
// graph.adjacency_list[node_id]
|
||||
// .edges()
|
||||
// .filter(|edge| can_ghost_traverse(*edge))
|
||||
// .map(|edge| (edge.target, (edge.distance * 100.0) as u32))
|
||||
// .collect::<Vec<_>>()
|
||||
// },
|
||||
// |&node_id| node_id == target,
|
||||
// );
|
||||
|
||||
// result.map(|(path, _cost)| path).ok_or_else(|| {
|
||||
// GameError::Entity(EntityError::PathfindingFailed(format!(
|
||||
// "No path found from node {} to target {}",
|
||||
// start_node, target
|
||||
// )))
|
||||
// })
|
||||
// }
|
||||
|
||||
// /// Returns the ghost's color for debug rendering.
|
||||
// pub fn debug_color(&self) -> sdl2::pixels::Color {
|
||||
// match self.ghost_type {
|
||||
// GhostType::Blinky => sdl2::pixels::Color::RGB(255, 0, 0), // Red
|
||||
// GhostType::Pinky => sdl2::pixels::Color::RGB(255, 182, 255), // Pink
|
||||
// GhostType::Inky => sdl2::pixels::Color::RGB(0, 255, 255), // Cyan
|
||||
// GhostType::Clyde => sdl2::pixels::Color::RGB(255, 182, 85), // Orange
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// impl Collidable for Ghost {
|
||||
// fn position(&self) -> crate::entity::traversal::Position {
|
||||
// self.traverser.position
|
||||
// }
|
||||
// }
|
||||
@@ -1,117 +0,0 @@
|
||||
// use crate::{
|
||||
// constants,
|
||||
// entity::{collision::Collidable, graph::Graph},
|
||||
// error::{EntityError, GameResult},
|
||||
// texture::sprite::{Sprite, SpriteAtlas},
|
||||
// };
|
||||
// use sdl2::render::{Canvas, RenderTarget};
|
||||
// use strum_macros::{EnumCount, EnumIter};
|
||||
|
||||
// #[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
// pub enum ItemType {
|
||||
// Pellet,
|
||||
// Energizer,
|
||||
// #[allow(dead_code)]
|
||||
// Fruit {
|
||||
// kind: FruitKind,
|
||||
// },
|
||||
// }
|
||||
|
||||
// impl ItemType {
|
||||
// pub fn get_score(self) -> u32 {
|
||||
// match self {
|
||||
// ItemType::Pellet => 10,
|
||||
// ItemType::Energizer => 50,
|
||||
// ItemType::Fruit { kind } => kind.get_score(),
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// #[derive(Debug, Clone, Copy, PartialEq, Eq, EnumIter, EnumCount)]
|
||||
// #[allow(dead_code)]
|
||||
// pub enum FruitKind {
|
||||
// Apple,
|
||||
// Strawberry,
|
||||
// Orange,
|
||||
// Melon,
|
||||
// Bell,
|
||||
// Key,
|
||||
// Galaxian,
|
||||
// }
|
||||
|
||||
// impl FruitKind {
|
||||
// #[allow(dead_code)]
|
||||
// pub fn index(self) -> u8 {
|
||||
// match self {
|
||||
// FruitKind::Apple => 0,
|
||||
// FruitKind::Strawberry => 1,
|
||||
// FruitKind::Orange => 2,
|
||||
// FruitKind::Melon => 3,
|
||||
// FruitKind::Bell => 4,
|
||||
// FruitKind::Key => 5,
|
||||
// FruitKind::Galaxian => 6,
|
||||
// }
|
||||
// }
|
||||
|
||||
// pub fn get_score(self) -> u32 {
|
||||
// match self {
|
||||
// FruitKind::Apple => 100,
|
||||
// FruitKind::Strawberry => 300,
|
||||
// FruitKind::Orange => 500,
|
||||
// FruitKind::Melon => 700,
|
||||
// FruitKind::Bell => 1000,
|
||||
// FruitKind::Key => 2000,
|
||||
// FruitKind::Galaxian => 3000,
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// pub struct Item {
|
||||
// pub node_index: usize,
|
||||
// pub item_type: ItemType,
|
||||
// pub sprite: Sprite,
|
||||
// pub collected: bool,
|
||||
// }
|
||||
|
||||
// impl Item {
|
||||
// pub fn new(node_index: usize, item_type: ItemType, sprite: Sprite) -> Self {
|
||||
// Self {
|
||||
// node_index,
|
||||
// item_type,
|
||||
// sprite,
|
||||
// collected: false,
|
||||
// }
|
||||
// }
|
||||
|
||||
// pub fn is_collected(&self) -> bool {
|
||||
// self.collected
|
||||
// }
|
||||
|
||||
// pub fn collect(&mut self) {
|
||||
// self.collected = true;
|
||||
// }
|
||||
|
||||
// pub fn get_score(&self) -> u32 {
|
||||
// self.item_type.get_score()
|
||||
// }
|
||||
|
||||
// pub fn render<T: RenderTarget>(&self, canvas: &mut Canvas<T>, atlas: &mut SpriteAtlas, graph: &Graph) -> GameResult<()> {
|
||||
// if self.collected {
|
||||
// return Ok(());
|
||||
// }
|
||||
|
||||
// let node = graph
|
||||
// .get_node(self.node_index)
|
||||
// .ok_or(EntityError::NodeNotFound(self.node_index))?;
|
||||
// let position = node.position + constants::BOARD_PIXEL_OFFSET.as_vec2();
|
||||
|
||||
// self.sprite.render(canvas, atlas, position)?;
|
||||
// Ok(())
|
||||
// }
|
||||
// }
|
||||
|
||||
// impl Collidable for Item {
|
||||
// fn position(&self) -> crate::entity::traversal::Position {
|
||||
// crate::entity::traversal::Position::AtNode(self.node_index)
|
||||
// }
|
||||
// }
|
||||
@@ -1,7 +0,0 @@
|
||||
pub mod collision;
|
||||
pub mod direction;
|
||||
pub mod ghost;
|
||||
pub mod graph;
|
||||
pub mod item;
|
||||
pub mod pacman;
|
||||
pub mod r#trait;
|
||||
@@ -1,115 +0,0 @@
|
||||
// //! Pac-Man entity implementation.
|
||||
// //!
|
||||
// //! This module contains the main player character logic, including movement,
|
||||
// //! animation, and rendering. Pac-Man moves through the game graph using
|
||||
// //! a traverser and displays directional animated textures.
|
||||
|
||||
// use crate::entity::{
|
||||
// collision::Collidable,
|
||||
// direction::Direction,
|
||||
// graph::{Edge, EdgePermissions, Graph, NodeId},
|
||||
// r#trait::Entity,
|
||||
// traversal::Traverser,
|
||||
// };
|
||||
// use crate::texture::animated::AnimatedTexture;
|
||||
// use crate::texture::directional::DirectionalAnimatedTexture;
|
||||
// use crate::texture::sprite::SpriteAtlas;
|
||||
// use tracing::error;
|
||||
|
||||
// use crate::error::{GameError, GameResult, TextureError};
|
||||
|
||||
// /// Determines if Pac-Man can traverse a given edge.
|
||||
// ///
|
||||
// /// Pac-Man can only move through edges that allow all entities.
|
||||
// fn can_pacman_traverse(edge: Edge) -> bool {
|
||||
// matches!(edge.permissions, EdgePermissions::All)
|
||||
// }
|
||||
|
||||
// /// The main player character entity.
|
||||
// ///
|
||||
// /// Pac-Man moves through the game world using a graph-based navigation system
|
||||
// /// and displays directional animated sprites based on movement state.
|
||||
// pub struct Pacman {
|
||||
// /// Handles movement through the game graph
|
||||
// pub traverser: Traverser,
|
||||
// /// Manages directional animated textures for different movement states
|
||||
// texture: DirectionalAnimatedTexture,
|
||||
// }
|
||||
|
||||
// impl Entity for Pacman {
|
||||
// fn traverser(&self) -> &Traverser {
|
||||
// &self.traverser
|
||||
// }
|
||||
|
||||
// fn traverser_mut(&mut self) -> &mut Traverser {
|
||||
// &mut self.traverser
|
||||
// }
|
||||
|
||||
// fn texture(&self) -> &DirectionalAnimatedTexture {
|
||||
// &self.texture
|
||||
// }
|
||||
|
||||
// fn texture_mut(&mut self) -> &mut DirectionalAnimatedTexture {
|
||||
// &mut self.texture
|
||||
// }
|
||||
|
||||
// fn speed(&self) -> f32 {
|
||||
// 1.125
|
||||
// }
|
||||
|
||||
// fn can_traverse(&self, edge: Edge) -> bool {
|
||||
// can_pacman_traverse(edge)
|
||||
// }
|
||||
|
||||
// fn tick(&mut self, dt: f32, graph: &Graph) {
|
||||
// if let Err(e) = self.traverser.advance(graph, dt * 60.0 * 1.125, &can_pacman_traverse) {
|
||||
// error!("Pac-Man movement error: {}", e);
|
||||
// }
|
||||
// self.texture.tick(dt);
|
||||
// }
|
||||
// }
|
||||
|
||||
// impl Pacman {
|
||||
// /// Creates a new Pac-Man instance at the specified starting node.
|
||||
// ///
|
||||
// /// Sets up animated textures for all four directions with moving and stopped states.
|
||||
// /// The moving animation cycles through open mouth, closed mouth, and full sprites.
|
||||
// pub fn new(graph: &Graph, start_node: NodeId, atlas: &SpriteAtlas) -> GameResult<Self> {
|
||||
// let mut textures = [None, None, None, None];
|
||||
// let mut stopped_textures = [None, None, None, None];
|
||||
|
||||
// for direction in Direction::DIRECTIONS {
|
||||
// let moving_prefix = match direction {
|
||||
// Direction::Up => "pacman/up",
|
||||
// Direction::Down => "pacman/down",
|
||||
// Direction::Left => "pacman/left",
|
||||
// Direction::Right => "pacman/right",
|
||||
// };
|
||||
// let moving_tiles = vec![
|
||||
// SpriteAtlas::get_tile(atlas, &format!("{moving_prefix}_a.png"))
|
||||
// .ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound(format!("{moving_prefix}_a.png"))))?,
|
||||
// SpriteAtlas::get_tile(atlas, &format!("{moving_prefix}_b.png"))
|
||||
// .ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound(format!("{moving_prefix}_b.png"))))?,
|
||||
// SpriteAtlas::get_tile(atlas, "pacman/full.png")
|
||||
// .ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound("pacman/full.png".to_string())))?,
|
||||
// ];
|
||||
|
||||
// let stopped_tiles = vec![SpriteAtlas::get_tile(atlas, &format!("{moving_prefix}_b.png"))
|
||||
// .ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound(format!("{moving_prefix}_b.png"))))?];
|
||||
|
||||
// textures[direction.as_usize()] = Some(AnimatedTexture::new(moving_tiles, 0.08)?);
|
||||
// stopped_textures[direction.as_usize()] = Some(AnimatedTexture::new(stopped_tiles, 0.1)?);
|
||||
// }
|
||||
|
||||
// Ok(Self {
|
||||
// traverser: Traverser::new(graph, start_node, Direction::Left, &can_pacman_traverse),
|
||||
// texture: DirectionalAnimatedTexture::new(textures, stopped_textures),
|
||||
// })
|
||||
// }
|
||||
// }
|
||||
|
||||
// impl Collidable for Pacman {
|
||||
// fn position(&self) -> crate::entity::traversal::Position {
|
||||
// self.traverser.position
|
||||
// }
|
||||
// }
|
||||
@@ -1,114 +0,0 @@
|
||||
// //! Entity trait for common movement and rendering functionality.
|
||||
// //!
|
||||
// //! This module defines a trait that captures the shared behavior between
|
||||
// //! different game entities like Ghosts and Pac-Man, including movement,
|
||||
// //! rendering, and position calculations.
|
||||
|
||||
// use glam::Vec2;
|
||||
// use sdl2::render::{Canvas, RenderTarget};
|
||||
|
||||
// use crate::entity::direction::Direction;
|
||||
// use crate::entity::graph::{Edge, Graph, NodeId};
|
||||
// use crate::entity::traversal::{Position, Traverser};
|
||||
// use crate::error::{EntityError, GameError, GameResult, TextureError};
|
||||
// use crate::texture::directional::DirectionalAnimatedTexture;
|
||||
// use crate::texture::sprite::SpriteAtlas;
|
||||
|
||||
// /// Trait defining common functionality for game entities that move through the graph.
|
||||
// ///
|
||||
// /// This trait provides a unified interface for entities that:
|
||||
// /// - Move through the game graph using a traverser
|
||||
// /// - Render using directional animated textures
|
||||
// /// - Have position calculations and movement speed
|
||||
// #[allow(dead_code)]
|
||||
// pub trait Entity {
|
||||
// /// Returns a reference to the entity's traverser for movement control.
|
||||
// fn traverser(&self) -> &Traverser;
|
||||
|
||||
// /// Returns a mutable reference to the entity's traverser for movement control.
|
||||
// fn traverser_mut(&mut self) -> &mut Traverser;
|
||||
|
||||
// /// Returns a reference to the entity's directional animated texture.
|
||||
// fn texture(&self) -> &DirectionalAnimatedTexture;
|
||||
|
||||
// /// Returns a mutable reference to the entity's directional animated texture.
|
||||
// fn texture_mut(&mut self) -> &mut DirectionalAnimatedTexture;
|
||||
|
||||
// /// Returns the movement speed multiplier for this entity.
|
||||
// fn speed(&self) -> f32;
|
||||
|
||||
// /// Determines if this entity can traverse a given edge.
|
||||
// fn can_traverse(&self, edge: Edge) -> bool;
|
||||
|
||||
// /// Updates the entity's position and animation state.
|
||||
// ///
|
||||
// /// This method advances movement through the graph and updates texture animation.
|
||||
// fn tick(&mut self, dt: f32, graph: &Graph);
|
||||
|
||||
// /// Calculates the current pixel position in the game world.
|
||||
// ///
|
||||
// /// Converts the graph position to screen coordinates, accounting for
|
||||
// /// the board offset and centering the sprite.
|
||||
// fn get_pixel_pos(&self, graph: &Graph) -> GameResult<Vec2> {
|
||||
// let pos = match self.traverser().position {
|
||||
// Position::AtNode(node_id) => {
|
||||
// let node = graph.get_node(node_id).ok_or(EntityError::NodeNotFound(node_id))?;
|
||||
// node.position
|
||||
// }
|
||||
// Position::BetweenNodes { from, to, traversed } => {
|
||||
// let from_node = graph.get_node(from).ok_or(EntityError::NodeNotFound(from))?;
|
||||
// let to_node = graph.get_node(to).ok_or(EntityError::NodeNotFound(to))?;
|
||||
// let edge = graph.find_edge(from, to).ok_or(EntityError::EdgeNotFound { from, to })?;
|
||||
// from_node.position + (to_node.position - from_node.position) * (traversed / edge.distance)
|
||||
// }
|
||||
// };
|
||||
|
||||
// Ok(Vec2::new(
|
||||
// pos.x + crate::constants::BOARD_PIXEL_OFFSET.x as f32,
|
||||
// pos.y + crate::constants::BOARD_PIXEL_OFFSET.y as f32,
|
||||
// ))
|
||||
// }
|
||||
|
||||
// /// Returns the current node ID that the entity is at or moving towards.
|
||||
// ///
|
||||
// /// If the entity is at a node, returns that node ID.
|
||||
// /// If the entity is between nodes, returns the node it's moving towards.
|
||||
// fn current_node_id(&self) -> NodeId {
|
||||
// match self.traverser().position {
|
||||
// Position::AtNode(node_id) => node_id,
|
||||
// Position::BetweenNodes { to, .. } => to,
|
||||
// }
|
||||
// }
|
||||
|
||||
// /// Sets the next direction for the entity to take.
|
||||
// ///
|
||||
// /// The direction is buffered and will be applied at the next opportunity,
|
||||
// /// typically when the entity reaches a new node.
|
||||
// fn set_next_direction(&mut self, direction: Direction) {
|
||||
// self.traverser_mut().set_next_direction(direction);
|
||||
// }
|
||||
|
||||
// /// Renders the entity at its current position.
|
||||
// ///
|
||||
// /// Draws the appropriate directional sprite based on the entity's
|
||||
// /// current movement state and direction.
|
||||
// fn render<T: RenderTarget>(&self, canvas: &mut Canvas<T>, atlas: &mut SpriteAtlas, graph: &Graph) -> GameResult<()> {
|
||||
// let pixel_pos = self.get_pixel_pos(graph)?;
|
||||
// let dest = crate::helpers::centered_with_size(
|
||||
// glam::IVec2::new(pixel_pos.x as i32, pixel_pos.y as i32),
|
||||
// glam::UVec2::new(16, 16),
|
||||
// );
|
||||
|
||||
// if self.traverser().position.is_stopped() {
|
||||
// self.texture()
|
||||
// .render_stopped(canvas, atlas, dest, self.traverser().direction)
|
||||
// .map_err(|e| GameError::Texture(TextureError::RenderFailed(e.to_string())))?;
|
||||
// } else {
|
||||
// self.texture()
|
||||
// .render(canvas, atlas, dest, self.traverser().direction)
|
||||
// .map_err(|e| GameError::Texture(TextureError::RenderFailed(e.to_string())))?;
|
||||
// }
|
||||
|
||||
// Ok(())
|
||||
// }
|
||||
// }
|
||||
15
src/error.rs
15
src/error.rs
@@ -31,9 +31,6 @@ pub enum GameError {
|
||||
#[error("Entity error: {0}")]
|
||||
Entity(#[from] EntityError),
|
||||
|
||||
#[error("Game state error: {0}")]
|
||||
GameState(#[from] GameStateError),
|
||||
|
||||
#[error("SDL error: {0}")]
|
||||
Sdl(String),
|
||||
|
||||
@@ -51,6 +48,8 @@ pub enum GameError {
|
||||
pub enum AssetError {
|
||||
#[error("IO error: {0}")]
|
||||
Io(#[from] io::Error),
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[error("Asset not found: {0}")]
|
||||
NotFound(String),
|
||||
}
|
||||
@@ -109,18 +108,8 @@ pub enum EntityError {
|
||||
|
||||
#[error("Edge not found: from {from} to {to}")]
|
||||
EdgeNotFound { from: usize, to: usize },
|
||||
|
||||
#[error("Invalid movement: {0}")]
|
||||
InvalidMovement(String),
|
||||
|
||||
#[error("Pathfinding failed: {0}")]
|
||||
PathfindingFailed(String),
|
||||
}
|
||||
|
||||
/// Errors related to game state operations.
|
||||
#[derive(thiserror::Error, Debug)]
|
||||
pub enum GameStateError {}
|
||||
|
||||
/// Errors related to map operations.
|
||||
#[derive(thiserror::Error, Debug)]
|
||||
pub enum MapError {
|
||||
|
||||
@@ -1,18 +1,37 @@
|
||||
use bevy_ecs::prelude::*;
|
||||
use bevy_ecs::{entity::Entity, event::Event};
|
||||
|
||||
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)]
|
||||
pub enum GameCommand {
|
||||
/// Request immediate game shutdown
|
||||
Exit,
|
||||
MovePlayer(crate::entity::direction::Direction),
|
||||
/// Set Pac-Man's movement direction
|
||||
MovePlayer(Direction),
|
||||
/// Cycle through debug visualization modes
|
||||
ToggleDebug,
|
||||
/// Toggle audio mute state
|
||||
MuteAudio,
|
||||
/// Restart the current level with fresh entity positions and items
|
||||
ResetLevel,
|
||||
/// Pause or resume game ticking logic
|
||||
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)]
|
||||
pub enum GameEvent {
|
||||
/// Player input command to be processed by relevant game systems
|
||||
Command(GameCommand),
|
||||
/// Physical overlap detected between two entities requiring gameplay response
|
||||
Collision(Entity, Entity),
|
||||
}
|
||||
|
||||
|
||||
@@ -3,10 +3,10 @@
|
||||
include!(concat!(env!("OUT_DIR"), "/atlas_data.rs"));
|
||||
|
||||
use crate::constants::CANVAS_SIZE;
|
||||
use crate::entity::direction::Direction;
|
||||
use crate::error::{GameError, GameResult, TextureError};
|
||||
use crate::events::GameEvent;
|
||||
use crate::map::builder::Map;
|
||||
use crate::map::direction::Direction;
|
||||
use crate::systems::blinking::Blinking;
|
||||
use crate::systems::movement::{BufferedDirection, Position, Velocity};
|
||||
use crate::systems::player::player_movement_system;
|
||||
@@ -48,18 +48,37 @@ use crate::{
|
||||
texture::sprite::{AtlasMapper, SpriteAtlas},
|
||||
};
|
||||
|
||||
pub mod state;
|
||||
|
||||
/// 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
|
||||
/// handling user input, updating the game state, and rendering the game.
|
||||
/// Orchestrates all game systems through a centralized `World` containing entities,
|
||||
/// 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 world: World,
|
||||
pub schedule: Schedule,
|
||||
}
|
||||
|
||||
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(
|
||||
canvas: &'static mut Canvas<Window>,
|
||||
texture_creator: &'static mut TextureCreator<WindowContext>,
|
||||
@@ -291,7 +310,12 @@ impl Game {
|
||||
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<()> {
|
||||
// Extract the data we need first to avoid borrow conflicts
|
||||
let ghost_start_positions = {
|
||||
@@ -396,9 +420,21 @@ impl Game {
|
||||
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 {
|
||||
self.world.insert_resource(DeltaTime(dt));
|
||||
|
||||
@@ -1,153 +0,0 @@
|
||||
// use std::collections::VecDeque;
|
||||
|
||||
// use sdl2::{
|
||||
// image::LoadTexture,
|
||||
// render::{Texture, TextureCreator},
|
||||
// video::WindowContext,
|
||||
// };
|
||||
// use smallvec::SmallVec;
|
||||
|
||||
// use crate::{
|
||||
// asset::{get_asset_bytes, Asset},
|
||||
// audio::Audio,
|
||||
// constants::RAW_BOARD,
|
||||
// entity::{
|
||||
// collision::{Collidable, CollisionSystem, EntityId},
|
||||
// ghost::{Ghost, GhostType},
|
||||
// item::Item,
|
||||
// pacman::Pacman,
|
||||
// },
|
||||
// error::{GameError, GameResult, TextureError},
|
||||
// game::events::GameEvent,
|
||||
// map::builder::Map,
|
||||
// texture::{
|
||||
// sprite::{AtlasMapper, SpriteAtlas},
|
||||
// text::TextTexture,
|
||||
// },
|
||||
// };
|
||||
|
||||
// include!(concat!(env!("OUT_DIR"), "/atlas_data.rs"));
|
||||
|
||||
// /// The `GameState` struct holds all the essential data for the game.
|
||||
// ///
|
||||
// /// This includes the score, map, entities (Pac-Man, ghosts, items),
|
||||
// /// collision system, and rendering resources. By centralizing the game's state,
|
||||
// /// we can cleanly separate it from the game's logic, making it easier to manage
|
||||
// /// and reason about.
|
||||
// pub struct GameState {
|
||||
// pub paused: bool,
|
||||
|
||||
// pub score: u32,
|
||||
// pub map: Map,
|
||||
// pub pacman: Pacman,
|
||||
// pub pacman_id: EntityId,
|
||||
// pub ghosts: SmallVec<[Ghost; 4]>,
|
||||
// pub ghost_ids: SmallVec<[EntityId; 4]>,
|
||||
// pub items: Vec<Item>,
|
||||
// pub item_ids: Vec<EntityId>,
|
||||
// pub debug_mode: bool,
|
||||
// pub event_queue: VecDeque<GameEvent>,
|
||||
|
||||
// // Collision system
|
||||
// pub(crate) collision_system: CollisionSystem,
|
||||
|
||||
// // Rendering resources
|
||||
// pub(crate) atlas: SpriteAtlas,
|
||||
// pub(crate) text_texture: TextTexture,
|
||||
|
||||
// // Audio
|
||||
// pub audio: Audio,
|
||||
|
||||
// // Map texture pre-rendering
|
||||
// pub(crate) map_texture: Option<Texture<'static>>,
|
||||
// pub(crate) map_rendered: bool,
|
||||
// pub(crate) texture_creator: &'static TextureCreator<WindowContext>,
|
||||
// }
|
||||
|
||||
// impl GameState {
|
||||
// /// Creates a new `GameState` by initializing all the game's data.
|
||||
// ///
|
||||
// /// This function sets up the map, Pac-Man, ghosts, items, collision system,
|
||||
// /// and all rendering resources required to start the game. It returns a `GameResult`
|
||||
// /// to handle any potential errors during initialization.
|
||||
// pub fn new(texture_creator: &'static TextureCreator<WindowContext>) -> GameResult<Self> {
|
||||
// let map = Map::new(RAW_BOARD)?;
|
||||
|
||||
// let start_node = map.start_positions.pacman;
|
||||
|
||||
// let atlas_bytes = get_asset_bytes(Asset::Atlas)?;
|
||||
// let atlas_texture = texture_creator.load_texture_bytes(&atlas_bytes).map_err(|e| {
|
||||
// if e.to_string().contains("format") || e.to_string().contains("unsupported") {
|
||||
// GameError::Texture(TextureError::InvalidFormat(format!("Unsupported texture format: {e}")))
|
||||
// } else {
|
||||
// GameError::Texture(TextureError::LoadFailed(e.to_string()))
|
||||
// }
|
||||
// })?;
|
||||
|
||||
// let atlas_mapper = AtlasMapper {
|
||||
// frames: ATLAS_FRAMES.into_iter().map(|(k, v)| (k.to_string(), *v)).collect(),
|
||||
// };
|
||||
// let atlas = SpriteAtlas::new(atlas_texture, atlas_mapper);
|
||||
|
||||
// let text_texture = TextTexture::new(1.0);
|
||||
// let audio = Audio::new();
|
||||
// let pacman = Pacman::new(&map.graph, start_node, &atlas)?;
|
||||
|
||||
// // Generate items (pellets and energizers)
|
||||
// let items = map.generate_items(&atlas)?;
|
||||
|
||||
// // Initialize collision system
|
||||
// let mut collision_system = CollisionSystem::default();
|
||||
|
||||
// // Register Pac-Man
|
||||
// let pacman_id = collision_system.register_entity(pacman.position());
|
||||
|
||||
// // Register items
|
||||
// let item_ids = items
|
||||
// .iter()
|
||||
// .map(|item| collision_system.register_entity(item.position()))
|
||||
// .collect();
|
||||
|
||||
// // Create and register ghosts
|
||||
// let ghosts = [GhostType::Blinky, GhostType::Pinky, GhostType::Inky, GhostType::Clyde]
|
||||
// .iter()
|
||||
// .zip(
|
||||
// [
|
||||
// map.start_positions.blinky,
|
||||
// map.start_positions.pinky,
|
||||
// map.start_positions.inky,
|
||||
// map.start_positions.clyde,
|
||||
// ]
|
||||
// .iter(),
|
||||
// )
|
||||
// .map(|(ghost_type, start_node)| Ghost::new(&map.graph, *start_node, *ghost_type, &atlas))
|
||||
// .collect::<GameResult<SmallVec<[_; 4]>>>()?;
|
||||
|
||||
// // Register ghosts
|
||||
// let ghost_ids = ghosts
|
||||
// .iter()
|
||||
// .map(|ghost| collision_system.register_entity(ghost.position()))
|
||||
// .collect();
|
||||
|
||||
// Ok(Self {
|
||||
// paused: false,
|
||||
// map,
|
||||
// atlas,
|
||||
// pacman,
|
||||
// pacman_id,
|
||||
// ghosts,
|
||||
// ghost_ids,
|
||||
// items,
|
||||
// item_ids,
|
||||
// text_texture,
|
||||
// audio,
|
||||
// score: 0,
|
||||
// debug_mode: false,
|
||||
// collision_system,
|
||||
// map_texture: None,
|
||||
// map_rendered: false,
|
||||
// texture_creator,
|
||||
// event_queue: VecDeque::new(),
|
||||
// })
|
||||
// }
|
||||
// }
|
||||
@@ -1,10 +0,0 @@
|
||||
use glam::{IVec2, UVec2};
|
||||
use sdl2::rect::Rect;
|
||||
|
||||
pub fn centered_with_size(pixel_pos: IVec2, size: UVec2) -> Rect {
|
||||
// Ensure the position doesn't cause integer overflow when centering
|
||||
let x = pixel_pos.x.saturating_sub(size.x as i32 / 2);
|
||||
let y = pixel_pos.y.saturating_sub(size.y as i32 / 2);
|
||||
|
||||
Rect::new(x, y, size.x, size.y)
|
||||
}
|
||||
@@ -4,11 +4,9 @@ pub mod app;
|
||||
pub mod asset;
|
||||
pub mod audio;
|
||||
pub mod constants;
|
||||
pub mod entity;
|
||||
pub mod error;
|
||||
pub mod events;
|
||||
pub mod game;
|
||||
pub mod helpers;
|
||||
pub mod map;
|
||||
pub mod platform;
|
||||
pub mod systems;
|
||||
|
||||
@@ -10,11 +10,9 @@ mod asset;
|
||||
mod audio;
|
||||
mod constants;
|
||||
|
||||
mod entity;
|
||||
mod error;
|
||||
mod events;
|
||||
mod game;
|
||||
mod helpers;
|
||||
mod map;
|
||||
mod platform;
|
||||
mod systems;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Map construction and building functionality.
|
||||
use crate::constants::{MapTile, BOARD_CELL_SIZE, CELL_SIZE};
|
||||
use crate::entity::direction::Direction;
|
||||
use crate::entity::graph::{Graph, Node, TraversalFlags};
|
||||
use crate::map::direction::Direction;
|
||||
use crate::map::graph::{Graph, Node, TraversalFlags};
|
||||
use crate::map::parser::MapTileParser;
|
||||
use crate::systems::movement::NodeId;
|
||||
use bevy_ecs::resource::Resource;
|
||||
@@ -11,25 +11,37 @@ use tracing::debug;
|
||||
|
||||
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 {
|
||||
/// Pac-Man's starting position in the lower section of the maze
|
||||
pub pacman: NodeId,
|
||||
/// Blinky starts at the ghost house entrance
|
||||
pub blinky: NodeId,
|
||||
/// Pinky starts in the left area of the ghost house
|
||||
pub pinky: NodeId,
|
||||
/// Inky starts in the right area of the ghost house
|
||||
pub inky: NodeId,
|
||||
/// Clyde starts in the center of the ghost house
|
||||
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)]
|
||||
pub struct Map {
|
||||
/// The node map for entity movement.
|
||||
/// Connected graph of navigable positions.
|
||||
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>,
|
||||
/// A mapping of the starting positions of the entities.
|
||||
/// Predetermined spawn locations for all game entities
|
||||
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],
|
||||
}
|
||||
|
||||
@@ -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(
|
||||
graph: &mut Graph,
|
||||
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(
|
||||
graph: &mut Graph,
|
||||
grid_to_node: &HashMap<IVec2, NodeId>,
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
//! This module defines the game map and provides functions for interacting with it.
|
||||
|
||||
pub mod builder;
|
||||
pub mod direction;
|
||||
pub mod graph;
|
||||
pub mod layout;
|
||||
pub mod parser;
|
||||
pub mod render;
|
||||
|
||||
@@ -4,16 +4,21 @@ use crate::constants::{MapTile, BOARD_CELL_SIZE};
|
||||
use crate::error::ParseError;
|
||||
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)]
|
||||
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],
|
||||
/// The positions of the house door tiles.
|
||||
/// Two positions marking the ghost house entrance (represented by '=' characters)
|
||||
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],
|
||||
/// Pac-Man's starting position.
|
||||
/// Starting position for Pac-Man (marked by 'X' character in the layout)
|
||||
pub pacman_start: Option<IVec2>,
|
||||
}
|
||||
|
||||
@@ -21,15 +26,18 @@ pub struct ParsedMap {
|
||||
pub struct 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
|
||||
///
|
||||
/// The parsed map tile, or an error if the character is unknown.
|
||||
/// Returns `ParseError::UnknownCharacter` for any character not defined
|
||||
/// in the game's ASCII art vocabulary.
|
||||
pub fn parse_character(c: char) -> Result<MapTile, ParseError> {
|
||||
match c {
|
||||
'#' => Ok(MapTile::Wall),
|
||||
|
||||
@@ -10,29 +10,29 @@ mod desktop;
|
||||
#[cfg(target_os = "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 {
|
||||
/// 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);
|
||||
|
||||
/// Get the current time in seconds since some reference point.
|
||||
/// This is available for future use in timing and performance monitoring.
|
||||
#[allow(dead_code)]
|
||||
fn get_time(&self) -> f64;
|
||||
|
||||
/// Initialize platform-specific console functionality.
|
||||
/// Configures platform-specific console and debugging output capabilities.
|
||||
fn init_console(&self) -> Result<(), PlatformError>;
|
||||
|
||||
/// Get canvas size for platforms that need it (e.g., Emscripten).
|
||||
/// This is available for future use in responsive design.
|
||||
/// Retrieves the actual display canvas dimensions.
|
||||
#[allow(dead_code)]
|
||||
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>;
|
||||
}
|
||||
|
||||
/// Get the current platform implementation.
|
||||
/// Returns the appropriate platform implementation based on compile-time target.
|
||||
#[allow(dead_code)]
|
||||
pub fn get_platform() -> &'static dyn CommonPlatform {
|
||||
#[cfg(not(target_os = "emscripten"))]
|
||||
|
||||
@@ -9,6 +9,13 @@ use crate::map::builder::Map;
|
||||
use crate::systems::components::{Collider, ItemCollider, PacmanCollider};
|
||||
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(
|
||||
map: Res<Map>,
|
||||
pacman_query: Query<(Entity, &Position, &Collider), With<PacmanCollider>>,
|
||||
|
||||
@@ -2,7 +2,7 @@ use bevy_ecs::{bundle::Bundle, component::Component, resource::Resource};
|
||||
use bitflags::bitflags;
|
||||
|
||||
use crate::{
|
||||
entity::graph::TraversalFlags,
|
||||
map::graph::TraversalFlags,
|
||||
systems::movement::{BufferedDirection, Position, Velocity},
|
||||
texture::{animated::AnimatedTexture, sprite::AtlasTile},
|
||||
};
|
||||
@@ -41,6 +41,7 @@ impl Ghost {
|
||||
}
|
||||
|
||||
/// Returns the ghost's color for debug rendering.
|
||||
#[allow(dead_code)]
|
||||
pub fn debug_color(&self) -> sdl2::pixels::Color {
|
||||
match self {
|
||||
Ghost::Blinky => sdl2::pixels::Color::RGB(255, 0, 0), // Red
|
||||
|
||||
@@ -3,18 +3,18 @@ use rand::prelude::*;
|
||||
use smallvec::SmallVec;
|
||||
|
||||
use crate::{
|
||||
entity::{direction::Direction, graph::Edge},
|
||||
map::builder::Map,
|
||||
map::{
|
||||
builder::Map,
|
||||
direction::Direction,
|
||||
graph::{Edge, TraversalFlags},
|
||||
},
|
||||
systems::{
|
||||
components::{DeltaTime, Ghost},
|
||||
movement::{Position, Velocity},
|
||||
},
|
||||
};
|
||||
|
||||
/// Ghost AI system that handles randomized movement decisions.
|
||||
///
|
||||
/// This system runs on all ghosts and makes periodic decisions about
|
||||
/// which direction to move in when they reach intersections.
|
||||
/// Autonomous ghost AI system implementing randomized movement with backtracking avoidance.
|
||||
pub fn ghost_movement_system(
|
||||
map: Res<Map>,
|
||||
delta_time: Res<DeltaTime>,
|
||||
@@ -32,9 +32,7 @@ pub fn ghost_movement_system(
|
||||
|
||||
// Collect all available directions that ghosts can traverse
|
||||
for edge in Direction::DIRECTIONS.iter().flat_map(|d| intersection.get(*d)) {
|
||||
if edge.traversal_flags.contains(crate::entity::graph::TraversalFlags::GHOST)
|
||||
&& edge.direction != opposite
|
||||
{
|
||||
if edge.traversal_flags.contains(TraversalFlags::GHOST) && edge.direction != opposite {
|
||||
non_opposite_options.push(edge);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,8 +10,8 @@ use sdl2::{event::Event, keyboard::Keycode, EventPump};
|
||||
|
||||
use crate::systems::components::DeltaTime;
|
||||
use crate::{
|
||||
entity::direction::Direction,
|
||||
events::{GameCommand, GameEvent},
|
||||
map::direction::Direction,
|
||||
};
|
||||
|
||||
#[derive(Resource, Default, Debug, Copy, Clone)]
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
use crate::entity::direction::Direction;
|
||||
use crate::entity::graph::Graph;
|
||||
use crate::error::{EntityError, GameResult};
|
||||
use crate::map::direction::Direction;
|
||||
use crate::map::graph::Graph;
|
||||
use bevy_ecs::component::Component;
|
||||
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;
|
||||
|
||||
/// 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 },
|
||||
}
|
||||
|
||||
/// 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)]
|
||||
pub enum Position {
|
||||
Stopped {
|
||||
node: NodeId,
|
||||
},
|
||||
/// Entity is stationary at a specific graph node.
|
||||
Stopped { node: NodeId },
|
||||
/// Entity is traveling between two nodes.
|
||||
Moving {
|
||||
from: NodeId,
|
||||
to: NodeId,
|
||||
/// Distance remaining to reach the target node.
|
||||
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> {
|
||||
if distance <= 0.0 || self.is_at_node() {
|
||||
return None;
|
||||
|
||||
@@ -6,10 +6,10 @@ use bevy_ecs::{
|
||||
};
|
||||
|
||||
use crate::{
|
||||
entity::graph::Edge,
|
||||
error::GameError,
|
||||
events::{GameCommand, GameEvent},
|
||||
map::builder::Map,
|
||||
map::graph::Edge,
|
||||
systems::{
|
||||
components::{AudioState, DeltaTime, EntityType, GlobalState, PlayerControlled},
|
||||
debug::DebugState,
|
||||
@@ -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(
|
||||
mut events: EventReader<GameEvent>,
|
||||
mut state: ResMut<GlobalState>,
|
||||
@@ -69,6 +74,11 @@ fn can_traverse(entity_type: EntityType, edge: Edge) -> bool {
|
||||
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(
|
||||
map: Res<Map>,
|
||||
delta_time: Res<DeltaTime>,
|
||||
|
||||
@@ -7,6 +7,7 @@ use bevy_ecs::entity::Entity;
|
||||
use bevy_ecs::event::EventWriter;
|
||||
use bevy_ecs::prelude::{Changed, Or, RemovedComponents};
|
||||
use bevy_ecs::system::{NonSendMut, Query, Res, ResMut};
|
||||
use sdl2::rect::{Point, Rect};
|
||||
use sdl2::render::{Canvas, Texture};
|
||||
use sdl2::video::Window;
|
||||
|
||||
@@ -99,9 +100,10 @@ pub fn render_system(
|
||||
let pos = position.get_pixel_position(&map.graph);
|
||||
match pos {
|
||||
Ok(pos) => {
|
||||
let dest = crate::helpers::centered_with_size(
|
||||
glam::IVec2::new(pos.x as i32, pos.y as i32),
|
||||
glam::UVec2::new(renderable.sprite.size.x as u32, renderable.sprite.size.y as u32),
|
||||
let dest = Rect::from_center(
|
||||
Point::from((pos.x as i32, pos.y as i32)),
|
||||
renderable.sprite.size.x as u32,
|
||||
renderable.sprite.size.y as u32,
|
||||
);
|
||||
|
||||
renderable
|
||||
|
||||
@@ -1,11 +1,19 @@
|
||||
use crate::error::{AnimatedTextureError, GameError, GameResult, TextureError};
|
||||
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)]
|
||||
pub struct AnimatedTexture {
|
||||
/// Sequence of sprite tiles that make up the animation frames
|
||||
tiles: Vec<AtlasTile>,
|
||||
/// Duration each frame should be displayed (in seconds)
|
||||
frame_duration: f32,
|
||||
/// Index of the currently active frame in the tiles vector
|
||||
current_frame: usize,
|
||||
/// Accumulated time since the last frame change (for smooth timing)
|
||||
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) {
|
||||
self.time_bank += dt;
|
||||
while self.time_bank >= self.frame_duration {
|
||||
|
||||
@@ -8,8 +8,10 @@ use std::collections::HashMap;
|
||||
|
||||
use crate::error::TextureError;
|
||||
|
||||
/// Atlas frame mapping data loaded from JSON metadata files.
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
pub struct AtlasMapper {
|
||||
/// Mapping from sprite name to frame bounds within the atlas texture
|
||||
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 {
|
||||
/// The combined texture containing all sprite frames
|
||||
texture: Texture<'static>,
|
||||
/// Mapping from sprite names to their pixel coordinates within the texture
|
||||
tiles: HashMap<String, MapperFrame>,
|
||||
default_color: Option<Color>,
|
||||
/// Cached color modulation state to avoid redundant SDL2 calls
|
||||
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> {
|
||||
self.tiles.get(name).map(|frame| AtlasTile {
|
||||
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]
|
||||
fn test_raw_board_structure() {
|
||||
// Test board dimensions match expected size
|
||||
assert_eq!(RAW_BOARD.len(), BOARD_CELL_SIZE.y as usize);
|
||||
|
||||
for row in RAW_BOARD.iter() {
|
||||
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[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]
|
||||
fn test_raw_board_content() {
|
||||
let power_pellet_count = RAW_BOARD.iter().flat_map(|row| row.chars()).filter(|&c| c == 'o').count();
|
||||
assert_eq!(power_pellet_count, 4);
|
||||
|
||||
assert!(RAW_BOARD.iter().any(|row| row.contains('X')));
|
||||
assert!(RAW_BOARD.iter().any(|row| row.contains("==")));
|
||||
fn test_raw_board_contains_required_elements() {
|
||||
// Test that essential game elements are present
|
||||
assert!(
|
||||
RAW_BOARD.iter().any(|row| row.contains('X')),
|
||||
"Board should contain Pac-Man start position"
|
||||
);
|
||||
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"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use glam::IVec2;
|
||||
use pacman::entity::direction::*;
|
||||
use pacman::map::direction::*;
|
||||
|
||||
#[test]
|
||||
fn test_direction_opposite() {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use pacman::entity::direction::Direction;
|
||||
use pacman::entity::graph::{Graph, Node, TraversalFlags};
|
||||
use pacman::map::direction::Direction;
|
||||
use pacman::map::graph::{Graph, Node, TraversalFlags};
|
||||
|
||||
fn create_test_graph() -> Graph {
|
||||
let mut graph = Graph::new();
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
use glam::{IVec2, UVec2};
|
||||
use pacman::helpers::centered_with_size;
|
||||
|
||||
#[test]
|
||||
fn test_centered_with_size() {
|
||||
let test_cases = [
|
||||
((100, 100), (50, 30), (75, 85)),
|
||||
((50, 50), (51, 31), (25, 35)),
|
||||
((0, 0), (100, 100), (-50, -50)),
|
||||
((-100, -50), (80, 40), (-140, -70)),
|
||||
((1000, 1000), (1000, 1000), (500, 500)),
|
||||
];
|
||||
|
||||
for ((pos_x, pos_y), (size_x, size_y), (expected_x, expected_y)) in test_cases {
|
||||
let rect = centered_with_size(IVec2::new(pos_x, pos_y), UVec2::new(size_x, size_y));
|
||||
assert_eq!(rect.origin(), (expected_x, expected_y));
|
||||
assert_eq!(rect.size(), (size_x, size_y));
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
// use glam::U16Vec2;
|
||||
// use pacman::texture::sprite::{AtlasTile, Sprite};
|
||||
|
||||
// #[test]
|
||||
// fn test_item_type_get_score() {
|
||||
// assert_eq!(ItemType::Pellet.get_score(), 10);
|
||||
// assert_eq!(ItemType::Energizer.get_score(), 50);
|
||||
|
||||
// let fruit = ItemType::Fruit { kind: FruitKind::Apple };
|
||||
// assert_eq!(fruit.get_score(), 100);
|
||||
// }
|
||||
|
||||
// #[test]
|
||||
// fn test_fruit_kind_increasing_score() {
|
||||
// // Build a list of fruit kinds, sorted by their index
|
||||
// let mut kinds = FruitKind::iter()
|
||||
// .map(|kind| (kind.index(), kind.get_score()))
|
||||
// .collect::<Vec<_>>();
|
||||
// kinds.sort_unstable_by_key(|(index, _)| *index);
|
||||
|
||||
// assert_eq!(kinds.len(), FruitKind::COUNT);
|
||||
|
||||
// // Check that the score increases as expected
|
||||
// for window in kinds.windows(2) {
|
||||
// let ((_, prev), (_, next)) = (window[0], window[1]);
|
||||
// assert!(prev < next, "Fruits should have increasing scores, but {prev:?} < {next:?}");
|
||||
// }
|
||||
// }
|
||||
|
||||
// #[test]
|
||||
// fn test_item_creation_and_collection() {
|
||||
// let atlas_tile = AtlasTile {
|
||||
// pos: U16Vec2::new(0, 0),
|
||||
// size: U16Vec2::new(16, 16),
|
||||
// color: None,
|
||||
// };
|
||||
// let sprite = Sprite::new(atlas_tile);
|
||||
// let mut item = Item::new(0, ItemType::Pellet, sprite);
|
||||
|
||||
// assert!(!item.is_collected());
|
||||
// assert_eq!(item.get_score(), 10);
|
||||
// assert_eq!(item.position().from_node_id(), 0);
|
||||
|
||||
// item.collect();
|
||||
// assert!(item.is_collected());
|
||||
// }
|
||||
Reference in New Issue
Block a user