mirror of
https://github.com/Xevion/Pac-Man.git
synced 2025-12-07 16:07:54 -06:00
Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5bdf11dfb6 | ||
|
|
c163171304 | ||
|
|
63e1059df8 |
2
Cargo.lock
generated
2
Cargo.lock
generated
@@ -663,7 +663,7 @@ checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pacman"
|
name = "pacman"
|
||||||
version = "0.78.1"
|
version = "0.78.3"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"bevy_ecs",
|
"bevy_ecs",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "pacman"
|
name = "pacman"
|
||||||
version = "0.78.1"
|
version = "0.78.3"
|
||||||
authors = ["Xevion"]
|
authors = ["Xevion"]
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
rust-version = "1.86.0"
|
rust-version = "1.86.0"
|
||||||
|
|||||||
43
src/game.rs
43
src/game.rs
@@ -13,13 +13,13 @@ use crate::map::direction::Direction;
|
|||||||
use crate::systems::{
|
use crate::systems::{
|
||||||
self, audio_system, blinking_system, collision_system, combined_render_system, directional_render_system,
|
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,
|
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,
|
hud_render_system, item_system, linear_render_system, player_life_sprite_system, present_system, profile,
|
||||||
AudioEvent, AudioResource, AudioState, BackbufferResource, Blinking, BufferedDirection, Collider, DebugState,
|
time_to_live_system, touch_ui_render_system, AudioEvent, AudioResource, AudioState, BackbufferResource, Blinking,
|
||||||
DebugTextureResource, DeltaTime, DirectionalAnimation, EntityType, Frozen, GameStage, Ghost, GhostAnimation, GhostAnimations,
|
BufferedDirection, Collider, DebugState, DebugTextureResource, DeltaTime, DirectionalAnimation, EntityType, Frozen,
|
||||||
GhostBundle, GhostCollider, GhostState, GlobalState, Hidden, ItemBundle, ItemCollider, LastAnimationState, LinearAnimation,
|
GameStage, Ghost, GhostAnimation, GhostAnimations, GhostBundle, GhostCollider, GhostState, GlobalState, Hidden, ItemBundle,
|
||||||
MapTextureResource, MovementModifiers, NodeId, PacmanCollider, PlayerAnimation, PlayerBundle, PlayerControlled,
|
ItemCollider, LastAnimationState, LinearAnimation, MapTextureResource, MovementModifiers, NodeId, PacmanCollider,
|
||||||
PlayerDeathAnimation, PlayerLives, Position, RenderDirty, Renderable, ScoreResource, StartupSequence, SystemId,
|
PlayerAnimation, PlayerBundle, PlayerControlled, PlayerDeathAnimation, PlayerLives, Position, RenderDirty, Renderable,
|
||||||
SystemTimings, Timing, TouchState, Velocity,
|
ScoreResource, StartupSequence, SystemId, SystemTimings, Timing, TouchState, Velocity,
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::texture::animated::{DirectionalTiles, TileSequence};
|
use crate::texture::animated::{DirectionalTiles, TileSequence};
|
||||||
@@ -449,10 +449,9 @@ impl Game {
|
|||||||
let linear_render_system = profile(SystemId::LinearRender, linear_render_system);
|
let linear_render_system = profile(SystemId::LinearRender, linear_render_system);
|
||||||
let dirty_render_system = profile(SystemId::DirtyRender, dirty_render_system);
|
let dirty_render_system = profile(SystemId::DirtyRender, dirty_render_system);
|
||||||
let hud_render_system = profile(SystemId::HudRender, hud_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 present_system = profile(SystemId::Present, present_system);
|
||||||
let unified_ghost_state_system = profile(SystemId::GhostStateAnimation, ghost_state_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 eaten_ghost_system = profile(SystemId::EatenGhost, eaten_ghost_system);
|
||||||
let time_to_live_system = profile(SystemId::TimeToLive, time_to_live_system);
|
let time_to_live_system = profile(SystemId::TimeToLive, time_to_live_system);
|
||||||
|
|
||||||
@@ -460,10 +459,8 @@ impl Game {
|
|||||||
dirty.0 = true;
|
dirty.0 = true;
|
||||||
};
|
};
|
||||||
|
|
||||||
schedule.add_systems(
|
schedule.add_systems((forced_dirty_system
|
||||||
forced_dirty_system
|
.run_if(|score: Res<ScoreResource>, stage: Res<GameStage>| score.is_changed() || stage.is_changed()),));
|
||||||
.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
|
// Input system should always run to prevent SDL event pump from blocking
|
||||||
let input_systems = (
|
let input_systems = (
|
||||||
@@ -496,6 +493,7 @@ impl Game {
|
|||||||
dirty_render_system,
|
dirty_render_system,
|
||||||
combined_render_system,
|
combined_render_system,
|
||||||
hud_render_system,
|
hud_render_system,
|
||||||
|
player_life_sprite_system,
|
||||||
touch_ui_render_system,
|
touch_ui_render_system,
|
||||||
present_system,
|
present_system,
|
||||||
)
|
)
|
||||||
@@ -716,12 +714,23 @@ impl Game {
|
|||||||
timings.add_total_timing(total_duration, new_tick);
|
timings.add_total_timing(total_duration, new_tick);
|
||||||
|
|
||||||
// Log performance warnings for slow frames
|
// Log performance warnings for slow frames
|
||||||
if total_duration.as_millis() > 20 {
|
if total_duration.as_millis() > 17 {
|
||||||
// Warn if frame takes more than 20ms
|
// 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!(
|
warn!(
|
||||||
duration_ms = total_duration.as_millis(),
|
total = format!("{:.3?}", total_duration),
|
||||||
frame_dt = ?std::time::Duration::from_secs_f32(dt),
|
|
||||||
tick = new_tick,
|
tick = new_tick,
|
||||||
|
systems = systems_context,
|
||||||
"Frame took longer than expected"
|
"Frame took longer than expected"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ use bevy_ecs::{
|
|||||||
entity::Entity,
|
entity::Entity,
|
||||||
event::{EventReader, EventWriter},
|
event::{EventReader, EventWriter},
|
||||||
query::With,
|
query::With,
|
||||||
system::{Commands, Query, Res, ResMut},
|
system::{Commands, Query, Res, ResMut, Single},
|
||||||
};
|
};
|
||||||
use tracing::{debug, trace, warn};
|
use tracing::{debug, trace, warn};
|
||||||
|
|
||||||
@@ -123,7 +123,7 @@ pub fn ghost_collision_system(
|
|||||||
mut stage_events: EventWriter<StageTransition>,
|
mut stage_events: EventWriter<StageTransition>,
|
||||||
mut score: ResMut<ScoreResource>,
|
mut score: ResMut<ScoreResource>,
|
||||||
mut game_state: ResMut<GameStage>,
|
mut game_state: ResMut<GameStage>,
|
||||||
pacman_query: Query<Entity, With<PlayerControlled>>,
|
player: Single<Entity, With<PlayerControlled>>,
|
||||||
ghost_query: Query<(Entity, &Ghost), With<GhostCollider>>,
|
ghost_query: Query<(Entity, &Ghost), With<GhostCollider>>,
|
||||||
mut ghost_state_query: Query<&mut GhostState>,
|
mut ghost_state_query: Query<&mut GhostState>,
|
||||||
mut events: EventWriter<AudioEvent>,
|
mut events: EventWriter<AudioEvent>,
|
||||||
@@ -131,9 +131,9 @@ pub fn ghost_collision_system(
|
|||||||
for event in collision_events.read() {
|
for event in collision_events.read() {
|
||||||
if let GameEvent::Collision(entity1, entity2) = event {
|
if let GameEvent::Collision(entity1, entity2) = event {
|
||||||
// Check if one is Pacman and the other is a ghost
|
// 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)
|
(*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)
|
(*entity2, *entity1)
|
||||||
} else {
|
} else {
|
||||||
continue;
|
continue;
|
||||||
|
|||||||
@@ -229,6 +229,14 @@ pub struct Eaten;
|
|||||||
#[derive(Component, Debug, Clone, Copy)]
|
#[derive(Component, Debug, Clone, Copy)]
|
||||||
pub struct Dying;
|
pub struct Dying;
|
||||||
|
|
||||||
|
/// 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,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Component, Debug, Clone, Copy)]
|
#[derive(Component, Debug, Clone, Copy)]
|
||||||
pub enum GhostState {
|
pub enum GhostState {
|
||||||
/// Normal ghost behavior - chasing Pac-Man
|
/// Normal ghost behavior - chasing Pac-Man
|
||||||
|
|||||||
@@ -1,12 +1,11 @@
|
|||||||
use bevy_ecs::{
|
use bevy_ecs::{
|
||||||
event::{EventReader, EventWriter},
|
event::EventReader,
|
||||||
query::{With, Without},
|
query::{With, Without},
|
||||||
system::{Query, Res, ResMut},
|
system::{Query, Res, ResMut, Single},
|
||||||
};
|
};
|
||||||
use tracing::trace;
|
use tracing::trace;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
error::GameError,
|
|
||||||
events::{GameCommand, GameEvent},
|
events::{GameCommand, GameEvent},
|
||||||
map::{builder::Map, graph::Edge},
|
map::{builder::Map, graph::Edge},
|
||||||
systems::{
|
systems::{
|
||||||
@@ -33,32 +32,22 @@ pub fn player_control_system(
|
|||||||
mut state: ResMut<GlobalState>,
|
mut state: ResMut<GlobalState>,
|
||||||
mut debug_state: ResMut<DebugState>,
|
mut debug_state: ResMut<DebugState>,
|
||||||
mut audio_state: ResMut<AudioState>,
|
mut audio_state: ResMut<AudioState>,
|
||||||
mut players: Query<&mut BufferedDirection, (With<PlayerControlled>, Without<Frozen>)>,
|
mut player: Option<Single<&mut BufferedDirection, (With<PlayerControlled>, Without<Frozen>)>>,
|
||||||
mut errors: EventWriter<GameError>,
|
|
||||||
) {
|
) {
|
||||||
// Handle events
|
// Handle events
|
||||||
for event in events.read() {
|
for event in events.read() {
|
||||||
if let GameEvent::Command(command) = event {
|
if let GameEvent::Command(command) = event {
|
||||||
match command {
|
match command {
|
||||||
GameCommand::MovePlayer(direction) => {
|
GameCommand::MovePlayer(direction) => {
|
||||||
// Get the player's movable component (ensuring there is only one player)
|
// Only handle movement if there's an unfrozen player
|
||||||
let mut buffered_direction = match players.single_mut() {
|
if let Some(player_single) = player.as_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");
|
trace!(direction = ?*direction, "Player direction buffered for movement");
|
||||||
*buffered_direction = BufferedDirection::Some {
|
***player_single = BufferedDirection::Some {
|
||||||
direction: *direction,
|
direction: *direction,
|
||||||
remaining_time: 0.25,
|
remaining_time: 0.25,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
}
|
||||||
GameCommand::Exit => {
|
GameCommand::Exit => {
|
||||||
state.exit = true;
|
state.exit = true;
|
||||||
}
|
}
|
||||||
@@ -168,8 +157,8 @@ pub fn player_movement_system(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Applies tunnel slowdown based on the current node tile
|
/// 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>>) {
|
pub fn player_tunnel_slowdown_system(map: Res<Map>, player: Single<(&Position, &mut MovementModifiers), With<PlayerControlled>>) {
|
||||||
if let Ok((position, mut modifiers)) = q.single_mut() {
|
let (position, mut modifiers) = player.into_inner();
|
||||||
let node = position.current_node();
|
let node = position.current_node();
|
||||||
let in_tunnel = map
|
let in_tunnel = map
|
||||||
.tile_at_node(node)
|
.tile_at_node(node)
|
||||||
@@ -187,5 +176,4 @@ pub fn player_tunnel_slowdown_system(map: Res<Map>, mut q: Query<(&Position, &mu
|
|||||||
|
|
||||||
modifiers.tunnel_slowdown_active = in_tunnel;
|
modifiers.tunnel_slowdown_active = in_tunnel;
|
||||||
modifiers.speed_multiplier = if in_tunnel { 0.6 } else { 1.0 };
|
modifiers.speed_multiplier = if in_tunnel { 0.6 } else { 1.0 };
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -52,6 +52,11 @@ impl TimingBuffer {
|
|||||||
self.last_tick = current_tick;
|
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.
|
/// Gets statistics for this timing buffer.
|
||||||
///
|
///
|
||||||
/// # Panics
|
/// # Panics
|
||||||
@@ -248,6 +253,61 @@ impl SystemTimings {
|
|||||||
// Use the formatting module to format the data
|
// Use the formatting module to format the data
|
||||||
format_timing_display(timing_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)
|
pub fn profile<S, M>(id: SystemId, system: S) -> impl FnMut(&mut bevy_ecs::world::World)
|
||||||
|
|||||||
@@ -3,8 +3,8 @@ use crate::map::direction::Direction;
|
|||||||
use crate::systems::input::TouchState;
|
use crate::systems::input::TouchState;
|
||||||
use crate::systems::{
|
use crate::systems::{
|
||||||
debug_render_system, BatchedLinesResource, Collider, CursorPosition, DebugState, DebugTextureResource, DeltaTime,
|
debug_render_system, BatchedLinesResource, Collider, CursorPosition, DebugState, DebugTextureResource, DeltaTime,
|
||||||
DirectionalAnimation, Dying, Frozen, GameStage, LinearAnimation, Looping, PlayerLives, Position, Renderable, ScoreResource,
|
DirectionalAnimation, Dying, Frozen, GameStage, LinearAnimation, Looping, PlayerLife, PlayerLives, Position, Renderable,
|
||||||
StartupSequence, SystemId, SystemTimings, TtfAtlasResource, Velocity,
|
ScoreResource, StartupSequence, SystemId, SystemTimings, TtfAtlasResource, Velocity,
|
||||||
};
|
};
|
||||||
use crate::texture::sprite::SpriteAtlas;
|
use crate::texture::sprite::SpriteAtlas;
|
||||||
use crate::texture::sprites::{GameSprite, PacmanSprite};
|
use crate::texture::sprites::{GameSprite, PacmanSprite};
|
||||||
@@ -19,7 +19,8 @@ use bevy_ecs::event::EventWriter;
|
|||||||
use bevy_ecs::query::{Changed, Has, Or, With, Without};
|
use bevy_ecs::query::{Changed, Has, Or, With, Without};
|
||||||
use bevy_ecs::removal_detection::RemovedComponents;
|
use bevy_ecs::removal_detection::RemovedComponents;
|
||||||
use bevy_ecs::resource::Resource;
|
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::pixels::Color;
|
||||||
use sdl2::rect::{Point, Rect};
|
use sdl2::rect::{Point, Rect};
|
||||||
use sdl2::render::{BlendMode, Canvas, Texture};
|
use sdl2::render::{BlendMode, Canvas, Texture};
|
||||||
@@ -126,6 +127,84 @@ pub fn linear_render_system(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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 displayed_lives = player_lives.0.saturating_sub(1);
|
||||||
|
|
||||||
|
// 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;
|
||||||
|
|
||||||
|
// Calculate the difference
|
||||||
|
let diff = (displayed_lives as i8) - (current_count as i8);
|
||||||
|
|
||||||
|
if diff > 0 {
|
||||||
|
// Spawn new life sprites
|
||||||
|
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.abs() {
|
||||||
|
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,
|
||||||
|
},
|
||||||
|
));
|
||||||
|
}
|
||||||
|
} else if diff < 0 {
|
||||||
|
// Remove excess life sprites (highest indices first)
|
||||||
|
let to_remove = diff.abs() as usize;
|
||||||
|
let sprites_to_remove: Vec<_> = current_sprites
|
||||||
|
.iter()
|
||||||
|
.rev() // Start from highest index
|
||||||
|
.take(to_remove as usize)
|
||||||
|
.map(|(entity, _)| *entity)
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
for entity in sprites_to_remove {
|
||||||
|
commands.entity(entity).despawn();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Component for Renderables to store an exact pixel position
|
||||||
|
#[derive(Component)]
|
||||||
|
pub struct PixelPosition {
|
||||||
|
pub pixel_position: Vec2,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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
|
||||||
|
|
||||||
|
let x = start_x + ((index as f32) * (sprite_spacing as f32 * 1.5)).round() as u32;
|
||||||
|
let y = start_y - CELL_SIZE / 2;
|
||||||
|
|
||||||
|
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.
|
/// 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.
|
||||||
pub struct MapTextureResource(pub Texture);
|
pub struct MapTextureResource(pub Texture);
|
||||||
|
|
||||||
@@ -211,7 +290,6 @@ pub fn hud_render_system(
|
|||||||
mut backbuffer: NonSendMut<BackbufferResource>,
|
mut backbuffer: NonSendMut<BackbufferResource>,
|
||||||
mut canvas: NonSendMut<&mut Canvas<Window>>,
|
mut canvas: NonSendMut<&mut Canvas<Window>>,
|
||||||
mut atlas: NonSendMut<SpriteAtlas>,
|
mut atlas: NonSendMut<SpriteAtlas>,
|
||||||
player_lives: Res<PlayerLives>,
|
|
||||||
score: Res<ScoreResource>,
|
score: Res<ScoreResource>,
|
||||||
stage: Res<GameStage>,
|
stage: Res<GameStage>,
|
||||||
mut errors: EventWriter<GameError>,
|
mut errors: EventWriter<GameError>,
|
||||||
@@ -227,35 +305,6 @@ pub fn hud_render_system(
|
|||||||
errors.write(TextureError::RenderFailed(format!("Failed to render lives text: {}", e)).into());
|
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
|
// Render score text
|
||||||
let score_text = format!("{:02}", score.0);
|
let score_text = format!("{:02}", score.0);
|
||||||
let score_offset = 7 - (score_text.len() as i32);
|
let score_offset = 7 - (score_text.len() as i32);
|
||||||
@@ -318,7 +367,10 @@ pub fn render_system(
|
|||||||
atlas: &mut SpriteAtlas,
|
atlas: &mut SpriteAtlas,
|
||||||
map: &Res<Map>,
|
map: &Res<Map>,
|
||||||
dirty: &Res<RenderDirty>,
|
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>,
|
errors: &mut EventWriter<GameError>,
|
||||||
) {
|
) {
|
||||||
if !dirty.0 {
|
if !dirty.0 {
|
||||||
@@ -335,12 +387,21 @@ pub fn render_system(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Render all entities to the backbuffer
|
// Render all entities to the backbuffer
|
||||||
for (_, renderable, position) in renderables
|
for (_entity, renderable, position, pixel_position) in renderables
|
||||||
.iter()
|
.iter()
|
||||||
.sort_by_key::<(Entity, &Renderable, &Position), _>(|(_, renderable, _)| renderable.layer)
|
.sort_by_key::<(Entity, &Renderable, Option<&Position>, Option<&PixelPosition>), _>(|(_, renderable, _, _)| {
|
||||||
|
renderable.layer
|
||||||
|
})
|
||||||
.rev()
|
.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 {
|
match pos {
|
||||||
Ok(pos) => {
|
Ok(pos) => {
|
||||||
let dest = Rect::from_center(
|
let dest = Rect::from_center(
|
||||||
@@ -378,7 +439,10 @@ pub fn combined_render_system(
|
|||||||
timing: Res<crate::systems::profiling::Timing>,
|
timing: Res<crate::systems::profiling::Timing>,
|
||||||
map: Res<Map>,
|
map: Res<Map>,
|
||||||
dirty: Res<RenderDirty>,
|
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)>,
|
colliders: Query<(&Collider, &Position)>,
|
||||||
cursor: Res<CursorPosition>,
|
cursor: Res<CursorPosition>,
|
||||||
mut errors: EventWriter<GameError>,
|
mut errors: EventWriter<GameError>,
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ use bevy_ecs::{
|
|||||||
event::{EventReader, EventWriter},
|
event::{EventReader, EventWriter},
|
||||||
query::{With, Without},
|
query::{With, Without},
|
||||||
resource::Resource,
|
resource::Resource,
|
||||||
system::{Commands, NonSendMut, Query, Res, ResMut},
|
system::{Commands, NonSendMut, Query, Res, ResMut, Single},
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Resource, Clone)]
|
#[derive(Resource, Clone)]
|
||||||
@@ -122,7 +122,7 @@ pub fn stage_system(
|
|||||||
mut audio_events: EventWriter<AudioEvent>,
|
mut audio_events: EventWriter<AudioEvent>,
|
||||||
mut stage_event_reader: EventReader<StageTransition>,
|
mut stage_event_reader: EventReader<StageTransition>,
|
||||||
mut blinking_query: Query<Entity, With<Blinking>>,
|
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>)>,
|
mut ghost_query: Query<(Entity, &Ghost, &mut Position), (With<GhostCollider>, Without<PlayerControlled>)>,
|
||||||
atlas: NonSendMut<SpriteAtlas>,
|
atlas: NonSendMut<SpriteAtlas>,
|
||||||
) {
|
) {
|
||||||
@@ -132,11 +132,7 @@ pub fn stage_system(
|
|||||||
// Handle stage transition requests before normal ticking
|
// Handle stage transition requests before normal ticking
|
||||||
for event in stage_event_reader.read() {
|
for event in stage_event_reader.read() {
|
||||||
let StageTransition::GhostEatenPause { ghost_entity } = *event;
|
let StageTransition::GhostEatenPause { ghost_entity } = *event;
|
||||||
let pac_node = player_query
|
let pac_node = player.1.current_node();
|
||||||
.single_mut()
|
|
||||||
.ok()
|
|
||||||
.map(|(_, pos)| pos.current_node())
|
|
||||||
.unwrap_or(map.start_positions.pacman);
|
|
||||||
|
|
||||||
debug!(ghost_entity = ?ghost_entity, node = pac_node, "Ghost eaten, entering pause state");
|
debug!(ghost_entity = ?ghost_entity, node = pac_node, "Ghost eaten, entering pause state");
|
||||||
new_state = Some(GameStage::GhostEatenPause {
|
new_state = Some(GameStage::GhostEatenPause {
|
||||||
@@ -240,18 +236,13 @@ pub fn stage_system(
|
|||||||
match (old_state, new_state) {
|
match (old_state, new_state) {
|
||||||
(GameStage::Playing, GameStage::GhostEatenPause { ghost_entity, node, .. }) => {
|
(GameStage::Playing, GameStage::GhostEatenPause { ghost_entity, node, .. }) => {
|
||||||
// Freeze the player & ghosts
|
// Freeze the player & ghosts
|
||||||
for entity in player_query
|
commands.entity(player.0).insert(Frozen);
|
||||||
.iter_mut()
|
for (entity, _, _) in ghost_query.iter_mut() {
|
||||||
.map(|(e, _)| e)
|
|
||||||
.chain(ghost_query.iter_mut().map(|(e, _, _)| e))
|
|
||||||
{
|
|
||||||
commands.entity(entity).insert(Frozen);
|
commands.entity(entity).insert(Frozen);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Hide the player & eaten ghost
|
// Hide the player & eaten ghost
|
||||||
for (player_entity, _) in player_query.iter_mut() {
|
commands.entity(player.0).insert(Hidden);
|
||||||
commands.entity(player_entity).insert(Hidden);
|
|
||||||
}
|
|
||||||
commands.entity(ghost_entity).insert(Hidden);
|
commands.entity(ghost_entity).insert(Hidden);
|
||||||
|
|
||||||
// Spawn bonus points entity at Pac-Man's position
|
// Spawn bonus points entity at Pac-Man's position
|
||||||
@@ -275,11 +266,8 @@ pub fn stage_system(
|
|||||||
}
|
}
|
||||||
(GameStage::GhostEatenPause { ghost_entity, .. }, GameStage::Playing) => {
|
(GameStage::GhostEatenPause { ghost_entity, .. }, GameStage::Playing) => {
|
||||||
// Unfreeze and reveal the player & all ghosts
|
// Unfreeze and reveal the player & all ghosts
|
||||||
for entity in player_query
|
commands.entity(player.0).remove::<(Frozen, Hidden)>();
|
||||||
.iter_mut()
|
for (entity, _, _) in ghost_query.iter_mut() {
|
||||||
.map(|(e, _)| e)
|
|
||||||
.chain(ghost_query.iter_mut().map(|(e, _, _)| e))
|
|
||||||
{
|
|
||||||
commands.entity(entity).remove::<(Frozen, Hidden)>();
|
commands.entity(entity).remove::<(Frozen, Hidden)>();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -288,11 +276,8 @@ pub fn stage_system(
|
|||||||
}
|
}
|
||||||
(GameStage::Playing, GameStage::PlayerDying(DyingSequence::Frozen { .. })) => {
|
(GameStage::Playing, GameStage::PlayerDying(DyingSequence::Frozen { .. })) => {
|
||||||
// Freeze the player & ghosts
|
// Freeze the player & ghosts
|
||||||
for entity in player_query
|
commands.entity(player.0).insert(Frozen);
|
||||||
.iter_mut()
|
for (entity, _, _) in ghost_query.iter_mut() {
|
||||||
.map(|(e, _)| e)
|
|
||||||
.chain(ghost_query.iter_mut().map(|(e, _, _)| e))
|
|
||||||
{
|
|
||||||
commands.entity(entity).insert(Frozen);
|
commands.entity(entity).insert(Frozen);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -303,23 +288,17 @@ pub fn stage_system(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Start Pac-Man's death animation
|
// Start Pac-Man's death animation
|
||||||
if let Ok((player_entity, _)) = player_query.single_mut() {
|
commands.entity(player.0).insert((Dying, player_death_animation.0.clone()));
|
||||||
commands
|
|
||||||
.entity(player_entity)
|
|
||||||
.insert((Dying, player_death_animation.0.clone()));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Play the death sound
|
// Play the death sound
|
||||||
audio_events.write(AudioEvent::PlayDeath);
|
audio_events.write(AudioEvent::PlayDeath);
|
||||||
}
|
}
|
||||||
(GameStage::PlayerDying(DyingSequence::Animating { .. }), GameStage::PlayerDying(DyingSequence::Hidden { .. })) => {
|
(GameStage::PlayerDying(DyingSequence::Animating { .. }), GameStage::PlayerDying(DyingSequence::Hidden { .. })) => {
|
||||||
// Hide the player
|
// Hide the player
|
||||||
if let Ok((player_entity, _)) = player_query.single_mut() {
|
commands.entity(player.0).insert(Hidden);
|
||||||
commands.entity(player_entity).insert(Hidden);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
(_, GameStage::LevelRestarting) => {
|
(_, GameStage::LevelRestarting) => {
|
||||||
if let Ok((player_entity, mut pos)) = player_query.single_mut() {
|
let (player_entity, mut pos) = player.into_inner();
|
||||||
*pos = Position::Stopped {
|
*pos = Position::Stopped {
|
||||||
node: map.start_positions.pacman,
|
node: map.start_positions.pacman,
|
||||||
};
|
};
|
||||||
@@ -334,7 +313,6 @@ pub fn stage_system(
|
|||||||
.entity(player_entity)
|
.entity(player_entity)
|
||||||
.remove::<(Frozen, Dying, LinearAnimation, Looping)>()
|
.remove::<(Frozen, Dying, LinearAnimation, Looping)>()
|
||||||
.insert(player_animation.0.clone());
|
.insert(player_animation.0.clone());
|
||||||
}
|
|
||||||
|
|
||||||
// Reset ghost positions and state
|
// Reset ghost positions and state
|
||||||
for (ghost_entity, ghost, mut ghost_pos) in ghost_query.iter_mut() {
|
for (ghost_entity, ghost, mut ghost_pos) in ghost_query.iter_mut() {
|
||||||
@@ -354,22 +332,18 @@ pub fn stage_system(
|
|||||||
}
|
}
|
||||||
(_, GameStage::Starting(StartupSequence::CharactersVisible { .. })) => {
|
(_, GameStage::Starting(StartupSequence::CharactersVisible { .. })) => {
|
||||||
// Unhide the player & ghosts
|
// Unhide the player & ghosts
|
||||||
for entity in player_query
|
commands.entity(player.0).remove::<Hidden>();
|
||||||
.iter_mut()
|
for (entity, _, _) in ghost_query.iter_mut() {
|
||||||
.map(|(e, _)| e)
|
|
||||||
.chain(ghost_query.iter_mut().map(|(e, _, _)| e))
|
|
||||||
{
|
|
||||||
commands.entity(entity).remove::<Hidden>();
|
commands.entity(entity).remove::<Hidden>();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
(GameStage::Starting(StartupSequence::CharactersVisible { .. }), GameStage::Playing) => {
|
(GameStage::Starting(StartupSequence::CharactersVisible { .. }), GameStage::Playing) => {
|
||||||
// Unfreeze the player & ghosts & blinking
|
// Unfreeze the player & ghosts & blinking
|
||||||
for entity in player_query
|
commands.entity(player.0).remove::<Frozen>();
|
||||||
.iter_mut()
|
for (entity, _, _) in ghost_query.iter_mut() {
|
||||||
.map(|(e, _)| e)
|
commands.entity(entity).remove::<Frozen>();
|
||||||
.chain(ghost_query.iter_mut().map(|(e, _, _)| e))
|
}
|
||||||
.chain(blinking_query.iter_mut())
|
for entity in blinking_query.iter_mut() {
|
||||||
{
|
|
||||||
commands.entity(entity).remove::<Frozen>();
|
commands.entity(entity).remove::<Frozen>();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -214,11 +214,9 @@ fn test_player_control_system_no_player_entity() {
|
|||||||
// Run the system - should write an error
|
// Run the system - should write an error
|
||||||
world
|
world
|
||||||
.run_system_once(player_control_system)
|
.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,
|
// The system should run successfully and simply ignore movement commands when there's no player
|
||||||
// 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
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
Reference in New Issue
Block a user