mirror of
https://github.com/Xevion/Pac-Man.git
synced 2025-12-06 13:15:47 -06:00
Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9bfe4a9ce7 | ||
|
|
2da8a312f3 | ||
|
|
2bdd4f0d04 | ||
|
|
5cc9b1a6ee | ||
|
|
5d4adb7743 | ||
|
|
633d467f2c |
33
src/game.rs
33
src/game.rs
@@ -8,18 +8,17 @@ use crate::events::GameEvent;
|
|||||||
use crate::map::builder::Map;
|
use crate::map::builder::Map;
|
||||||
use crate::map::direction::Direction;
|
use crate::map::direction::Direction;
|
||||||
use crate::systems::blinking::Blinking;
|
use crate::systems::blinking::Blinking;
|
||||||
use crate::systems::{self, ghost_collision_system};
|
use crate::systems::{self, ghost_collision_system, MovementModifiers};
|
||||||
|
|
||||||
use crate::systems::movement::{BufferedDirection, Position, Velocity};
|
use crate::systems::movement::{BufferedDirection, Position, Velocity};
|
||||||
use crate::systems::profiling::SystemId;
|
use crate::systems::profiling::SystemId;
|
||||||
use crate::systems::render::RenderDirty;
|
use crate::systems::render::RenderDirty;
|
||||||
use crate::systems::{
|
use crate::systems::{
|
||||||
audio_system, blinking_system, collision_system, debug_render_system, directional_render_system, dirty_render_system,
|
audio_system, blinking_system, collision_system, debug_render_system, directional_render_system, dirty_render_system,
|
||||||
ghost_movement_system, hud_render_system, item_system, profile, ready_visibility_system, render_system, AudioEvent,
|
ghost_movement_system, hud_render_system, item_system, profile, render_system, AudioEvent, AudioResource, AudioState,
|
||||||
AudioResource, AudioState, BackbufferResource, Collider, DebugFontResource, DebugState, DebugTextureResource, DeltaTime,
|
BackbufferResource, Collider, DebugFontResource, DebugState, DebugTextureResource, DeltaTime, DirectionalAnimated,
|
||||||
DirectionalAnimated, EntityType, Frozen, Ghost, GhostBundle, GhostCollider, GlobalState, ItemBundle, ItemCollider,
|
EntityType, Frozen, Ghost, GhostBundle, GhostCollider, GlobalState, ItemBundle, ItemCollider, MapTextureResource,
|
||||||
LevelTiming, MapTextureResource, PacmanCollider, PlayerBundle, PlayerControlled, PlayerStateBundle, Renderable,
|
PacmanCollider, PlayerBundle, PlayerControlled, Renderable, ScoreResource, StartupSequence, SystemTimings,
|
||||||
ScoreResource, StartupSequence, SystemTimings,
|
|
||||||
};
|
};
|
||||||
use crate::texture::animated::AnimatedTexture;
|
use crate::texture::animated::AnimatedTexture;
|
||||||
use bevy_ecs::event::EventRegistry;
|
use bevy_ecs::event::EventRegistry;
|
||||||
@@ -185,12 +184,12 @@ impl Game {
|
|||||||
speed: 1.15,
|
speed: 1.15,
|
||||||
direction: Direction::Left,
|
direction: Direction::Left,
|
||||||
},
|
},
|
||||||
|
movement_modifiers: MovementModifiers::default(),
|
||||||
buffered_direction: BufferedDirection::None,
|
buffered_direction: BufferedDirection::None,
|
||||||
sprite: Renderable {
|
sprite: Renderable {
|
||||||
sprite: SpriteAtlas::get_tile(&atlas, "pacman/full.png")
|
sprite: SpriteAtlas::get_tile(&atlas, "pacman/full.png")
|
||||||
.ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound("pacman/full.png".to_string())))?,
|
.ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound("pacman/full.png".to_string())))?,
|
||||||
layer: 0,
|
layer: 0,
|
||||||
visible: true,
|
|
||||||
},
|
},
|
||||||
directional_animated: DirectionalAnimated {
|
directional_animated: DirectionalAnimated {
|
||||||
textures,
|
textures,
|
||||||
@@ -205,7 +204,6 @@ impl Game {
|
|||||||
|
|
||||||
// Spawn player and attach initial state bundle
|
// Spawn player and attach initial state bundle
|
||||||
let player_entity = world.spawn(player).id();
|
let player_entity = world.spawn(player).id();
|
||||||
world.entity_mut(player_entity).insert(PlayerStateBundle::default());
|
|
||||||
world.entity_mut(player_entity).insert(Frozen);
|
world.entity_mut(player_entity).insert(Frozen);
|
||||||
|
|
||||||
world.insert_non_send_resource(atlas);
|
world.insert_non_send_resource(atlas);
|
||||||
@@ -227,7 +225,6 @@ impl Game {
|
|||||||
world.insert_resource(DebugState::default());
|
world.insert_resource(DebugState::default());
|
||||||
world.insert_resource(AudioState::default());
|
world.insert_resource(AudioState::default());
|
||||||
world.insert_resource(CursorPosition::default());
|
world.insert_resource(CursorPosition::default());
|
||||||
world.insert_resource(LevelTiming::for_level(1));
|
|
||||||
|
|
||||||
world.add_observer(
|
world.add_observer(
|
||||||
|event: Trigger<GameEvent>, mut state: ResMut<GlobalState>, _score: ResMut<ScoreResource>| {
|
|event: Trigger<GameEvent>, mut state: ResMut<GlobalState>, _score: ResMut<ScoreResource>| {
|
||||||
@@ -283,7 +280,6 @@ impl Game {
|
|||||||
(collision_system, ghost_collision_system, item_system).chain(),
|
(collision_system, ghost_collision_system, item_system).chain(),
|
||||||
audio_system,
|
audio_system,
|
||||||
blinking_system,
|
blinking_system,
|
||||||
ready_visibility_system,
|
|
||||||
(
|
(
|
||||||
directional_render_system,
|
directional_render_system,
|
||||||
dirty_render_system,
|
dirty_render_system,
|
||||||
@@ -295,15 +291,7 @@ impl Game {
|
|||||||
.chain(),
|
.chain(),
|
||||||
));
|
));
|
||||||
|
|
||||||
// Initialize StartupSequence as a global resource
|
world.insert_resource(StartupSequence::new(60 * 3, 60));
|
||||||
let ready_duration_ticks = {
|
|
||||||
let duration = world
|
|
||||||
.get_resource::<LevelTiming>()
|
|
||||||
.map(|t| t.spawn_freeze_duration)
|
|
||||||
.unwrap_or(1.5);
|
|
||||||
(duration * 60.0) as u32 // Convert to ticks at 60 FPS
|
|
||||||
};
|
|
||||||
world.insert_resource(StartupSequence::new(ready_duration_ticks, 60));
|
|
||||||
|
|
||||||
// Spawn ghosts
|
// Spawn ghosts
|
||||||
Self::spawn_ghosts(&mut world)?;
|
Self::spawn_ghosts(&mut world)?;
|
||||||
@@ -327,11 +315,7 @@ impl Game {
|
|||||||
|
|
||||||
let mut item = world.spawn(ItemBundle {
|
let mut item = world.spawn(ItemBundle {
|
||||||
position: Position::Stopped { node: node_id },
|
position: Position::Stopped { node: node_id },
|
||||||
sprite: Renderable {
|
sprite: Renderable { sprite, layer: 1 },
|
||||||
sprite,
|
|
||||||
layer: 1,
|
|
||||||
visible: true,
|
|
||||||
},
|
|
||||||
entity_type: item_type,
|
entity_type: item_type,
|
||||||
collider: Collider { size },
|
collider: Collider { size },
|
||||||
item_collider: ItemCollider,
|
item_collider: ItemCollider,
|
||||||
@@ -438,7 +422,6 @@ impl Game {
|
|||||||
},
|
},
|
||||||
)?,
|
)?,
|
||||||
layer: 0,
|
layer: 0,
|
||||||
visible: true,
|
|
||||||
},
|
},
|
||||||
directional_animated: DirectionalAnimated {
|
directional_animated: DirectionalAnimated {
|
||||||
textures,
|
textures,
|
||||||
|
|||||||
@@ -1,9 +1,14 @@
|
|||||||
use bevy_ecs::{
|
use bevy_ecs::{
|
||||||
component::Component,
|
component::Component,
|
||||||
system::{Query, Res},
|
entity::Entity,
|
||||||
|
query::{Has, With},
|
||||||
|
system::{Commands, Query, Res},
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::systems::components::{DeltaTime, Renderable};
|
use crate::systems::{
|
||||||
|
components::{DeltaTime, Renderable},
|
||||||
|
Hidden,
|
||||||
|
};
|
||||||
|
|
||||||
#[derive(Component)]
|
#[derive(Component)]
|
||||||
pub struct Blinking {
|
pub struct Blinking {
|
||||||
@@ -15,13 +20,23 @@ pub struct Blinking {
|
|||||||
///
|
///
|
||||||
/// This system manages entities that have both `Blinking` and `Renderable` components,
|
/// This system manages entities that have both `Blinking` and `Renderable` components,
|
||||||
/// accumulating time and toggling visibility when the specified interval is reached.
|
/// accumulating time and toggling visibility when the specified interval is reached.
|
||||||
pub fn blinking_system(time: Res<DeltaTime>, mut query: Query<(&mut Blinking, &mut Renderable)>) {
|
pub fn blinking_system(
|
||||||
for (mut blinking, mut renderable) in query.iter_mut() {
|
mut commands: Commands,
|
||||||
|
time: Res<DeltaTime>,
|
||||||
|
mut query: Query<(Entity, &mut Blinking, Has<Hidden>), With<Renderable>>,
|
||||||
|
) {
|
||||||
|
for (entity, mut blinking, hidden) in query.iter_mut() {
|
||||||
blinking.timer += time.0;
|
blinking.timer += time.0;
|
||||||
|
|
||||||
if blinking.timer >= blinking.interval {
|
if blinking.timer >= blinking.interval {
|
||||||
blinking.timer = 0.0;
|
blinking.timer = 0.0;
|
||||||
renderable.visible = !renderable.visible;
|
|
||||||
|
// Add or remove the Visible component based on whether it is currently in the query
|
||||||
|
if hidden {
|
||||||
|
commands.entity(entity).remove::<Hidden>();
|
||||||
|
} else {
|
||||||
|
commands.entity(entity).insert(Hidden);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ use crate::{
|
|||||||
map::graph::TraversalFlags,
|
map::graph::TraversalFlags,
|
||||||
systems::{
|
systems::{
|
||||||
movement::{BufferedDirection, Position, Velocity},
|
movement::{BufferedDirection, Position, Velocity},
|
||||||
Collider, GhostCollider, ItemCollider, PacmanCollider, PlayerLifecycle,
|
Collider, GhostCollider, ItemCollider, PacmanCollider,
|
||||||
},
|
},
|
||||||
texture::{animated::AnimatedTexture, sprite::AtlasTile},
|
texture::{animated::AnimatedTexture, sprite::AtlasTile},
|
||||||
};
|
};
|
||||||
@@ -93,7 +93,6 @@ impl EntityType {
|
|||||||
pub struct Renderable {
|
pub struct Renderable {
|
||||||
pub sprite: AtlasTile,
|
pub sprite: AtlasTile,
|
||||||
pub layer: u8,
|
pub layer: u8,
|
||||||
pub visible: bool,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A component for entities that have a directional animated texture.
|
/// A component for entities that have a directional animated texture.
|
||||||
@@ -141,35 +140,6 @@ impl Default for MovementModifiers {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Level-dependent timing configuration
|
|
||||||
#[derive(Resource, Debug, Clone, Copy)]
|
|
||||||
pub struct LevelTiming {
|
|
||||||
/// Duration of energizer effect in seconds
|
|
||||||
pub energizer_duration: f32,
|
|
||||||
/// Freeze duration at spawn/ready in seconds
|
|
||||||
pub spawn_freeze_duration: f32,
|
|
||||||
/// When to start flashing relative to energizer end (seconds)
|
|
||||||
pub energizer_flash_threshold: f32,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for LevelTiming {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self {
|
|
||||||
energizer_duration: 6.0,
|
|
||||||
spawn_freeze_duration: 1.5,
|
|
||||||
energizer_flash_threshold: 2.0,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl LevelTiming {
|
|
||||||
/// Returns timing configuration for a given level.
|
|
||||||
pub fn for_level(_level: u32) -> Self {
|
|
||||||
// Placeholder: tune per the Pac-Man Dossier tables
|
|
||||||
Self::default()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Tag component for entities that should be frozen during startup
|
/// Tag component for entities that should be frozen during startup
|
||||||
#[derive(Component, Debug, Clone, Copy)]
|
#[derive(Component, Debug, Clone, Copy)]
|
||||||
pub struct Frozen;
|
pub struct Frozen;
|
||||||
@@ -190,14 +160,8 @@ pub struct PlayerBundle {
|
|||||||
pub directional_animated: DirectionalAnimated,
|
pub directional_animated: DirectionalAnimated,
|
||||||
pub entity_type: EntityType,
|
pub entity_type: EntityType,
|
||||||
pub collider: Collider,
|
pub collider: Collider,
|
||||||
pub pacman_collider: PacmanCollider,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Convenience bundle for attaching the hybrid FSM to the player entity
|
|
||||||
#[derive(Bundle, Default)]
|
|
||||||
pub struct PlayerStateBundle {
|
|
||||||
pub lifecycle: PlayerLifecycle,
|
|
||||||
pub movement_modifiers: MovementModifiers,
|
pub movement_modifiers: MovementModifiers,
|
||||||
|
pub pacman_collider: PacmanCollider,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Bundle)]
|
#[derive(Bundle)]
|
||||||
|
|||||||
@@ -1,107 +0,0 @@
|
|||||||
use num_width::NumberWidth;
|
|
||||||
use smallvec::SmallVec;
|
|
||||||
use std::time::Duration;
|
|
||||||
use strum::EnumCount;
|
|
||||||
|
|
||||||
use crate::systems::profiling::SystemId;
|
|
||||||
|
|
||||||
// Helper to split a duration into a integer, decimal, and unit
|
|
||||||
fn get_value(duration: &Duration) -> (u64, u32, &'static str) {
|
|
||||||
let (int, decimal, unit) = match duration {
|
|
||||||
// if greater than 1 second, return as seconds
|
|
||||||
n if n >= &Duration::from_secs(1) => {
|
|
||||||
let secs = n.as_secs();
|
|
||||||
let decimal = n.as_millis() as u64 % 1000;
|
|
||||||
(secs, decimal as u32, "s")
|
|
||||||
}
|
|
||||||
// if greater than 1 millisecond, return as milliseconds
|
|
||||||
n if n >= &Duration::from_millis(1) => {
|
|
||||||
let ms = n.as_millis() as u64;
|
|
||||||
let decimal = n.as_micros() as u64 % 1000;
|
|
||||||
(ms, decimal as u32, "ms")
|
|
||||||
}
|
|
||||||
// if greater than 1 microsecond, return as microseconds
|
|
||||||
n if n >= &Duration::from_micros(1) => {
|
|
||||||
let us = n.as_micros() as u64;
|
|
||||||
let decimal = n.as_nanos() as u64 % 1000;
|
|
||||||
(us, decimal as u32, "µs")
|
|
||||||
}
|
|
||||||
// otherwise, return as nanoseconds
|
|
||||||
n => {
|
|
||||||
let ns = n.as_nanos() as u64;
|
|
||||||
(ns, 0, "ns")
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
(int, decimal, unit)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Formats timing data into a vector of strings with proper alignment
|
|
||||||
pub fn format_timing_display(
|
|
||||||
timing_data: impl IntoIterator<Item = (String, Duration, Duration)>,
|
|
||||||
) -> SmallVec<[String; SystemId::COUNT]> {
|
|
||||||
let mut iter = timing_data.into_iter().peekable();
|
|
||||||
if iter.peek().is_none() {
|
|
||||||
return SmallVec::new();
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Entry {
|
|
||||||
name: String,
|
|
||||||
avg_int: u64,
|
|
||||||
avg_decimal: u32,
|
|
||||||
avg_unit: &'static str,
|
|
||||||
std_int: u64,
|
|
||||||
std_decimal: u32,
|
|
||||||
std_unit: &'static str,
|
|
||||||
}
|
|
||||||
|
|
||||||
let entries = iter
|
|
||||||
.map(|(name, avg, std_dev)| {
|
|
||||||
let (avg_int, avg_decimal, avg_unit) = get_value(&avg);
|
|
||||||
let (std_int, std_decimal, std_unit) = get_value(&std_dev);
|
|
||||||
|
|
||||||
Entry {
|
|
||||||
name: name.clone(),
|
|
||||||
avg_int,
|
|
||||||
avg_decimal,
|
|
||||||
avg_unit,
|
|
||||||
std_int,
|
|
||||||
std_decimal,
|
|
||||||
std_unit,
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect::<SmallVec<[Entry; 12]>>();
|
|
||||||
|
|
||||||
let (max_name_width, max_avg_int_width, max_avg_decimal_width, max_std_int_width, max_std_decimal_width) = entries
|
|
||||||
.iter()
|
|
||||||
.fold((0, 0, 3, 0, 3), |(name_w, avg_int_w, avg_dec_w, std_int_w, std_dec_w), e| {
|
|
||||||
(
|
|
||||||
name_w.max(e.name.len()),
|
|
||||||
avg_int_w.max(e.avg_int.width() as usize),
|
|
||||||
avg_dec_w.max(e.avg_decimal.width() as usize),
|
|
||||||
std_int_w.max(e.std_int.width() as usize),
|
|
||||||
std_dec_w.max(e.std_decimal.width() as usize),
|
|
||||||
)
|
|
||||||
});
|
|
||||||
|
|
||||||
entries.iter().map(|e| {
|
|
||||||
format!(
|
|
||||||
"{name:max_name_width$} : {avg_int:max_avg_int_width$}.{avg_decimal:<max_avg_decimal_width$}{avg_unit} ± {std_int:max_std_int_width$}.{std_decimal:<max_std_decimal_width$}{std_unit}",
|
|
||||||
// Content
|
|
||||||
name = e.name,
|
|
||||||
avg_int = e.avg_int,
|
|
||||||
avg_decimal = e.avg_decimal,
|
|
||||||
std_int = e.std_int,
|
|
||||||
std_decimal = e.std_decimal,
|
|
||||||
// Units
|
|
||||||
avg_unit = e.avg_unit,
|
|
||||||
std_unit = e.std_unit,
|
|
||||||
// Padding
|
|
||||||
max_name_width = max_name_width,
|
|
||||||
max_avg_int_width = max_avg_int_width,
|
|
||||||
max_avg_decimal_width = max_avg_decimal_width,
|
|
||||||
max_std_int_width = max_std_int_width,
|
|
||||||
max_std_decimal_width = max_std_decimal_width
|
|
||||||
)
|
|
||||||
}).collect::<SmallVec<[String; SystemId::COUNT]>>()
|
|
||||||
}
|
|
||||||
@@ -2,12 +2,12 @@ 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, ResMut},
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
events::GameEvent,
|
events::GameEvent,
|
||||||
systems::{AudioEvent, EntityType, GhostCollider, ItemCollider, LevelTiming, PacmanCollider, ScoreResource, Vulnerable},
|
systems::{AudioEvent, EntityType, GhostCollider, ItemCollider, PacmanCollider, ScoreResource, Vulnerable},
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Determines if a collision between two entity types should be handled by the item system.
|
/// Determines if a collision between two entity types should be handled by the item system.
|
||||||
@@ -29,7 +29,6 @@ pub fn item_system(
|
|||||||
item_query: Query<(Entity, &EntityType), With<ItemCollider>>,
|
item_query: Query<(Entity, &EntityType), With<ItemCollider>>,
|
||||||
ghost_query: Query<Entity, With<GhostCollider>>,
|
ghost_query: Query<Entity, With<GhostCollider>>,
|
||||||
mut events: EventWriter<AudioEvent>,
|
mut events: EventWriter<AudioEvent>,
|
||||||
level_timing: Res<LevelTiming>,
|
|
||||||
) {
|
) {
|
||||||
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 {
|
||||||
@@ -58,7 +57,7 @@ pub fn item_system(
|
|||||||
// Make ghosts vulnerable when power pellet is collected
|
// Make ghosts vulnerable when power pellet is collected
|
||||||
if *entity_type == EntityType::PowerPellet {
|
if *entity_type == EntityType::PowerPellet {
|
||||||
// Convert seconds to frames (assumes 60 FPS)
|
// Convert seconds to frames (assumes 60 FPS)
|
||||||
let total_ticks = (level_timing.energizer_duration * 60.0).round().clamp(0.0, u32::MAX as f32) as u32;
|
let total_ticks = 60 * 5;
|
||||||
|
|
||||||
// Add Vulnerable component to all ghosts
|
// Add Vulnerable component to all ghosts
|
||||||
for ghost_entity in ghost_query.iter() {
|
for ghost_entity in ghost_query.iter() {
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ pub mod blinking;
|
|||||||
pub mod collision;
|
pub mod collision;
|
||||||
pub mod components;
|
pub mod components;
|
||||||
pub mod debug;
|
pub mod debug;
|
||||||
pub mod formatting;
|
|
||||||
pub mod ghost;
|
pub mod ghost;
|
||||||
pub mod input;
|
pub mod input;
|
||||||
pub mod item;
|
pub mod item;
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
use bevy_ecs::{
|
use bevy_ecs::{
|
||||||
component::Component,
|
|
||||||
event::{EventReader, EventWriter},
|
event::{EventReader, EventWriter},
|
||||||
query::{With, Without},
|
query::{With, Without},
|
||||||
system::{Query, Res, ResMut},
|
system::{Query, Res, ResMut},
|
||||||
@@ -17,26 +16,9 @@ use crate::{
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Lifecycle state for the player entity.
|
pub fn can_traverse(entity_type: EntityType, edge: Edge) -> bool {
|
||||||
#[derive(Component, Debug, Clone, Copy, PartialEq, Eq)]
|
let entity_flags = entity_type.traversal_flags();
|
||||||
pub enum PlayerLifecycle {
|
edge.traversal_flags.contains(entity_flags)
|
||||||
Spawning,
|
|
||||||
Alive,
|
|
||||||
Dying,
|
|
||||||
Respawning,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PlayerLifecycle {
|
|
||||||
/// Returns true when gameplay input and movement should be active
|
|
||||||
pub fn is_interactive(self) -> bool {
|
|
||||||
matches!(self, PlayerLifecycle::Alive)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for PlayerLifecycle {
|
|
||||||
fn default() -> Self {
|
|
||||||
PlayerLifecycle::Spawning
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Processes player input commands and updates game state accordingly.
|
/// Processes player input commands and updates game state accordingly.
|
||||||
@@ -50,29 +32,26 @@ 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<(&PlayerLifecycle, &mut BufferedDirection), (With<PlayerControlled>, Without<Frozen>)>,
|
mut players: Query<&mut BufferedDirection, (With<PlayerControlled>, Without<Frozen>)>,
|
||||||
mut errors: EventWriter<GameError>,
|
mut errors: EventWriter<GameError>,
|
||||||
) {
|
) {
|
||||||
// Get the player's movable component (ensuring there is only one player)
|
|
||||||
let (lifecycle, 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;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// If the player is not interactive or input is locked, ignore movement commands
|
|
||||||
// let allow_input = lifecycle.is_interactive();
|
|
||||||
|
|
||||||
// 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)
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
*buffered_direction = BufferedDirection::Some {
|
*buffered_direction = BufferedDirection::Some {
|
||||||
direction: *direction,
|
direction: *direction,
|
||||||
remaining_time: 0.25,
|
remaining_time: 0.25,
|
||||||
@@ -94,32 +73,21 @@ pub fn player_control_system(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn can_traverse(entity_type: EntityType, edge: Edge) -> bool {
|
|
||||||
let entity_flags = entity_type.traversal_flags();
|
|
||||||
edge.traversal_flags.contains(entity_flags)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Executes frame-by-frame movement for Pac-Man.
|
/// Executes frame-by-frame movement for Pac-Man.
|
||||||
///
|
///
|
||||||
/// Handles movement logic including buffered direction changes, edge traversal validation, and continuous movement between nodes.
|
/// Handles movement logic including buffered direction changes, edge traversal validation, and continuous movement between nodes.
|
||||||
/// When stopped, prioritizes buffered directions for responsive controls, falling back to current direction.
|
/// When stopped, prioritizes buffered directions for responsive controls, falling back to current direction.
|
||||||
/// Supports movement chaining within a single frame when traveling at high speeds.
|
/// Supports movement chaining within a single frame when traveling at high speeds.
|
||||||
|
#[allow(clippy::type_complexity)]
|
||||||
pub fn player_movement_system(
|
pub fn player_movement_system(
|
||||||
map: Res<Map>,
|
map: Res<Map>,
|
||||||
delta_time: Res<DeltaTime>,
|
delta_time: Res<DeltaTime>,
|
||||||
mut entities: Query<
|
mut entities: Query<
|
||||||
(
|
(&MovementModifiers, &mut Position, &mut Velocity, &mut BufferedDirection),
|
||||||
&PlayerLifecycle,
|
|
||||||
&MovementModifiers,
|
|
||||||
&mut Position,
|
|
||||||
&mut Velocity,
|
|
||||||
&mut BufferedDirection,
|
|
||||||
),
|
|
||||||
(With<PlayerControlled>, Without<Frozen>),
|
(With<PlayerControlled>, Without<Frozen>),
|
||||||
>,
|
>,
|
||||||
// mut errors: EventWriter<GameError>,
|
|
||||||
) {
|
) {
|
||||||
for (lifecycle, modifiers, mut position, mut velocity, mut buffered_direction) in entities.iter_mut() {
|
for (modifiers, mut position, mut velocity, mut buffered_direction) in entities.iter_mut() {
|
||||||
// Decrement the buffered direction remaining time
|
// Decrement the buffered direction remaining time
|
||||||
if let BufferedDirection::Some {
|
if let BufferedDirection::Some {
|
||||||
direction,
|
direction,
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ use bevy_ecs::system::IntoSystem;
|
|||||||
use bevy_ecs::{resource::Resource, system::System};
|
use bevy_ecs::{resource::Resource, system::System};
|
||||||
use circular_buffer::CircularBuffer;
|
use circular_buffer::CircularBuffer;
|
||||||
use micromap::Map;
|
use micromap::Map;
|
||||||
|
use num_width::NumberWidth;
|
||||||
use parking_lot::{Mutex, RwLock};
|
use parking_lot::{Mutex, RwLock};
|
||||||
use smallvec::SmallVec;
|
use smallvec::SmallVec;
|
||||||
use std::fmt::Display;
|
use std::fmt::Display;
|
||||||
@@ -10,8 +11,6 @@ use strum::EnumCount;
|
|||||||
use strum_macros::{EnumCount, IntoStaticStr};
|
use strum_macros::{EnumCount, IntoStaticStr};
|
||||||
use thousands::Separable;
|
use thousands::Separable;
|
||||||
|
|
||||||
use crate::systems::formatting;
|
|
||||||
|
|
||||||
/// The maximum number of systems that can be profiled. Must not be exceeded, or it will panic.
|
/// The maximum number of systems that can be profiled. Must not be exceeded, or it will panic.
|
||||||
const MAX_SYSTEMS: usize = SystemId::COUNT;
|
const MAX_SYSTEMS: usize = SystemId::COUNT;
|
||||||
/// The number of durations to keep in the circular buffer.
|
/// The number of durations to keep in the circular buffer.
|
||||||
@@ -159,7 +158,7 @@ impl SystemTimings {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Use the formatting module to format the data
|
// Use the formatting module to format the data
|
||||||
formatting::format_timing_display(timing_data)
|
format_timing_display(timing_data)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -184,3 +183,104 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Helper to split a duration into a integer, decimal, and unit
|
||||||
|
fn get_value(duration: &Duration) -> (u64, u32, &'static str) {
|
||||||
|
let (int, decimal, unit) = match duration {
|
||||||
|
// if greater than 1 second, return as seconds
|
||||||
|
n if n >= &Duration::from_secs(1) => {
|
||||||
|
let secs = n.as_secs();
|
||||||
|
let decimal = n.as_millis() as u64 % 1000;
|
||||||
|
(secs, decimal as u32, "s")
|
||||||
|
}
|
||||||
|
// if greater than 1 millisecond, return as milliseconds
|
||||||
|
n if n >= &Duration::from_millis(1) => {
|
||||||
|
let ms = n.as_millis() as u64;
|
||||||
|
let decimal = n.as_micros() as u64 % 1000;
|
||||||
|
(ms, decimal as u32, "ms")
|
||||||
|
}
|
||||||
|
// if greater than 1 microsecond, return as microseconds
|
||||||
|
n if n >= &Duration::from_micros(1) => {
|
||||||
|
let us = n.as_micros() as u64;
|
||||||
|
let decimal = n.as_nanos() as u64 % 1000;
|
||||||
|
(us, decimal as u32, "µs")
|
||||||
|
}
|
||||||
|
// otherwise, return as nanoseconds
|
||||||
|
n => {
|
||||||
|
let ns = n.as_nanos() as u64;
|
||||||
|
(ns, 0, "ns")
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
(int, decimal, unit)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Formats timing data into a vector of strings with proper alignment
|
||||||
|
pub fn format_timing_display(
|
||||||
|
timing_data: impl IntoIterator<Item = (String, Duration, Duration)>,
|
||||||
|
) -> SmallVec<[String; SystemId::COUNT]> {
|
||||||
|
let mut iter = timing_data.into_iter().peekable();
|
||||||
|
if iter.peek().is_none() {
|
||||||
|
return SmallVec::new();
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Entry {
|
||||||
|
name: String,
|
||||||
|
avg_int: u64,
|
||||||
|
avg_decimal: u32,
|
||||||
|
avg_unit: &'static str,
|
||||||
|
std_int: u64,
|
||||||
|
std_decimal: u32,
|
||||||
|
std_unit: &'static str,
|
||||||
|
}
|
||||||
|
|
||||||
|
let entries = iter
|
||||||
|
.map(|(name, avg, std_dev)| {
|
||||||
|
let (avg_int, avg_decimal, avg_unit) = get_value(&avg);
|
||||||
|
let (std_int, std_decimal, std_unit) = get_value(&std_dev);
|
||||||
|
|
||||||
|
Entry {
|
||||||
|
name: name.clone(),
|
||||||
|
avg_int,
|
||||||
|
avg_decimal,
|
||||||
|
avg_unit,
|
||||||
|
std_int,
|
||||||
|
std_decimal,
|
||||||
|
std_unit,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect::<SmallVec<[Entry; 12]>>();
|
||||||
|
|
||||||
|
let (max_name_width, max_avg_int_width, max_avg_decimal_width, max_std_int_width, max_std_decimal_width) = entries
|
||||||
|
.iter()
|
||||||
|
.fold((0, 0, 3, 0, 3), |(name_w, avg_int_w, avg_dec_w, std_int_w, std_dec_w), e| {
|
||||||
|
(
|
||||||
|
name_w.max(e.name.len()),
|
||||||
|
avg_int_w.max(e.avg_int.width() as usize),
|
||||||
|
avg_dec_w.max(e.avg_decimal.width() as usize),
|
||||||
|
std_int_w.max(e.std_int.width() as usize),
|
||||||
|
std_dec_w.max(e.std_decimal.width() as usize),
|
||||||
|
)
|
||||||
|
});
|
||||||
|
|
||||||
|
entries.iter().map(|e| {
|
||||||
|
format!(
|
||||||
|
"{name:max_name_width$} : {avg_int:max_avg_int_width$}.{avg_decimal:<max_avg_decimal_width$}{avg_unit} ± {std_int:max_std_int_width$}.{std_decimal:<max_std_decimal_width$}{std_unit}",
|
||||||
|
// Content
|
||||||
|
name = e.name,
|
||||||
|
avg_int = e.avg_int,
|
||||||
|
avg_decimal = e.avg_decimal,
|
||||||
|
std_int = e.std_int,
|
||||||
|
std_decimal = e.std_decimal,
|
||||||
|
// Units
|
||||||
|
avg_unit = e.avg_unit,
|
||||||
|
std_unit = e.std_unit,
|
||||||
|
// Padding
|
||||||
|
max_name_width = max_name_width,
|
||||||
|
max_avg_int_width = max_avg_int_width,
|
||||||
|
max_avg_decimal_width = max_avg_decimal_width,
|
||||||
|
max_std_int_width = max_std_int_width,
|
||||||
|
max_std_decimal_width = max_std_decimal_width
|
||||||
|
)
|
||||||
|
}).collect::<SmallVec<[String; SystemId::COUNT]>>()
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,15 +1,13 @@
|
|||||||
use crate::constants::CANVAS_SIZE;
|
use crate::constants::CANVAS_SIZE;
|
||||||
use crate::error::{GameError, TextureError};
|
use crate::error::{GameError, TextureError};
|
||||||
use crate::map::builder::Map;
|
use crate::map::builder::Map;
|
||||||
use crate::systems::{
|
use crate::systems::{DeltaTime, DirectionalAnimated, Position, Renderable, ScoreResource, StartupSequence, Velocity};
|
||||||
Blinking, DeltaTime, DirectionalAnimated, EntityType, GhostCollider, PlayerControlled, Position, Renderable, ScoreResource,
|
|
||||||
StartupSequence, Velocity,
|
|
||||||
};
|
|
||||||
use crate::texture::sprite::SpriteAtlas;
|
use crate::texture::sprite::SpriteAtlas;
|
||||||
use crate::texture::text::TextTexture;
|
use crate::texture::text::TextTexture;
|
||||||
|
use bevy_ecs::component::Component;
|
||||||
use bevy_ecs::entity::Entity;
|
use bevy_ecs::entity::Entity;
|
||||||
use bevy_ecs::event::EventWriter;
|
use bevy_ecs::event::EventWriter;
|
||||||
use bevy_ecs::query::{Changed, Or, With, Without};
|
use bevy_ecs::query::{Changed, Or, 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::{NonSendMut, Query, Res, ResMut};
|
||||||
@@ -21,6 +19,9 @@ use sdl2::video::Window;
|
|||||||
#[derive(Resource, Default)]
|
#[derive(Resource, Default)]
|
||||||
pub struct RenderDirty(pub bool);
|
pub struct RenderDirty(pub bool);
|
||||||
|
|
||||||
|
#[derive(Component)]
|
||||||
|
pub struct Hidden;
|
||||||
|
|
||||||
#[allow(clippy::type_complexity)]
|
#[allow(clippy::type_complexity)]
|
||||||
pub fn dirty_render_system(
|
pub fn dirty_render_system(
|
||||||
mut dirty: ResMut<RenderDirty>,
|
mut dirty: ResMut<RenderDirty>,
|
||||||
@@ -71,56 +72,6 @@ pub struct MapTextureResource(pub Texture<'static>);
|
|||||||
/// A non-send resource for the backbuffer 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 backbuffer texture. This just wraps the texture with a type so it can be differentiated when exposed as a resource.
|
||||||
pub struct BackbufferResource(pub Texture<'static>);
|
pub struct BackbufferResource(pub Texture<'static>);
|
||||||
|
|
||||||
/// Updates entity visibility based on StartupSequence stages
|
|
||||||
pub fn ready_visibility_system(
|
|
||||||
startup: Res<StartupSequence>,
|
|
||||||
mut player_query: Query<&mut Renderable, (With<PlayerControlled>, Without<GhostCollider>)>,
|
|
||||||
mut ghost_query: Query<&mut Renderable, (With<GhostCollider>, Without<PlayerControlled>)>,
|
|
||||||
mut energizer_query: Query<(&mut Blinking, &EntityType)>,
|
|
||||||
) {
|
|
||||||
match *startup {
|
|
||||||
StartupSequence::TextOnly { .. } => {
|
|
||||||
// Hide player and ghosts, disable energizer blinking
|
|
||||||
if let Ok(mut renderable) = player_query.single_mut() {
|
|
||||||
renderable.visible = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
for mut renderable in ghost_query.iter_mut() {
|
|
||||||
renderable.visible = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Disable energizer blinking in text-only stage
|
|
||||||
for (mut blinking, entity_type) in energizer_query.iter_mut() {
|
|
||||||
if matches!(entity_type, EntityType::PowerPellet) {
|
|
||||||
blinking.timer = 0.0; // Reset timer to prevent blinking
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
StartupSequence::CharactersVisible { .. } => {
|
|
||||||
// Show player and ghosts, enable energizer blinking
|
|
||||||
if let Ok(mut renderable) = player_query.single_mut() {
|
|
||||||
renderable.visible = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
for mut renderable in ghost_query.iter_mut() {
|
|
||||||
renderable.visible = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Energizer blinking is handled by the blinking system
|
|
||||||
}
|
|
||||||
StartupSequence::GameActive => {
|
|
||||||
// All entities are visible and blinking is normal
|
|
||||||
if let Ok(mut renderable) = player_query.single_mut() {
|
|
||||||
renderable.visible = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
for mut renderable in ghost_query.iter_mut() {
|
|
||||||
renderable.visible = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Renders the HUD (score, lives, etc.) on top of the game.
|
/// Renders the HUD (score, lives, etc.) on top of the game.
|
||||||
pub fn hud_render_system(
|
pub fn hud_render_system(
|
||||||
mut canvas: NonSendMut<&mut Canvas<Window>>,
|
mut canvas: NonSendMut<&mut Canvas<Window>>,
|
||||||
@@ -183,7 +134,7 @@ pub fn render_system(
|
|||||||
mut atlas: NonSendMut<SpriteAtlas>,
|
mut atlas: NonSendMut<SpriteAtlas>,
|
||||||
map: Res<Map>,
|
map: Res<Map>,
|
||||||
dirty: Res<RenderDirty>,
|
dirty: Res<RenderDirty>,
|
||||||
renderables: Query<(Entity, &Renderable, &Position)>,
|
renderables: Query<(Entity, &Renderable, &Position), Without<Hidden>>,
|
||||||
mut errors: EventWriter<GameError>,
|
mut errors: EventWriter<GameError>,
|
||||||
) {
|
) {
|
||||||
if !dirty.0 {
|
if !dirty.0 {
|
||||||
@@ -207,10 +158,6 @@ pub fn render_system(
|
|||||||
.sort_by_key::<(Entity, &Renderable, &Position), _>(|(_, renderable, _)| renderable.layer)
|
.sort_by_key::<(Entity, &Renderable, &Position), _>(|(_, renderable, _)| renderable.layer)
|
||||||
.rev()
|
.rev()
|
||||||
{
|
{
|
||||||
if !renderable.visible {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
let pos = position.get_pixel_position(&map.graph);
|
let pos = position.get_pixel_position(&map.graph);
|
||||||
match pos {
|
match pos {
|
||||||
Ok(pos) => {
|
Ok(pos) => {
|
||||||
|
|||||||
@@ -4,8 +4,9 @@ use bevy_ecs::{
|
|||||||
resource::Resource,
|
resource::Resource,
|
||||||
system::{Commands, Query, ResMut},
|
system::{Commands, Query, ResMut},
|
||||||
};
|
};
|
||||||
|
use tracing::debug;
|
||||||
|
|
||||||
use crate::systems::{Frozen, GhostCollider, PlayerControlled};
|
use crate::systems::{Frozen, GhostCollider, Hidden, PlayerControlled};
|
||||||
|
|
||||||
#[derive(Resource, Debug, Clone, Copy)]
|
#[derive(Resource, Debug, Clone, Copy)]
|
||||||
pub enum StartupSequence {
|
pub enum StartupSequence {
|
||||||
@@ -75,21 +76,14 @@ pub fn startup_stage_system(
|
|||||||
mut ghost_query: Query<Entity, With<GhostCollider>>,
|
mut ghost_query: Query<Entity, With<GhostCollider>>,
|
||||||
) {
|
) {
|
||||||
if let Some((from, to)) = startup.tick() {
|
if let Some((from, to)) = startup.tick() {
|
||||||
|
debug!("StartupSequence transition from {from:?} to {to:?}");
|
||||||
match (from, to) {
|
match (from, to) {
|
||||||
(StartupSequence::TextOnly { .. }, StartupSequence::CharactersVisible { .. }) => {
|
// (StartupSequence::TextOnly { .. }, StartupSequence::CharactersVisible { .. }) => {}
|
||||||
// TODO: Add TextOnly tag component to hide entities
|
|
||||||
// TODO: Add CharactersVisible tag component to show entities
|
|
||||||
// TODO: Remove TextOnly tag component
|
|
||||||
}
|
|
||||||
(StartupSequence::CharactersVisible { .. }, StartupSequence::GameActive) => {
|
(StartupSequence::CharactersVisible { .. }, StartupSequence::GameActive) => {
|
||||||
// Remove Frozen tag from all entities and enable player input
|
// Remove Frozen/Hidden tags from all entities and enable player input
|
||||||
for entity in player_query.iter_mut().chain(ghost_query.iter_mut()) {
|
for entity in player_query.iter_mut().chain(ghost_query.iter_mut()) {
|
||||||
tracing::info!("Removing Frozen component from entity {}", entity);
|
commands.entity(entity).remove::<(Frozen, Hidden)>();
|
||||||
commands.entity(entity).remove::<Frozen>();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Add GameActive tag component
|
|
||||||
// TODO: Remove CharactersVisible tag component
|
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use pacman::systems::formatting::format_timing_display;
|
use pacman::systems::profiling::format_timing_display;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use pretty_assertions::assert_eq;
|
use pretty_assertions::assert_eq;
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ use pacman::{
|
|||||||
},
|
},
|
||||||
systems::{
|
systems::{
|
||||||
can_traverse, player_control_system, player_movement_system, AudioState, BufferedDirection, DebugState, DeltaTime,
|
can_traverse, player_control_system, player_movement_system, AudioState, BufferedDirection, DebugState, DeltaTime,
|
||||||
EntityType, GlobalState, PlayerControlled, Position, Velocity,
|
EntityType, GlobalState, MovementModifiers, PlayerControlled, Position, Velocity,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -49,6 +49,7 @@ fn spawn_test_player(world: &mut World) -> Entity {
|
|||||||
},
|
},
|
||||||
BufferedDirection::None,
|
BufferedDirection::None,
|
||||||
EntityType::Player,
|
EntityType::Player,
|
||||||
|
MovementModifiers::default(),
|
||||||
))
|
))
|
||||||
.id()
|
.id()
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user