Compare commits

..

6 Commits

Author SHA1 Message Date
Ryan Walters
5d56b31353 feat: fruit spawning mechanism, sprites, pellet counting, fruit trigger observer 2025-09-09 11:26:05 -05:00
Ryan Walters
b4990af109 chore: fix clippy lints part 972 2025-09-08 23:53:30 -05:00
Ryan Walters
088c496ad9 refactor: store common components & bundles in 'common' submodule, move others directly into relevant files, create 'animation' submodule 2025-09-08 23:53:30 -05:00
Ryan Walters
5bdf11dfb6 feat: enhance slow frame timing warning 2025-09-08 19:19:23 -05:00
Ryan Walters
c163171304 refactor: use Single<> for player queries 2025-09-08 16:50:28 -05:00
Ryan Walters
63e1059df8 feat: implement entity-based sprite system for HUD display (lives)
- Spawn HUD elements as Renderables with simple change-based entity updates
- Updated rendering systems to accommodate new precise pixel positioning for life sprites.
2025-09-08 16:22:40 -05:00
26 changed files with 960 additions and 667 deletions

2
Cargo.lock generated
View File

@@ -663,7 +663,7 @@ checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
[[package]]
name = "pacman"
version = "0.78.1"
version = "0.78.4"
dependencies = [
"anyhow",
"bevy_ecs",

View File

@@ -1,6 +1,6 @@
[package]
name = "pacman"
version = "0.78.1"
version = "0.78.4"
authors = ["Xevion"]
edition = "2021"
rust-version = "1.86.0"

View File

@@ -79,6 +79,8 @@ pub mod collider {
pub const PELLET_SIZE: f32 = CELL_SIZE as f32 * 0.4;
/// Collider size for power pellets/energizers (0.95x cell size)
pub const POWER_PELLET_SIZE: f32 = CELL_SIZE as f32 * 0.95;
/// Collider size for fruits (0.8x cell size)
pub const FRUIT_SIZE: f32 = CELL_SIZE as f32 * 1.375;
}
/// UI and rendering constants

View File

@@ -13,13 +13,13 @@ use crate::map::direction::Direction;
use crate::systems::{
self, audio_system, blinking_system, collision_system, combined_render_system, directional_render_system,
dirty_render_system, eaten_ghost_system, ghost_collision_system, ghost_movement_system, ghost_state_system,
hud_render_system, item_system, linear_render_system, present_system, profile, time_to_live_system, touch_ui_render_system,
AudioEvent, AudioResource, AudioState, BackbufferResource, Blinking, BufferedDirection, Collider, DebugState,
DebugTextureResource, DeltaTime, DirectionalAnimation, EntityType, Frozen, GameStage, Ghost, GhostAnimation, GhostAnimations,
GhostBundle, GhostCollider, GhostState, GlobalState, Hidden, ItemBundle, ItemCollider, LastAnimationState, LinearAnimation,
MapTextureResource, MovementModifiers, NodeId, PacmanCollider, PlayerAnimation, PlayerBundle, PlayerControlled,
PlayerDeathAnimation, PlayerLives, Position, RenderDirty, Renderable, ScoreResource, StartupSequence, SystemId,
SystemTimings, Timing, TouchState, Velocity,
hud_render_system, item_system, linear_render_system, player_life_sprite_system, present_system, profile,
time_to_live_system, touch_ui_render_system, AudioEvent, AudioResource, AudioState, BackbufferResource, Blinking,
BufferedDirection, Collider, DebugState, DebugTextureResource, DeltaTime, DirectionalAnimation, EntityType, Frozen,
GameStage, Ghost, GhostAnimation, GhostAnimations, GhostBundle, GhostCollider, GhostState, GlobalState, Hidden, ItemBundle,
ItemCollider, LastAnimationState, LinearAnimation, MapTextureResource, MovementModifiers, NodeId, PacmanCollider,
PlayerAnimation, PlayerBundle, PlayerControlled, PlayerDeathAnimation, PlayerLives, Position, RenderDirty, Renderable,
ScoreResource, StartupSequence, SystemId, SystemTimings, Timing, TouchState, Velocity,
};
use crate::texture::animated::{DirectionalTiles, TileSequence};
@@ -42,8 +42,7 @@ use crate::{
asset::{get_asset_bytes, Asset},
events::GameCommand,
map::render::MapRenderer,
systems::debug::{BatchedLinesResource, TtfAtlasResource},
systems::input::{Bindings, CursorPosition},
systems::{BatchedLinesResource, Bindings, CursorPosition, TtfAtlasResource},
texture::sprite::{AtlasMapper, SpriteAtlas},
};
@@ -128,6 +127,8 @@ impl Game {
debug!("Setting up ECS event registry and observers");
Self::setup_ecs(&mut world);
world.add_observer(systems::spawn_fruit_observer);
debug!("Inserting resources into ECS world");
Self::insert_resources(
&mut world,
@@ -410,6 +411,7 @@ impl Game {
world.insert_resource(GlobalState { exit: false });
world.insert_resource(PlayerLives::default());
world.insert_resource(ScoreResource(0));
world.insert_resource(crate::systems::item::PelletCount(0));
world.insert_resource(SystemTimings::default());
world.insert_resource(Timing::default());
world.insert_resource(Bindings::default());
@@ -449,10 +451,9 @@ impl Game {
let linear_render_system = profile(SystemId::LinearRender, linear_render_system);
let dirty_render_system = profile(SystemId::DirtyRender, dirty_render_system);
let hud_render_system = profile(SystemId::HudRender, hud_render_system);
let player_life_sprite_system = profile(SystemId::HudRender, player_life_sprite_system);
let present_system = profile(SystemId::Present, present_system);
let unified_ghost_state_system = profile(SystemId::GhostStateAnimation, ghost_state_system);
// let death_sequence_system = profile(SystemId::DeathSequence, death_sequence_system);
// let game_over_system = profile(SystemId::GameOver, systems::game_over_system);
let eaten_ghost_system = profile(SystemId::EatenGhost, eaten_ghost_system);
let time_to_live_system = profile(SystemId::TimeToLive, time_to_live_system);
@@ -460,10 +461,8 @@ impl Game {
dirty.0 = true;
};
schedule.add_systems(
forced_dirty_system
.run_if(|score: Res<ScoreResource>, stage: Res<GameStage>| score.is_changed() || stage.is_changed()),
);
schedule.add_systems((forced_dirty_system
.run_if(|score: Res<ScoreResource>, stage: Res<GameStage>| score.is_changed() || stage.is_changed()),));
// Input system should always run to prevent SDL event pump from blocking
let input_systems = (
@@ -496,6 +495,7 @@ impl Game {
dirty_render_system,
combined_render_system,
hud_render_system,
player_life_sprite_system,
touch_ui_render_system,
present_system,
)
@@ -716,12 +716,23 @@ impl Game {
timings.add_total_timing(total_duration, new_tick);
// Log performance warnings for slow frames
if total_duration.as_millis() > 20 {
// Warn if frame takes more than 20ms
if total_duration.as_millis() > 17 {
// Warn if frame takes too long
let slowest_systems = timings.get_slowest_systems();
let systems_context = if slowest_systems.is_empty() {
"No specific systems identified".to_string()
} else {
slowest_systems
.iter()
.map(|(id, duration)| format!("{} ({:.2?})", id, duration))
.collect::<Vec<String>>()
.join(", ")
};
warn!(
duration_ms = total_duration.as_millis(),
frame_dt = ?std::time::Duration::from_secs_f32(dt),
total = format!("{:.3?}", total_duration),
tick = new_tick,
systems = systems_context,
"Frame took longer than expected"
);
}

View File

@@ -3,7 +3,7 @@ use crate::constants::{MapTile, BOARD_CELL_SIZE, CELL_SIZE};
use crate::map::direction::Direction;
use crate::map::graph::{Graph, Node, TraversalFlags};
use crate::map::parser::MapTileParser;
use crate::systems::movement::NodeId;
use crate::systems::{NodeId, Position};
use bevy_ecs::resource::Resource;
use glam::{I8Vec2, IVec2, Vec2};
use std::collections::{HashMap, VecDeque};
@@ -25,6 +25,8 @@ pub struct NodePositions {
pub inky: NodeId,
/// Clyde starts in the center of the ghost house
pub clyde: NodeId,
/// Fruit spawn location directly below the ghost house
pub fruit_spawn: Position,
}
/// Complete maze representation combining visual layout with navigation pathfinding.
@@ -154,12 +156,37 @@ impl Map {
let (house_entrance_node_id, left_center_node_id, center_center_node_id, right_center_node_id) =
Self::build_house(&mut graph, &grid_to_node, &house_door)?;
// Find fruit spawn location (directly below ghost house)
let left_node_position = I8Vec2::new(13, 17);
let left_node_id = grid_to_node.get(&left_node_position).unwrap();
let right_node_position = I8Vec2::new(14, 17);
let right_node_id = grid_to_node.get(&right_node_position).unwrap();
let distance = graph
.get_node(*right_node_id)
.unwrap()
.position
.distance(graph.get_node(*left_node_id).unwrap().position);
// interpolate between the two nodes
let fruit_spawn_position: Position = Position::Moving {
from: *left_node_id,
to: *right_node_id,
remaining_distance: distance / 2.0,
};
tracing::warn!(
fruit_spawn_position = ?fruit_spawn_position,
"Fruit spawn position found"
);
let start_positions = NodePositions {
pacman: grid_to_node[&start_pos],
blinky: house_entrance_node_id,
pinky: left_center_node_id,
inky: right_center_node_id,
clyde: center_center_node_id,
fruit_spawn: fruit_spawn_position,
};
// Build tunnel connections

View File

@@ -1,6 +1,6 @@
use glam::Vec2;
use crate::systems::movement::NodeId;
use crate::systems::NodeId;
use super::direction::Direction;

132
src/systems/animation.rs Normal file
View File

@@ -0,0 +1,132 @@
use bevy_ecs::{
component::Component,
query::{Has, Or, With, Without},
resource::Resource,
system::{Query, Res},
};
use crate::{
systems::{DeltaTime, Dying, Frozen, Position, Renderable, Velocity},
texture::animated::{DirectionalTiles, TileSequence},
};
/// Directional animation component with shared timing across all directions
#[derive(Component, Clone)]
pub struct DirectionalAnimation {
pub moving_tiles: DirectionalTiles,
pub stopped_tiles: DirectionalTiles,
pub current_frame: usize,
pub time_bank: u16,
pub frame_duration: u16,
}
impl DirectionalAnimation {
/// Creates a new directional animation with the given tiles and frame duration
pub fn new(moving_tiles: DirectionalTiles, stopped_tiles: DirectionalTiles, frame_duration: u16) -> Self {
Self {
moving_tiles,
stopped_tiles,
current_frame: 0,
time_bank: 0,
frame_duration,
}
}
}
/// Tag component to mark animations that should loop when they reach the end
#[derive(Component, Clone, Copy, Debug, PartialEq, Eq)]
pub struct Looping;
/// Linear animation component for non-directional animations (frightened ghosts)
#[derive(Component, Resource, Clone)]
pub struct LinearAnimation {
pub tiles: TileSequence,
pub current_frame: usize,
pub time_bank: u16,
pub frame_duration: u16,
pub finished: bool,
}
impl LinearAnimation {
/// Creates a new linear animation with the given tiles and frame duration
pub fn new(tiles: TileSequence, frame_duration: u16) -> Self {
Self {
tiles,
current_frame: 0,
time_bank: 0,
frame_duration,
finished: false,
}
}
}
/// Updates directional animated entities with synchronized timing across directions.
///
/// This runs before the render system to update sprites based on current direction and movement state.
/// All directions share the same frame timing to ensure perfect synchronization.
pub fn directional_render_system(
dt: Res<DeltaTime>,
mut query: Query<(&Position, &Velocity, &mut DirectionalAnimation, &mut Renderable), Without<Frozen>>,
) {
let ticks = (dt.seconds * 60.0).round() as u16; // Convert from seconds to ticks at 60 ticks/sec
for (position, velocity, mut anim, mut renderable) in query.iter_mut() {
let stopped = matches!(position, Position::Stopped { .. });
// Only tick animation when moving to preserve stopped frame
if !stopped {
// Tick shared animation state
anim.time_bank += ticks;
while anim.time_bank >= anim.frame_duration {
anim.time_bank -= anim.frame_duration;
anim.current_frame += 1;
}
}
// Get tiles for current direction and movement state
let tiles = if stopped {
anim.stopped_tiles.get(velocity.direction)
} else {
anim.moving_tiles.get(velocity.direction)
};
if !tiles.is_empty() {
let new_tile = tiles.get_tile(anim.current_frame);
if renderable.sprite != new_tile {
renderable.sprite = new_tile;
}
}
}
}
/// System that updates `Renderable` sprites for entities with `LinearAnimation`.
#[allow(clippy::type_complexity)]
pub fn linear_render_system(
dt: Res<DeltaTime>,
mut query: Query<(&mut LinearAnimation, &mut Renderable, Has<Looping>), Or<(Without<Frozen>, With<Dying>)>>,
) {
for (mut anim, mut renderable, looping) in query.iter_mut() {
if anim.finished {
continue;
}
anim.time_bank += dt.ticks as u16;
let frames_to_advance = (anim.time_bank / anim.frame_duration) as usize;
if frames_to_advance == 0 {
continue;
}
let total_frames = anim.tiles.len();
if !looping && anim.current_frame + frames_to_advance >= total_frames {
anim.finished = true;
anim.current_frame = total_frames - 1;
} else {
anim.current_frame += frames_to_advance;
}
anim.time_bank %= anim.frame_duration;
renderable.sprite = anim.tiles.get_tile(anim.current_frame);
}
}

View File

@@ -5,10 +5,7 @@ use bevy_ecs::{
system::{Commands, Query, Res},
};
use crate::systems::{
components::{DeltaTime, Renderable},
Frozen, Hidden,
};
use crate::systems::{DeltaTime, Frozen, Hidden, Renderable};
#[derive(Component, Debug)]
pub struct Blinking {

View File

@@ -3,17 +3,14 @@ use bevy_ecs::{
entity::Entity,
event::{EventReader, EventWriter},
query::With,
system::{Commands, Query, Res, ResMut},
system::{Commands, Query, Res, ResMut, Single},
};
use tracing::{debug, trace, warn};
use crate::error::GameError;
use crate::events::{GameEvent, StageTransition};
use crate::map::builder::Map;
use crate::systems::{
components::GhostState, movement::Position, AudioEvent, DyingSequence, Frozen, GameStage, Ghost, PlayerControlled,
ScoreResource,
};
use crate::systems::{movement::Position, AudioEvent, DyingSequence, Frozen, GameStage, Ghost, PlayerControlled, ScoreResource};
use crate::{error::GameError, systems::GhostState};
/// A component for defining the collision area of an entity.
#[derive(Component)]
@@ -123,7 +120,7 @@ pub fn ghost_collision_system(
mut stage_events: EventWriter<StageTransition>,
mut score: ResMut<ScoreResource>,
mut game_state: ResMut<GameStage>,
pacman_query: Query<Entity, With<PlayerControlled>>,
player: Single<Entity, With<PlayerControlled>>,
ghost_query: Query<(Entity, &Ghost), With<GhostCollider>>,
mut ghost_state_query: Query<&mut GhostState>,
mut events: EventWriter<AudioEvent>,
@@ -131,9 +128,9 @@ pub fn ghost_collision_system(
for event in collision_events.read() {
if let GameEvent::Collision(entity1, entity2) = event {
// Check if one is Pacman and the other is a ghost
let (pacman_entity, ghost_entity) = if pacman_query.get(*entity1).is_ok() && ghost_query.get(*entity2).is_ok() {
let (pacman_entity, ghost_entity) = if *entity1 == *player && ghost_query.get(*entity2).is_ok() {
(*entity1, *entity2)
} else if pacman_query.get(*entity2).is_ok() && ghost_query.get(*entity1).is_ok() {
} else if *entity2 == *player && ghost_query.get(*entity1).is_ok() {
(*entity2, *entity1)
} else {
continue;

View File

@@ -0,0 +1,43 @@
use bevy_ecs::bundle::Bundle;
use crate::systems::{
BufferedDirection, Collider, DirectionalAnimation, EntityType, Ghost, GhostCollider, GhostState, ItemCollider,
LastAnimationState, MovementModifiers, PacmanCollider, PlayerControlled, Position, Renderable, Velocity,
};
#[derive(Bundle)]
pub struct PlayerBundle {
pub player: PlayerControlled,
pub position: Position,
pub velocity: Velocity,
pub buffered_direction: BufferedDirection,
pub sprite: Renderable,
pub directional_animation: DirectionalAnimation,
pub entity_type: EntityType,
pub collider: Collider,
pub movement_modifiers: MovementModifiers,
pub pacman_collider: PacmanCollider,
}
#[derive(Bundle)]
pub struct ItemBundle {
pub position: Position,
pub sprite: Renderable,
pub entity_type: EntityType,
pub collider: Collider,
pub item_collider: ItemCollider,
}
#[derive(Bundle)]
pub struct GhostBundle {
pub ghost: Ghost,
pub position: Position,
pub velocity: Velocity,
pub sprite: Renderable,
pub directional_animation: DirectionalAnimation,
pub entity_type: EntityType,
pub collider: Collider,
pub ghost_collider: GhostCollider,
pub ghost_state: GhostState,
pub last_animation_state: LastAnimationState,
}

View File

@@ -0,0 +1,105 @@
use bevy_ecs::{component::Component, resource::Resource};
use crate::map::graph::TraversalFlags;
/// A tag component denoting the type of entity.
#[derive(Component, Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EntityType {
Player,
Ghost,
Pellet,
PowerPellet,
Fruit(crate::texture::sprites::FruitSprite),
}
impl EntityType {
/// Returns the traversal flags for this entity type.
pub fn traversal_flags(&self) -> TraversalFlags {
match self {
EntityType::Player => TraversalFlags::PACMAN,
EntityType::Ghost => TraversalFlags::GHOST,
_ => TraversalFlags::empty(), // Static entities don't traverse
}
}
pub fn score_value(&self) -> Option<u32> {
match self {
EntityType::Pellet => Some(10),
EntityType::PowerPellet => Some(50),
EntityType::Fruit(fruit_type) => Some(fruit_type.score_value()),
_ => None,
}
}
pub fn is_collectible(&self) -> bool {
matches!(self, EntityType::Pellet | EntityType::PowerPellet | EntityType::Fruit(_))
}
}
#[derive(Resource)]
pub struct GlobalState {
pub exit: bool,
}
#[derive(Resource)]
pub struct ScoreResource(pub u32);
#[derive(Resource)]
pub struct DeltaTime {
/// Floating-point delta time in seconds
pub seconds: f32,
/// Integer tick delta (usually 1, but can be different for testing)
pub ticks: u32,
}
#[allow(dead_code)]
impl DeltaTime {
/// Creates a new DeltaTime from a floating-point delta time in seconds
///
/// While this method exists as a helper, it does not mean that seconds and ticks are interchangeable.
pub fn from_seconds(seconds: f32) -> Self {
Self {
seconds,
ticks: (seconds * 60.0).round() as u32,
}
}
/// Creates a new DeltaTime from an integer tick delta
///
/// While this method exists as a helper, it does not mean that seconds and ticks are interchangeable.
pub fn from_ticks(ticks: u32) -> Self {
Self {
seconds: ticks as f32 / 60.0,
ticks,
}
}
}
/// Movement modifiers that can affect Pac-Man's speed or handling.
#[derive(Component, Debug, Clone, Copy)]
pub struct MovementModifiers {
/// Multiplier applied to base speed (e.g., tunnels)
pub speed_multiplier: f32,
/// True when currently in a tunnel slowdown region
pub tunnel_slowdown_active: bool,
}
impl Default for MovementModifiers {
fn default() -> Self {
Self {
speed_multiplier: 1.0,
tunnel_slowdown_active: false,
}
}
}
/// Tag component for entities that should be frozen during startup
#[derive(Component, Debug, Clone, Copy)]
pub struct Frozen;
/// Component for HUD life sprite entities.
/// Each life sprite entity has an index indicating its position from left to right (0, 1, 2, etc.).
/// This mostly functions as a tag component for sprites.
#[derive(Component, Debug, Clone, Copy)]
pub struct PlayerLife {
pub index: u32,
}

View File

@@ -0,0 +1,5 @@
pub mod bundles;
pub mod components;
pub use self::bundles::*;
pub use self::components::*;

View File

@@ -1,403 +0,0 @@
use std::collections::HashMap;
use bevy_ecs::{bundle::Bundle, component::Component, resource::Resource};
use bitflags::bitflags;
use crate::{
map::graph::TraversalFlags,
systems::{
movement::{BufferedDirection, Position, Velocity},
Collider, GhostCollider, ItemCollider, PacmanCollider,
},
texture::{
animated::{DirectionalTiles, TileSequence},
sprite::AtlasTile,
},
};
/// A tag component for entities that are controlled by the player.
#[derive(Default, Component)]
pub struct PlayerControlled;
#[derive(Component, Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Ghost {
Blinky,
Pinky,
Inky,
Clyde,
}
impl Ghost {
/// Returns the ghost type name for atlas lookups.
pub fn as_str(self) -> &'static str {
match self {
Ghost::Blinky => "blinky",
Ghost::Pinky => "pinky",
Ghost::Inky => "inky",
Ghost::Clyde => "clyde",
}
}
/// Returns the base movement speed for this ghost type.
pub fn base_speed(self) -> f32 {
match self {
Ghost::Blinky => 1.0,
Ghost::Pinky => 0.95,
Ghost::Inky => 0.9,
Ghost::Clyde => 0.85,
}
}
/// 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
Ghost::Pinky => sdl2::pixels::Color::RGB(255, 182, 255), // Pink
Ghost::Inky => sdl2::pixels::Color::RGB(0, 255, 255), // Cyan
Ghost::Clyde => sdl2::pixels::Color::RGB(255, 182, 85), // Orange
}
}
}
/// A tag component denoting the type of entity.
#[derive(Component, Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EntityType {
Player,
Ghost,
Pellet,
PowerPellet,
}
impl EntityType {
/// Returns the traversal flags for this entity type.
pub fn traversal_flags(&self) -> TraversalFlags {
match self {
EntityType::Player => TraversalFlags::PACMAN,
EntityType::Ghost => TraversalFlags::GHOST,
_ => TraversalFlags::empty(), // Static entities don't traverse
}
}
pub fn score_value(&self) -> Option<u32> {
match self {
EntityType::Pellet => Some(10),
EntityType::PowerPellet => Some(50),
_ => None,
}
}
pub fn is_collectible(&self) -> bool {
matches!(self, EntityType::Pellet | EntityType::PowerPellet)
}
}
/// A component for entities that have a sprite, with a layer for ordering.
///
/// This is intended to be modified by other entities allowing animation.
#[derive(Component)]
pub struct Renderable {
pub sprite: AtlasTile,
pub layer: u8,
}
/// Directional animation component with shared timing across all directions
#[derive(Component, Clone)]
pub struct DirectionalAnimation {
pub moving_tiles: DirectionalTiles,
pub stopped_tiles: DirectionalTiles,
pub current_frame: usize,
pub time_bank: u16,
pub frame_duration: u16,
}
impl DirectionalAnimation {
/// Creates a new directional animation with the given tiles and frame duration
pub fn new(moving_tiles: DirectionalTiles, stopped_tiles: DirectionalTiles, frame_duration: u16) -> Self {
Self {
moving_tiles,
stopped_tiles,
current_frame: 0,
time_bank: 0,
frame_duration,
}
}
}
/// Tag component to mark animations that should loop when they reach the end
#[derive(Component, Clone, Copy, Debug, PartialEq, Eq)]
pub struct Looping;
/// Linear animation component for non-directional animations (frightened ghosts)
#[derive(Component, Resource, Clone)]
pub struct LinearAnimation {
pub tiles: TileSequence,
pub current_frame: usize,
pub time_bank: u16,
pub frame_duration: u16,
pub finished: bool,
}
impl LinearAnimation {
/// Creates a new linear animation with the given tiles and frame duration
pub fn new(tiles: TileSequence, frame_duration: u16) -> Self {
Self {
tiles,
current_frame: 0,
time_bank: 0,
frame_duration,
finished: false,
}
}
}
bitflags! {
#[derive(Component, Default, Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CollisionLayer: u8 {
const PACMAN = 1 << 0;
const GHOST = 1 << 1;
const ITEM = 1 << 2;
}
}
#[derive(Resource)]
pub struct GlobalState {
pub exit: bool,
}
#[derive(Resource)]
pub struct ScoreResource(pub u32);
#[derive(Resource)]
pub struct DeltaTime {
/// Floating-point delta time in seconds
pub seconds: f32,
/// Integer tick delta (usually 1, but can be different for testing)
pub ticks: u32,
}
#[allow(dead_code)]
impl DeltaTime {
/// Creates a new DeltaTime from a floating-point delta time in seconds
///
/// While this method exists as a helper, it does not mean that seconds and ticks are interchangeable.
pub fn from_seconds(seconds: f32) -> Self {
Self {
seconds,
ticks: (seconds * 60.0).round() as u32,
}
}
/// Creates a new DeltaTime from an integer tick delta
///
/// While this method exists as a helper, it does not mean that seconds and ticks are interchangeable.
pub fn from_ticks(ticks: u32) -> Self {
Self {
seconds: ticks as f32 / 60.0,
ticks,
}
}
}
/// Movement modifiers that can affect Pac-Man's speed or handling.
#[derive(Component, Debug, Clone, Copy)]
pub struct MovementModifiers {
/// Multiplier applied to base speed (e.g., tunnels)
pub speed_multiplier: f32,
/// True when currently in a tunnel slowdown region
pub tunnel_slowdown_active: bool,
}
impl Default for MovementModifiers {
fn default() -> Self {
Self {
speed_multiplier: 1.0,
tunnel_slowdown_active: false,
}
}
}
/// Tag component for entities that should be frozen during startup
#[derive(Component, Debug, Clone, Copy)]
pub struct Frozen;
/// Tag component for eaten ghosts
#[derive(Component, Debug, Clone, Copy)]
pub struct Eaten;
/// Tag component for Pac-Man during his death animation.
/// This is mainly because the Frozen tag would stop both movement and animation, while the Dying tag can signal that the animation should continue despite being frozen.
#[derive(Component, Debug, Clone, Copy)]
pub struct Dying;
#[derive(Component, Debug, Clone, Copy)]
pub enum GhostState {
/// Normal ghost behavior - chasing Pac-Man
Normal,
/// Frightened state after power pellet - ghost can be eaten
Frightened {
remaining_ticks: u32,
flash: bool,
remaining_flash_ticks: u32,
},
/// Eyes state - ghost has been eaten and is returning to ghost house
Eyes,
}
/// Component to track the last animation state for efficient change detection
#[derive(Component, Debug, Clone, Copy, PartialEq)]
pub struct LastAnimationState(pub GhostAnimation);
impl GhostState {
/// Creates a new frightened state with the specified duration
pub fn new_frightened(total_ticks: u32, flash_start_ticks: u32) -> Self {
Self::Frightened {
remaining_ticks: total_ticks,
flash: false,
remaining_flash_ticks: flash_start_ticks, // Time until flashing starts
}
}
/// Ticks the ghost state, returning true if the state changed.
pub fn tick(&mut self) -> bool {
if let GhostState::Frightened {
remaining_ticks,
flash,
remaining_flash_ticks,
} = self
{
// Transition out of frightened state
if *remaining_ticks == 0 {
*self = GhostState::Normal;
return true;
}
*remaining_ticks -= 1;
if *remaining_flash_ticks > 0 {
*remaining_flash_ticks = remaining_flash_ticks.saturating_sub(1);
if *remaining_flash_ticks == 0 {
*flash = true;
true
} else {
false
}
} else {
false
}
} else {
false
}
}
/// Returns the appropriate animation state for this ghost state
pub fn animation_state(&self) -> GhostAnimation {
match self {
GhostState::Normal => GhostAnimation::Normal,
GhostState::Eyes => GhostAnimation::Eyes,
GhostState::Frightened { flash: false, .. } => GhostAnimation::Frightened { flash: false },
GhostState::Frightened { flash: true, .. } => GhostAnimation::Frightened { flash: true },
}
}
}
/// Enumeration of different ghost animation states.
/// Note that this is used in micromap which has a fixed size based on the number of variants,
/// so extending this should be done with caution, and will require updating the micromap's capacity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum GhostAnimation {
/// Normal ghost appearance with directional movement animations
Normal,
/// Blue ghost appearance when vulnerable (power pellet active)
Frightened { flash: bool },
/// Eyes-only animation when ghost has been consumed by Pac-Man (Eaten state)
Eyes,
}
/// Global resource containing pre-loaded animation sets for all ghost types.
///
/// This resource is initialized once during game startup and provides O(1) access
/// to animation sets for each ghost type. The animation system uses this resource
/// to efficiently switch between different ghost states without runtime asset loading.
///
/// The HashMap is keyed by `Ghost` enum variants (Blinky, Pinky, Inky, Clyde) and
/// contains the normal directional animation for each ghost type.
#[derive(Resource)]
pub struct GhostAnimations {
pub normal: HashMap<Ghost, DirectionalAnimation>,
pub eyes: DirectionalAnimation,
pub frightened: LinearAnimation,
pub frightened_flashing: LinearAnimation,
}
impl GhostAnimations {
/// Creates a new GhostAnimations resource with the provided data.
pub fn new(
normal: HashMap<Ghost, DirectionalAnimation>,
eyes: DirectionalAnimation,
frightened: LinearAnimation,
frightened_flashing: LinearAnimation,
) -> Self {
Self {
normal,
eyes,
frightened,
frightened_flashing,
}
}
/// Gets the normal directional animation for the specified ghost type.
pub fn get_normal(&self, ghost_type: &Ghost) -> Option<&DirectionalAnimation> {
self.normal.get(ghost_type)
}
/// Gets the eyes animation (shared across all ghosts).
pub fn eyes(&self) -> &DirectionalAnimation {
&self.eyes
}
/// Gets the frightened animations (shared across all ghosts).
pub fn frightened(&self, flash: bool) -> &LinearAnimation {
if flash {
&self.frightened_flashing
} else {
&self.frightened
}
}
}
#[derive(Bundle)]
pub struct PlayerBundle {
pub player: PlayerControlled,
pub position: Position,
pub velocity: Velocity,
pub buffered_direction: BufferedDirection,
pub sprite: Renderable,
pub directional_animation: DirectionalAnimation,
pub entity_type: EntityType,
pub collider: Collider,
pub movement_modifiers: MovementModifiers,
pub pacman_collider: PacmanCollider,
}
#[derive(Bundle)]
pub struct ItemBundle {
pub position: Position,
pub sprite: Renderable,
pub entity_type: EntityType,
pub collider: Collider,
pub item_collider: ItemCollider,
}
#[derive(Bundle)]
pub struct GhostBundle {
pub ghost: Ghost,
pub position: Position,
pub velocity: Velocity,
pub sprite: Renderable,
pub directional_animation: DirectionalAnimation,
pub entity_type: EntityType,
pub collider: Collider,
pub ghost_collider: GhostCollider,
pub ghost_state: GhostState,
pub last_animation_state: LastAnimationState,
}

View File

@@ -1,7 +1,7 @@
use std::collections::HashMap;
use crate::platform;
use crate::systems::components::{
DirectionalAnimation, Frozen, GhostAnimation, GhostState, LastAnimationState, LinearAnimation, Looping,
};
use crate::systems::{DirectionalAnimation, Frozen, LinearAnimation, Looping};
use crate::{
map::{
builder::Map,
@@ -9,18 +9,201 @@ use crate::{
graph::{Edge, TraversalFlags},
},
systems::{
components::{DeltaTime, Ghost},
components::DeltaTime,
movement::{Position, Velocity},
},
};
use bevy_ecs::component::Component;
use bevy_ecs::resource::Resource;
use tracing::{debug, trace, warn};
use crate::systems::GhostAnimations;
use bevy_ecs::query::Without;
use bevy_ecs::system::{Commands, Query, Res};
use rand::seq::IndexedRandom;
use smallvec::SmallVec;
/// Tag component for eaten ghosts
#[derive(Component, Debug, Clone, Copy)]
pub struct Eaten;
/// Tag component for Pac-Man during his death animation.
/// This is mainly because the Frozen tag would stop both movement and animation, while the Dying tag can signal that the animation should continue despite being frozen.
#[derive(Component, Debug, Clone, Copy)]
pub struct Dying;
#[derive(Component, Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Ghost {
Blinky,
Pinky,
Inky,
Clyde,
}
impl Ghost {
/// Returns the ghost type name for atlas lookups.
pub fn as_str(self) -> &'static str {
match self {
Ghost::Blinky => "blinky",
Ghost::Pinky => "pinky",
Ghost::Inky => "inky",
Ghost::Clyde => "clyde",
}
}
/// Returns the base movement speed for this ghost type.
pub fn base_speed(self) -> f32 {
match self {
Ghost::Blinky => 1.0,
Ghost::Pinky => 0.95,
Ghost::Inky => 0.9,
Ghost::Clyde => 0.85,
}
}
/// 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
Ghost::Pinky => sdl2::pixels::Color::RGB(255, 182, 255), // Pink
Ghost::Inky => sdl2::pixels::Color::RGB(0, 255, 255), // Cyan
Ghost::Clyde => sdl2::pixels::Color::RGB(255, 182, 85), // Orange
}
}
}
#[derive(Component, Debug, Clone, Copy)]
pub enum GhostState {
/// Normal ghost behavior - chasing Pac-Man
Normal,
/// Frightened state after power pellet - ghost can be eaten
Frightened {
remaining_ticks: u32,
flash: bool,
remaining_flash_ticks: u32,
},
/// Eyes state - ghost has been eaten and is returning to ghost house
Eyes,
}
impl GhostState {
/// Creates a new frightened state with the specified duration
pub fn new_frightened(total_ticks: u32, flash_start_ticks: u32) -> Self {
Self::Frightened {
remaining_ticks: total_ticks,
flash: false,
remaining_flash_ticks: flash_start_ticks, // Time until flashing starts
}
}
/// Ticks the ghost state, returning true if the state changed.
pub fn tick(&mut self) -> bool {
if let GhostState::Frightened {
remaining_ticks,
flash,
remaining_flash_ticks,
} = self
{
// Transition out of frightened state
if *remaining_ticks == 0 {
*self = GhostState::Normal;
return true;
}
*remaining_ticks -= 1;
if *remaining_flash_ticks > 0 {
*remaining_flash_ticks = remaining_flash_ticks.saturating_sub(1);
if *remaining_flash_ticks == 0 {
*flash = true;
true
} else {
false
}
} else {
false
}
} else {
false
}
}
/// Returns the appropriate animation state for this ghost state
pub fn animation_state(&self) -> GhostAnimation {
match self {
GhostState::Normal => GhostAnimation::Normal,
GhostState::Eyes => GhostAnimation::Eyes,
GhostState::Frightened { flash: false, .. } => GhostAnimation::Frightened { flash: false },
GhostState::Frightened { flash: true, .. } => GhostAnimation::Frightened { flash: true },
}
}
}
/// Enumeration of different ghost animation states.
/// Note that this is used in micromap which has a fixed size based on the number of variants,
/// so extending this should be done with caution, and will require updating the micromap's capacity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum GhostAnimation {
/// Normal ghost appearance with directional movement animations
Normal,
/// Blue ghost appearance when vulnerable (power pellet active)
Frightened { flash: bool },
/// Eyes-only animation when ghost has been consumed by Pac-Man (Eaten state)
Eyes,
}
/// Global resource containing pre-loaded animation sets for all ghost types.
///
/// This resource is initialized once during game startup and provides O(1) access
/// to animation sets for each ghost type. The animation system uses this resource
/// to efficiently switch between different ghost states without runtime asset loading.
///
/// The HashMap is keyed by `Ghost` enum variants (Blinky, Pinky, Inky, Clyde) and
/// contains the normal directional animation for each ghost type.
#[derive(Resource)]
pub struct GhostAnimations {
pub normal: HashMap<Ghost, DirectionalAnimation>,
pub eyes: DirectionalAnimation,
pub frightened: LinearAnimation,
pub frightened_flashing: LinearAnimation,
}
impl GhostAnimations {
/// Creates a new GhostAnimations resource with the provided data.
pub fn new(
normal: HashMap<Ghost, DirectionalAnimation>,
eyes: DirectionalAnimation,
frightened: LinearAnimation,
frightened_flashing: LinearAnimation,
) -> Self {
Self {
normal,
eyes,
frightened,
frightened_flashing,
}
}
/// Gets the normal directional animation for the specified ghost type.
pub fn get_normal(&self, ghost_type: &Ghost) -> Option<&DirectionalAnimation> {
self.normal.get(ghost_type)
}
/// Gets the eyes animation (shared across all ghosts).
pub fn eyes(&self) -> &DirectionalAnimation {
&self.eyes
}
/// Gets the frightened animations (shared across all ghosts).
pub fn frightened(&self, flash: bool) -> &LinearAnimation {
if flash {
&self.frightened_flashing
} else {
&self.frightened
}
}
}
/// Autonomous ghost AI system implementing randomized movement with backtracking avoidance.
pub fn ghost_movement_system(
map: Res<Map>,
@@ -185,6 +368,10 @@ fn find_direction_to_target(
None
}
/// Component to track the last animation state for efficient change detection
#[derive(Component, Debug, Clone, Copy, PartialEq)]
pub struct LastAnimationState(pub GhostAnimation);
/// Unified system that manages ghost state transitions and animations with component swapping
pub fn ghost_state_system(
mut commands: Commands,

View File

@@ -13,7 +13,7 @@ use sdl2::{
};
use smallvec::{smallvec, SmallVec};
use crate::systems::components::DeltaTime;
use crate::systems::DeltaTime;
use crate::{
events::{GameCommand, GameEvent},
map::direction::Direction,

View File

@@ -1,17 +1,65 @@
use bevy_ecs::{
entity::Entity,
event::{EventReader, EventWriter},
event::{Event, EventReader, EventWriter},
observer::Trigger,
query::With,
system::{Commands, Query, ResMut},
system::{Commands, NonSendMut, Query, Res, ResMut, Single},
};
use tracing::{debug, trace};
use crate::{
constants::collider::FRUIT_SIZE,
map::builder::Map,
systems::{common::bundles::ItemBundle, Collider, Position, Renderable},
texture::{sprite::SpriteAtlas, sprites::GameSprite},
};
use crate::{
constants::animation::FRIGHTENED_FLASH_START_TICKS,
events::GameEvent,
systems::{AudioEvent, EntityType, GhostCollider, GhostState, ItemCollider, PacmanCollider, ScoreResource},
systems::common::components::EntityType,
systems::lifetime::TimeToLive,
systems::{AudioEvent, GhostCollider, GhostState, ItemCollider, LinearAnimation, PacmanCollider, ScoreResource},
texture::animated::TileSequence,
};
/// Tracks the number of pellets consumed by the player for fruit spawning mechanics.
#[derive(bevy_ecs::resource::Resource, Debug, Default)]
pub struct PelletCount(pub u32);
/// Maps fruit score values to bonus sprite indices for displaying bonus points
fn fruit_score_to_sprite_index(score: u32) -> u8 {
match score {
100 => 0, // Cherry
300 => 2, // Strawberry
500 => 3, // Orange
700 => 4, // Apple
1000 => 6, // Melon
2000 => 8, // Galaxian
3000 => 9, // Bell
5000 => 10, // Key
_ => 0, // Default to 100 points sprite
}
}
/// Maps sprite index to the corresponding effect sprite path (same as in state.rs)
fn sprite_index_to_path(index: u8) -> &'static str {
match index {
0 => "effects/100.png",
1 => "effects/200.png",
2 => "effects/300.png",
3 => "effects/400.png",
4 => "effects/700.png",
5 => "effects/800.png",
6 => "effects/1000.png",
7 => "effects/1600.png",
8 => "effects/2000.png",
9 => "effects/3000.png",
10 => "effects/5000.png",
_ => "effects/100.png", // fallback to index 0
}
}
/// Determines if a collision between two entity types should be handled by the item system.
///
/// Returns `true` if one entity is a player and the other is a collectible item.
@@ -23,42 +71,83 @@ pub fn is_valid_item_collision(entity1: EntityType, entity2: EntityType) -> bool
}
}
#[allow(clippy::too_many_arguments)]
pub fn item_system(
mut commands: Commands,
mut collision_events: EventReader<GameEvent>,
mut score: ResMut<ScoreResource>,
pacman_query: Query<Entity, With<PacmanCollider>>,
item_query: Query<(Entity, &EntityType), With<ItemCollider>>,
mut pellet_count: ResMut<PelletCount>,
pacman: Single<Entity, With<PacmanCollider>>,
item_query: Query<(Entity, &EntityType, &Position), With<ItemCollider>>,
mut ghost_query: Query<&mut GhostState, With<GhostCollider>>,
mut events: EventWriter<AudioEvent>,
atlas: NonSendMut<SpriteAtlas>,
) {
for event in collision_events.read() {
if let GameEvent::Collision(entity1, entity2) = event {
// Check if one is Pacman and the other is an item
let (_pacman_entity, item_entity) = if pacman_query.get(*entity1).is_ok() && item_query.get(*entity2).is_ok() {
(*entity1, *entity2)
} else if pacman_query.get(*entity2).is_ok() && item_query.get(*entity1).is_ok() {
(*entity2, *entity1)
let (_, item_entity) = if *pacman == *entity1 && item_query.get(*entity2).is_ok() {
(*pacman, *entity2)
} else if *pacman == *entity2 && item_query.get(*entity1).is_ok() {
(*pacman, *entity1)
} else {
continue;
};
// Get the item type and update score
if let Ok((item_ent, entity_type)) = item_query.get(item_entity) {
if let Ok((item_ent, entity_type, item_position)) = item_query.get(item_entity) {
if let Some(score_value) = entity_type.score_value() {
trace!(item_entity = ?item_ent, item_type = ?entity_type, score_value, new_score = score.0 + score_value, "Item collected by player");
score.0 += score_value;
// Spawn bonus sprite for fruits at the fruit's position (similar to ghost eating bonus)
if matches!(entity_type, EntityType::Fruit(_)) {
let sprite_index = fruit_score_to_sprite_index(score_value);
let sprite_path = sprite_index_to_path(sprite_index);
if let Ok(sprite_tile) = SpriteAtlas::get_tile(&atlas, sprite_path) {
let tile_sequence = TileSequence::single(sprite_tile);
let animation = LinearAnimation::new(tile_sequence, 1);
commands.spawn((
*item_position,
Renderable {
sprite: sprite_tile,
layer: 2, // Above other entities
},
animation,
TimeToLive::new(120), // 2 seconds at 60 FPS
));
debug!(
fruit_score = score_value,
sprite_index, "Fruit bonus sprite spawned at fruit position"
);
}
}
// Remove the collected item
commands.entity(item_ent).despawn();
// Track pellet consumption for fruit spawning
if *entity_type == EntityType::Pellet {
pellet_count.0 += 1;
trace!(pellet_count = pellet_count.0, "Pellet consumed");
// Check if we should spawn a fruit
if pellet_count.0 == 70 || pellet_count.0 == 170 {
debug!(pellet_count = pellet_count.0, "Fruit spawn milestone reached");
commands.trigger(SpawnFruitTrigger);
}
}
// Trigger audio if appropriate
if entity_type.is_collectible() {
events.write(AudioEvent::PlayEat);
}
// Make ghosts frightened when power pellet is collected
if *entity_type == EntityType::PowerPellet {
if matches!(*entity_type, EntityType::PowerPellet) {
// Convert seconds to frames (assumes 60 FPS)
let total_ticks = 60 * 5; // 5 seconds total
debug!(duration_ticks = total_ticks, "Power pellet collected, frightening ghosts");
@@ -78,3 +167,32 @@ pub fn item_system(
}
}
}
/// Trigger to spawn a fruit
#[derive(Event, Clone, Copy, Debug, PartialEq, Eq)]
pub struct SpawnFruitTrigger;
pub fn spawn_fruit_observer(
_: Trigger<SpawnFruitTrigger>,
mut commands: Commands,
atlas: NonSendMut<SpriteAtlas>,
map: Res<Map>,
) {
// Use cherry sprite as the default fruit (first fruit in original Pac-Man)
let fruit_sprite = &atlas
.get_tile(&GameSprite::Fruit(crate::texture::sprites::FruitSprite::Cherry).to_path())
.unwrap();
let fruit_entity = commands.spawn(ItemBundle {
position: map.start_positions.fruit_spawn,
sprite: Renderable {
sprite: *fruit_sprite,
layer: 1,
},
entity_type: EntityType::Fruit(crate::texture::sprites::FruitSprite::Cherry),
collider: Collider { size: FRUIT_SIZE },
item_collider: ItemCollider,
});
debug!(fruit_entity = ?fruit_entity.id(), fruit_spawn_node = ?map.start_positions.fruit_spawn, "Fruit spawned");
}

View File

@@ -4,7 +4,7 @@ use bevy_ecs::{
system::{Commands, Query, Res},
};
use crate::systems::components::DeltaTime;
use crate::systems::DeltaTime;
/// Component for entities that should be automatically deleted after a certain number of ticks
#[derive(Component, Debug, Clone, Copy)]

View File

@@ -9,9 +9,10 @@ pub mod profiling;
#[cfg_attr(coverage_nightly, coverage(off))]
pub mod render;
pub mod animation;
pub mod blinking;
pub mod collision;
pub mod components;
pub mod common;
pub mod ghost;
pub mod input;
pub mod item;
@@ -22,10 +23,11 @@ pub mod state;
// Re-export all the modules. Do not fine-tune the exports.
pub use self::animation::*;
pub use self::audio::*;
pub use self::blinking::*;
pub use self::collision::*;
pub use self::components::*;
pub use self::common::*;
pub use self::debug::*;
pub use self::ghost::*;
pub use self::input::*;

View File

@@ -1,22 +1,26 @@
use bevy_ecs::{
event::{EventReader, EventWriter},
component::Component,
event::EventReader,
query::{With, Without},
system::{Query, Res, ResMut},
system::{Query, Res, ResMut, Single},
};
use tracing::trace;
use crate::{
error::GameError,
events::{GameCommand, GameEvent},
map::{builder::Map, graph::Edge},
systems::{
components::{DeltaTime, EntityType, Frozen, GlobalState, MovementModifiers, PlayerControlled},
components::{DeltaTime, EntityType, Frozen, GlobalState, MovementModifiers},
debug::DebugState,
movement::{BufferedDirection, Position, Velocity},
AudioState,
},
};
/// A tag component for entities that are controlled by the player.
#[derive(Default, Component)]
pub struct PlayerControlled;
pub fn can_traverse(entity_type: EntityType, edge: Edge) -> bool {
let entity_flags = entity_type.traversal_flags();
edge.traversal_flags.contains(entity_flags)
@@ -28,36 +32,27 @@ pub fn can_traverse(entity_type: EntityType, edge: Edge) -> bool {
/// 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.
#[allow(clippy::type_complexity)]
pub fn player_control_system(
mut events: EventReader<GameEvent>,
mut state: ResMut<GlobalState>,
mut debug_state: ResMut<DebugState>,
mut audio_state: ResMut<AudioState>,
mut players: Query<&mut BufferedDirection, (With<PlayerControlled>, Without<Frozen>)>,
mut errors: EventWriter<GameError>,
mut player: Option<Single<&mut BufferedDirection, (With<PlayerControlled>, Without<Frozen>)>>,
) {
// Handle events
for event in events.read() {
if let GameEvent::Command(command) = event {
match command {
GameCommand::MovePlayer(direction) => {
// Get the player's movable component (ensuring there is only one player)
let mut buffered_direction = match players.single_mut() {
Ok(tuple) => tuple,
Err(e) => {
errors.write(GameError::InvalidState(format!(
"No/multiple entities queried for player system: {}",
e
)));
return;
}
};
trace!(direction = ?*direction, "Player direction buffered for movement");
*buffered_direction = BufferedDirection::Some {
direction: *direction,
remaining_time: 0.25,
};
// Only handle movement if there's an unfrozen player
if let Some(player_single) = player.as_mut() {
trace!(direction = ?*direction, "Player direction buffered for movement");
***player_single = BufferedDirection::Some {
direction: *direction,
remaining_time: 0.25,
};
}
}
GameCommand::Exit => {
state.exit = true;
@@ -168,24 +163,23 @@ pub fn player_movement_system(
}
/// Applies tunnel slowdown based on the current node tile
pub fn player_tunnel_slowdown_system(map: Res<Map>, mut q: Query<(&Position, &mut MovementModifiers), With<PlayerControlled>>) {
if let Ok((position, mut modifiers)) = q.single_mut() {
let node = position.current_node();
let in_tunnel = map
.tile_at_node(node)
.map(|t| t == crate::constants::MapTile::Tunnel)
.unwrap_or(false);
pub fn player_tunnel_slowdown_system(map: Res<Map>, player: Single<(&Position, &mut MovementModifiers), With<PlayerControlled>>) {
let (position, mut modifiers) = player.into_inner();
let node = position.current_node();
let in_tunnel = map
.tile_at_node(node)
.map(|t| t == crate::constants::MapTile::Tunnel)
.unwrap_or(false);
if modifiers.tunnel_slowdown_active != in_tunnel {
trace!(
node,
in_tunnel,
speed_multiplier = if in_tunnel { 0.6 } else { 1.0 },
"Player tunnel slowdown state changed"
);
}
modifiers.tunnel_slowdown_active = in_tunnel;
modifiers.speed_multiplier = if in_tunnel { 0.6 } else { 1.0 };
if modifiers.tunnel_slowdown_active != in_tunnel {
trace!(
node,
in_tunnel,
speed_multiplier = if in_tunnel { 0.6 } else { 1.0 },
"Player tunnel slowdown state changed"
);
}
modifiers.tunnel_slowdown_active = in_tunnel;
modifiers.speed_multiplier = if in_tunnel { 0.6 } else { 1.0 };
}

View File

@@ -52,6 +52,11 @@ impl TimingBuffer {
self.last_tick = current_tick;
}
/// Gets the most recent timing from the buffer.
pub fn get_most_recent_timing(&self) -> Duration {
self.buffer.back().copied().unwrap_or(Duration::ZERO)
}
/// Gets statistics for this timing buffer.
///
/// # Panics
@@ -248,6 +253,61 @@ impl SystemTimings {
// Use the formatting module to format the data
format_timing_display(timing_data)
}
/// Returns a list of systems with their timings, likely responsible for slow frame timings.
///
/// First, checks if any systems took longer than 2ms on the most recent tick.
/// If none exceed 2ms, accumulates systems until the top 30% of total timing
/// is reached, stopping at 5 systems maximum.
///
/// Returns tuples of (SystemId, Duration) in a SmallVec capped at 5 items.
pub fn get_slowest_systems(&self) -> SmallVec<[(SystemId, Duration); 5]> {
let mut system_timings: Vec<(SystemId, Duration)> = Vec::new();
let mut total_duration = Duration::ZERO;
// Collect most recent timing for each system (excluding Total)
for id in SystemId::iter() {
if id == SystemId::Total {
continue;
}
if let Some(buffer) = self.timings.get(&id) {
let recent_timing = buffer.lock().get_most_recent_timing();
system_timings.push((id, recent_timing));
total_duration += recent_timing;
}
}
// Sort by duration (highest first)
system_timings.sort_by(|a, b| b.1.cmp(&a.1));
// Check for systems over 2ms threshold
let over_threshold: SmallVec<[(SystemId, Duration); 5]> = system_timings
.iter()
.filter(|(_, duration)| duration.as_millis() >= 2)
.copied()
.collect();
if !over_threshold.is_empty() {
return over_threshold;
}
// Accumulate top systems until 30% of total is reached (max 5 systems)
let threshold = total_duration.as_nanos() as f64 * 0.3;
let mut accumulated = 0u128;
let mut result = SmallVec::new();
for (id, duration) in system_timings.iter().take(5) {
result.push((*id, *duration));
accumulated += duration.as_nanos();
if accumulated as f64 >= threshold {
break;
}
}
result
}
}
pub fn profile<S, M>(id: SystemId, system: S) -> impl FnMut(&mut bevy_ecs::world::World)

View File

@@ -1,12 +1,10 @@
use crate::map::builder::Map;
use crate::map::direction::Direction;
use crate::systems::input::TouchState;
use crate::systems::{
debug_render_system, BatchedLinesResource, Collider, CursorPosition, DebugState, DebugTextureResource, DeltaTime,
DirectionalAnimation, Dying, Frozen, GameStage, LinearAnimation, Looping, PlayerLives, Position, Renderable, ScoreResource,
StartupSequence, SystemId, SystemTimings, TtfAtlasResource, Velocity,
debug_render_system, BatchedLinesResource, Collider, CursorPosition, DebugState, DebugTextureResource, GameStage, PlayerLife,
PlayerLives, Position, ScoreResource, StartupSequence, SystemId, SystemTimings, TouchState, TtfAtlasResource,
};
use crate::texture::sprite::SpriteAtlas;
use crate::texture::sprite::{AtlasTile, SpriteAtlas};
use crate::texture::sprites::{GameSprite, PacmanSprite};
use crate::texture::text::TextTexture;
use crate::{
@@ -16,16 +14,27 @@ use crate::{
use bevy_ecs::component::Component;
use bevy_ecs::entity::Entity;
use bevy_ecs::event::EventWriter;
use bevy_ecs::query::{Changed, Has, Or, With, Without};
use bevy_ecs::query::{Changed, Or, With, Without};
use bevy_ecs::removal_detection::RemovedComponents;
use bevy_ecs::resource::Resource;
use bevy_ecs::system::{NonSendMut, Query, Res, ResMut};
use bevy_ecs::system::{Commands, NonSendMut, Query, Res, ResMut};
use glam::Vec2;
use sdl2::pixels::Color;
use sdl2::rect::{Point, Rect};
use sdl2::render::{BlendMode, Canvas, Texture};
use sdl2::video::Window;
use std::cmp::Ordering;
use std::time::Instant;
/// A component for entities that have a sprite, with a layer for ordering.
///
/// This is intended to be modified by other entities allowing animation.
#[derive(Component)]
pub struct Renderable {
pub sprite: AtlasTile,
pub layer: u8,
}
#[derive(Resource, Default)]
pub struct RenderDirty(pub bool);
@@ -55,75 +64,87 @@ pub fn dirty_render_system(
}
}
/// Updates directional animated entities with synchronized timing across directions.
///
/// This runs before the render system to update sprites based on current direction and movement state.
/// All directions share the same frame timing to ensure perfect synchronization.
pub fn directional_render_system(
dt: Res<DeltaTime>,
mut query: Query<(&Position, &Velocity, &mut DirectionalAnimation, &mut Renderable), Without<Frozen>>,
/// System that manages player life sprite entities.
/// Spawns and despawns life sprite entities based on changes to PlayerLives resource.
/// Each life sprite is positioned based on its index (0, 1, 2, etc. from left to right).
pub fn player_life_sprite_system(
mut commands: Commands,
atlas: NonSendMut<SpriteAtlas>,
current_life_sprites: Query<(Entity, &PlayerLife)>,
player_lives: Res<PlayerLives>,
mut errors: EventWriter<GameError>,
) {
let ticks = (dt.seconds * 60.0).round() as u16; // Convert from seconds to ticks at 60 ticks/sec
let displayed_lives = player_lives.0.saturating_sub(1);
for (position, velocity, mut anim, mut renderable) in query.iter_mut() {
let stopped = matches!(position, Position::Stopped { .. });
// Get current life sprite entities, sorted by index
let mut current_sprites: Vec<_> = current_life_sprites.iter().collect();
current_sprites.sort_by_key(|(_, life)| life.index);
let current_count = current_sprites.len() as u8;
// Only tick animation when moving to preserve stopped frame
if !stopped {
// Tick shared animation state
anim.time_bank += ticks;
while anim.time_bank >= anim.frame_duration {
anim.time_bank -= anim.frame_duration;
anim.current_frame += 1;
// Calculate the difference
let diff = (displayed_lives as i8) - (current_count as i8);
match diff.cmp(&0) {
// Ignore when the number of lives displayed is correct
Ordering::Equal => {}
// Spawn new life sprites
Ordering::Greater => {
let life_sprite = match atlas.get_tile(&GameSprite::Pacman(PacmanSprite::Moving(Direction::Left, 1)).to_path()) {
Ok(sprite) => sprite,
Err(e) => {
errors.write(e.into());
return;
}
};
for i in 0..diff {
let position = calculate_life_sprite_position(i as u32);
commands.spawn((
PlayerLife { index: i as u32 },
Renderable {
sprite: life_sprite,
layer: 255, // High layer to render on top
},
PixelPosition {
pixel_position: position,
},
));
}
}
// Remove excess life sprites (highest indices first)
Ordering::Less => {
let to_remove = diff.unsigned_abs();
let sprites_to_remove: Vec<_> = current_sprites
.iter()
.rev() // Start from highest index
.take(to_remove as usize)
.map(|(entity, _)| *entity)
.collect();
// Get tiles for current direction and movement state
let tiles = if stopped {
anim.stopped_tiles.get(velocity.direction)
} else {
anim.moving_tiles.get(velocity.direction)
};
if !tiles.is_empty() {
let new_tile = tiles.get_tile(anim.current_frame);
if renderable.sprite != new_tile {
renderable.sprite = new_tile;
for entity in sprites_to_remove {
commands.entity(entity).despawn();
}
}
}
}
/// System that updates `Renderable` sprites for entities with `LinearAnimation`.
#[allow(clippy::type_complexity)]
pub fn linear_render_system(
dt: Res<DeltaTime>,
mut query: Query<(&mut LinearAnimation, &mut Renderable, Has<Looping>), Or<(Without<Frozen>, With<Dying>)>>,
) {
for (mut anim, mut renderable, looping) in query.iter_mut() {
if anim.finished {
continue;
}
/// Component for Renderables to store an exact pixel position
#[derive(Component)]
pub struct PixelPosition {
pub pixel_position: Vec2,
}
anim.time_bank += dt.ticks as u16;
let frames_to_advance = (anim.time_bank / anim.frame_duration) as usize;
/// Calculates the pixel position for a life sprite based on its index
fn calculate_life_sprite_position(index: u32) -> Vec2 {
let start_x = CELL_SIZE * 2; // 2 cells from left
let start_y = CANVAS_SIZE.y - BOARD_BOTTOM_PIXEL_OFFSET.y + (CELL_SIZE / 2) + 1; // In bottom area
let sprite_spacing = CELL_SIZE + CELL_SIZE / 2; // 1.5 cells between sprites
if frames_to_advance == 0 {
continue;
}
let x = start_x + ((index as f32) * (sprite_spacing as f32 * 1.5)).round() as u32;
let y = start_y - CELL_SIZE / 2;
let total_frames = anim.tiles.len();
if !looping && anim.current_frame + frames_to_advance >= total_frames {
anim.finished = true;
anim.current_frame = total_frames - 1;
} else {
anim.current_frame += frames_to_advance;
}
anim.time_bank %= anim.frame_duration;
renderable.sprite = anim.tiles.get_tile(anim.current_frame);
}
Vec2::new((x + CELL_SIZE) as f32, (y + CELL_SIZE) as f32)
}
/// A non-send resource for the map texture. This just wraps the texture with a type so it can be differentiated when exposed as a resource.
@@ -211,7 +232,6 @@ pub fn hud_render_system(
mut backbuffer: NonSendMut<BackbufferResource>,
mut canvas: NonSendMut<&mut Canvas<Window>>,
mut atlas: NonSendMut<SpriteAtlas>,
player_lives: Res<PlayerLives>,
score: Res<ScoreResource>,
stage: Res<GameStage>,
mut errors: EventWriter<GameError>,
@@ -227,35 +247,6 @@ pub fn hud_render_system(
errors.write(TextureError::RenderFailed(format!("Failed to render lives text: {}", e)).into());
}
// Render Pac-Man life sprites in bottom left
let lives = player_lives.0;
let life_sprite_path = &GameSprite::Pacman(PacmanSprite::Moving(Direction::Left, 1)).to_path();
// Get the sprite from the atlas for life display
match atlas.get_tile(life_sprite_path) {
Ok(life_sprite) => {
let start_x = CELL_SIZE * 2; // 2 cells from left
let start_y = CANVAS_SIZE.y - BOARD_BOTTOM_PIXEL_OFFSET.y + (CELL_SIZE / 2) + 1; // In bottom area
let sprite_spacing = CELL_SIZE + CELL_SIZE / 2; // 1.5 cells between sprites
// Render one sprite for each remaining life (lives - 1, since current life isn't shown)
let sprites_to_show = if lives > 0 { lives - 1 } else { 0 };
for i in 0..sprites_to_show {
let x = start_x + ((i as f32) * (sprite_spacing as f32 * 1.5)).round() as u32;
let y = start_y - CELL_SIZE / 2;
let dest = sdl2::rect::Rect::new(x as i32, y as i32, life_sprite.size.x as u32, life_sprite.size.y as u32);
if let Err(e) = life_sprite.render(canvas, &mut atlas, dest) {
errors.write(TextureError::RenderFailed(format!("Failed to render life sprite: {}", e)).into());
}
}
}
Err(e) => {
errors.write(e.into());
}
}
// Render score text
let score_text = format!("{:02}", score.0);
let score_offset = 7 - (score_text.len() as i32);
@@ -312,13 +303,17 @@ pub fn hud_render_system(
}
#[allow(clippy::too_many_arguments)]
#[allow(clippy::type_complexity)]
pub fn render_system(
canvas: &mut Canvas<Window>,
map_texture: &NonSendMut<MapTextureResource>,
atlas: &mut SpriteAtlas,
map: &Res<Map>,
dirty: &Res<RenderDirty>,
renderables: &Query<(Entity, &Renderable, &Position), Without<Hidden>>,
renderables: &Query<
(Entity, &Renderable, Option<&Position>, Option<&PixelPosition>),
(Without<Hidden>, Or<(With<Position>, With<PixelPosition>)>),
>,
errors: &mut EventWriter<GameError>,
) {
if !dirty.0 {
@@ -335,12 +330,21 @@ pub fn render_system(
}
// Render all entities to the backbuffer
for (_, renderable, position) in renderables
for (_entity, renderable, position, pixel_position) in renderables
.iter()
.sort_by_key::<(Entity, &Renderable, &Position), _>(|(_, renderable, _)| renderable.layer)
.sort_by_key::<(Entity, &Renderable, Option<&Position>, Option<&PixelPosition>), _>(|(_, renderable, _, _)| {
renderable.layer
})
.rev()
{
let pos = position.get_pixel_position(&map.graph);
let pos = if let Some(position) = position {
position.get_pixel_position(&map.graph)
} else {
Ok(pixel_position
.expect("Pixel position should be present via query filtering, but got None on both")
.pixel_position)
};
match pos {
Ok(pos) => {
let dest = Rect::from_center(
@@ -365,6 +369,7 @@ pub fn render_system(
/// Combined render system that renders to both backbuffer and debug textures in a single
/// with_multiple_texture_canvas call for reduced overhead
#[allow(clippy::too_many_arguments)]
#[allow(clippy::type_complexity)]
pub fn combined_render_system(
mut canvas: NonSendMut<&mut Canvas<Window>>,
map_texture: NonSendMut<MapTextureResource>,
@@ -378,7 +383,10 @@ pub fn combined_render_system(
timing: Res<crate::systems::profiling::Timing>,
map: Res<Map>,
dirty: Res<RenderDirty>,
renderables: Query<(Entity, &Renderable, &Position), Without<Hidden>>,
renderables: Query<
(Entity, &Renderable, Option<&Position>, Option<&PixelPosition>),
(Without<Hidden>, Or<(With<Position>, With<PixelPosition>)>),
>,
colliders: Query<(&Collider, &Position)>,
cursor: Res<CursorPosition>,
mut errors: EventWriter<GameError>,

View File

@@ -15,7 +15,7 @@ use bevy_ecs::{
event::{EventReader, EventWriter},
query::{With, Without},
resource::Resource,
system::{Commands, NonSendMut, Query, Res, ResMut},
system::{Commands, NonSendMut, Query, Res, ResMut, Single},
};
#[derive(Resource, Clone)]
@@ -122,7 +122,7 @@ pub fn stage_system(
mut audio_events: EventWriter<AudioEvent>,
mut stage_event_reader: EventReader<StageTransition>,
mut blinking_query: Query<Entity, With<Blinking>>,
mut player_query: Query<(Entity, &mut Position), With<PlayerControlled>>,
player: Single<(Entity, &mut Position), With<PlayerControlled>>,
mut ghost_query: Query<(Entity, &Ghost, &mut Position), (With<GhostCollider>, Without<PlayerControlled>)>,
atlas: NonSendMut<SpriteAtlas>,
) {
@@ -132,11 +132,7 @@ pub fn stage_system(
// Handle stage transition requests before normal ticking
for event in stage_event_reader.read() {
let StageTransition::GhostEatenPause { ghost_entity } = *event;
let pac_node = player_query
.single_mut()
.ok()
.map(|(_, pos)| pos.current_node())
.unwrap_or(map.start_positions.pacman);
let pac_node = player.1.current_node();
debug!(ghost_entity = ?ghost_entity, node = pac_node, "Ghost eaten, entering pause state");
new_state = Some(GameStage::GhostEatenPause {
@@ -240,18 +236,13 @@ pub fn stage_system(
match (old_state, new_state) {
(GameStage::Playing, GameStage::GhostEatenPause { ghost_entity, node, .. }) => {
// Freeze the player & ghosts
for entity in player_query
.iter_mut()
.map(|(e, _)| e)
.chain(ghost_query.iter_mut().map(|(e, _, _)| e))
{
commands.entity(player.0).insert(Frozen);
for (entity, _, _) in ghost_query.iter_mut() {
commands.entity(entity).insert(Frozen);
}
// Hide the player & eaten ghost
for (player_entity, _) in player_query.iter_mut() {
commands.entity(player_entity).insert(Hidden);
}
commands.entity(player.0).insert(Hidden);
commands.entity(ghost_entity).insert(Hidden);
// Spawn bonus points entity at Pac-Man's position
@@ -275,11 +266,8 @@ pub fn stage_system(
}
(GameStage::GhostEatenPause { ghost_entity, .. }, GameStage::Playing) => {
// Unfreeze and reveal the player & all ghosts
for entity in player_query
.iter_mut()
.map(|(e, _)| e)
.chain(ghost_query.iter_mut().map(|(e, _, _)| e))
{
commands.entity(player.0).remove::<(Frozen, Hidden)>();
for (entity, _, _) in ghost_query.iter_mut() {
commands.entity(entity).remove::<(Frozen, Hidden)>();
}
@@ -288,11 +276,8 @@ pub fn stage_system(
}
(GameStage::Playing, GameStage::PlayerDying(DyingSequence::Frozen { .. })) => {
// Freeze the player & ghosts
for entity in player_query
.iter_mut()
.map(|(e, _)| e)
.chain(ghost_query.iter_mut().map(|(e, _, _)| e))
{
commands.entity(player.0).insert(Frozen);
for (entity, _, _) in ghost_query.iter_mut() {
commands.entity(entity).insert(Frozen);
}
}
@@ -303,39 +288,32 @@ pub fn stage_system(
}
// Start Pac-Man's death animation
if let Ok((player_entity, _)) = player_query.single_mut() {
commands
.entity(player_entity)
.insert((Dying, player_death_animation.0.clone()));
}
commands.entity(player.0).insert((Dying, player_death_animation.0.clone()));
// Play the death sound
audio_events.write(AudioEvent::PlayDeath);
}
(GameStage::PlayerDying(DyingSequence::Animating { .. }), GameStage::PlayerDying(DyingSequence::Hidden { .. })) => {
// Hide the player
if let Ok((player_entity, _)) = player_query.single_mut() {
commands.entity(player_entity).insert(Hidden);
}
commands.entity(player.0).insert(Hidden);
}
(_, GameStage::LevelRestarting) => {
if let Ok((player_entity, mut pos)) = player_query.single_mut() {
*pos = Position::Stopped {
node: map.start_positions.pacman,
};
let (player_entity, mut pos) = player.into_inner();
*pos = Position::Stopped {
node: map.start_positions.pacman,
};
// Freeze the blinking, force them to be visible (if they were hidden by blinking)
for entity in blinking_query.iter_mut() {
commands.entity(entity).insert(Frozen).remove::<Hidden>();
}
// Reset the player animation
commands
.entity(player_entity)
.remove::<(Frozen, Dying, LinearAnimation, Looping)>()
.insert(player_animation.0.clone());
// Freeze the blinking, force them to be visible (if they were hidden by blinking)
for entity in blinking_query.iter_mut() {
commands.entity(entity).insert(Frozen).remove::<Hidden>();
}
// Reset the player animation
commands
.entity(player_entity)
.remove::<(Frozen, Dying, LinearAnimation, Looping)>()
.insert(player_animation.0.clone());
// Reset ghost positions and state
for (ghost_entity, ghost, mut ghost_pos) in ghost_query.iter_mut() {
*ghost_pos = Position::Stopped {
@@ -354,22 +332,18 @@ pub fn stage_system(
}
(_, GameStage::Starting(StartupSequence::CharactersVisible { .. })) => {
// Unhide the player & ghosts
for entity in player_query
.iter_mut()
.map(|(e, _)| e)
.chain(ghost_query.iter_mut().map(|(e, _, _)| e))
{
commands.entity(player.0).remove::<Hidden>();
for (entity, _, _) in ghost_query.iter_mut() {
commands.entity(entity).remove::<Hidden>();
}
}
(GameStage::Starting(StartupSequence::CharactersVisible { .. }), GameStage::Playing) => {
// Unfreeze the player & ghosts & blinking
for entity in player_query
.iter_mut()
.map(|(e, _)| e)
.chain(ghost_query.iter_mut().map(|(e, _, _)| e))
.chain(blinking_query.iter_mut())
{
commands.entity(player.0).remove::<Frozen>();
for (entity, _, _) in ghost_query.iter_mut() {
commands.entity(entity).remove::<Frozen>();
}
for entity in blinking_query.iter_mut() {
commands.entity(entity).remove::<Frozen>();
}
}

View File

@@ -5,8 +5,7 @@
//! The `GameSprite` enum is the main entry point, and its `to_path` method
//! generates the correct path for a given sprite in the texture atlas.
use crate::map::direction::Direction;
use crate::systems::components::Ghost;
use crate::{map::direction::Direction, systems::Ghost};
/// Represents the different sprites for Pac-Man.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
@@ -48,12 +47,43 @@ pub enum MazeSprite {
Energizer,
}
/// Represents the different fruit sprites that can appear as bonus items.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[allow(dead_code)]
pub enum FruitSprite {
Cherry,
Strawberry,
Orange,
Apple,
Melon,
Galaxian,
Bell,
Key,
}
impl FruitSprite {
/// Returns the score value for this fruit type.
pub fn score_value(self) -> u32 {
match self {
FruitSprite::Cherry => 100,
FruitSprite::Strawberry => 300,
FruitSprite::Orange => 500,
FruitSprite::Apple => 700,
FruitSprite::Melon => 1000,
FruitSprite::Galaxian => 2000,
FruitSprite::Bell => 3000,
FruitSprite::Key => 5000,
}
}
}
/// A top-level enum that encompasses all game sprites.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum GameSprite {
Pacman(PacmanSprite),
Ghost(GhostSprite),
Maze(MazeSprite),
Fruit(FruitSprite),
}
impl GameSprite {
@@ -106,6 +136,16 @@ impl GameSprite {
GameSprite::Maze(MazeSprite::Tile(index)) => format!("maze/tiles/{}.png", index),
GameSprite::Maze(MazeSprite::Pellet) => "maze/pellet.png".to_string(),
GameSprite::Maze(MazeSprite::Energizer) => "maze/energizer.png".to_string(),
// Fruit sprites
GameSprite::Fruit(FruitSprite::Cherry) => "edible/cherry.png".to_string(),
GameSprite::Fruit(FruitSprite::Strawberry) => "edible/strawberry.png".to_string(),
GameSprite::Fruit(FruitSprite::Orange) => "edible/orange.png".to_string(),
GameSprite::Fruit(FruitSprite::Apple) => "edible/apple.png".to_string(),
GameSprite::Fruit(FruitSprite::Melon) => "edible/melon.png".to_string(),
GameSprite::Fruit(FruitSprite::Galaxian) => "edible/galaxian.png".to_string(),
GameSprite::Fruit(FruitSprite::Bell) => "edible/bell.png".to_string(),
GameSprite::Fruit(FruitSprite::Key) => "edible/key.png".to_string(),
}
}
}

View File

@@ -1,9 +1,5 @@
use bevy_ecs::{entity::Entity, system::RunSystemOnce, world::World};
use pacman::systems::{
blinking::{blinking_system, Blinking},
components::{DeltaTime, Renderable},
Frozen, Hidden,
};
use pacman::systems::{blinking_system, Blinking, DeltaTime, Frozen, Hidden, Renderable};
use speculoos::prelude::*;
mod common;

View File

@@ -214,11 +214,9 @@ fn test_player_control_system_no_player_entity() {
// Run the system - should write an error
world
.run_system_once(player_control_system)
.expect("System should run successfully");
.expect("System should run successfully even with no player entity");
// Check that an error was written (we can't easily check Events without manual management,
// so for this test we just verify the system ran without panicking)
// In a real implementation, you might expose error checking through the ECS world
// The system should run successfully and simply ignore movement commands when there's no player
}
#[test]

View File

@@ -2,7 +2,7 @@
use pacman::{
game::ATLAS_FRAMES,
map::direction::Direction,
systems::components::Ghost,
systems::Ghost,
texture::sprites::{FrightenedColor, GameSprite, GhostSprite, MazeSprite, PacmanSprite},
};