mirror of
https://github.com/Xevion/Pac-Man.git
synced 2025-12-10 14:07:59 -06:00
Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a21459f337 | ||
|
|
b53db3788d | ||
|
|
e1a2e6ab62 |
@@ -33,14 +33,12 @@ pub const BOARD_PIXEL_OFFSET: UVec2 = UVec2::new(BOARD_CELL_OFFSET.x * CELL_SIZE
|
|||||||
|
|
||||||
/// Animation timing constants for ghost state management
|
/// Animation timing constants for ghost state management
|
||||||
pub mod animation {
|
pub mod animation {
|
||||||
/// Normal ghost movement animation speed (frames per second)
|
/// Normal ghost movement animation speed (ticks per frame at 60 ticks/sec)
|
||||||
pub const GHOST_NORMAL_SPEED: f32 = 0.2;
|
pub const GHOST_NORMAL_SPEED: u16 = 12;
|
||||||
/// Eaten ghost (eyes) animation speed (frames per second)
|
/// Eaten ghost (eyes) animation speed (ticks per frame at 60 ticks/sec)
|
||||||
pub const GHOST_EATEN_SPEED: f32 = 0.1;
|
pub const GHOST_EATEN_SPEED: u16 = 6;
|
||||||
/// Frightened ghost animation speed (frames per second)
|
/// Frightened ghost animation speed (ticks per frame at 60 ticks/sec)
|
||||||
pub const GHOST_FRIGHTENED_SPEED: f32 = 0.2;
|
pub const GHOST_FRIGHTENED_SPEED: u16 = 12;
|
||||||
/// Frightened ghost flashing animation speed (frames per second)
|
|
||||||
pub const GHOST_FLASHING_SPEED: f32 = 0.15;
|
|
||||||
|
|
||||||
/// Time in ticks when frightened ghosts start flashing (2 seconds at 60 FPS)
|
/// Time in ticks when frightened ghosts start flashing (2 seconds at 60 FPS)
|
||||||
pub const FRIGHTENED_FLASH_START_TICKS: u32 = 120;
|
pub const FRIGHTENED_FLASH_START_TICKS: u32 = 120;
|
||||||
|
|||||||
@@ -78,9 +78,6 @@ pub enum ParseError {
|
|||||||
/// Errors related to texture operations.
|
/// Errors related to texture operations.
|
||||||
#[derive(thiserror::Error, Debug)]
|
#[derive(thiserror::Error, Debug)]
|
||||||
pub enum TextureError {
|
pub enum TextureError {
|
||||||
#[error("Animated texture error: {0}")]
|
|
||||||
Animated(#[from] AnimatedTextureError),
|
|
||||||
|
|
||||||
#[error("Failed to load texture: {0}")]
|
#[error("Failed to load texture: {0}")]
|
||||||
LoadFailed(String),
|
LoadFailed(String),
|
||||||
|
|
||||||
@@ -94,12 +91,6 @@ pub enum TextureError {
|
|||||||
RenderFailed(String),
|
RenderFailed(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(thiserror::Error, Debug)]
|
|
||||||
pub enum AnimatedTextureError {
|
|
||||||
#[error("Frame duration must be positive, got {0}")]
|
|
||||||
InvalidFrameDuration(f32),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Errors related to entity operations.
|
/// Errors related to entity operations.
|
||||||
#[derive(thiserror::Error, Debug)]
|
#[derive(thiserror::Error, Debug)]
|
||||||
pub enum EntityError {
|
pub enum EntityError {
|
||||||
|
|||||||
327
src/game.rs
327
src/game.rs
@@ -2,25 +2,28 @@
|
|||||||
|
|
||||||
include!(concat!(env!("OUT_DIR"), "/atlas_data.rs"));
|
include!(concat!(env!("OUT_DIR"), "/atlas_data.rs"));
|
||||||
|
|
||||||
use crate::constants::{animation, MapTile, CANVAS_SIZE};
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use crate::constants::{self, animation, MapTile, CANVAS_SIZE};
|
||||||
use crate::error::{GameError, GameResult, TextureError};
|
use crate::error::{GameError, GameResult, TextureError};
|
||||||
use crate::events::GameEvent;
|
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::components::{GhostAnimation, GhostState, LastAnimationState};
|
||||||
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::{self, ghost_collision_system, present_system, Hidden, MovementModifiers, NodeId};
|
use crate::systems::{self, ghost_collision_system, present_system, Hidden, LinearAnimation, MovementModifiers, NodeId};
|
||||||
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,
|
||||||
eaten_ghost_system, ghost_movement_system, ghost_state_animation_system, hud_render_system, item_system, profile,
|
eaten_ghost_system, ghost_movement_system, ghost_state_system, hud_render_system, item_system, linear_render_system, profile,
|
||||||
render_system, AudioEvent, AudioResource, AudioState, BackbufferResource, Collider, DebugFontResource, DebugState,
|
render_system, AudioEvent, AudioResource, AudioState, BackbufferResource, Collider, DebugFontResource, DebugState,
|
||||||
DebugTextureResource, DeltaTime, DirectionalAnimated, EntityType, Frozen, Ghost, GhostAnimationSet, GhostAnimations,
|
DebugTextureResource, DeltaTime, DirectionalAnimation, EntityType, Frozen, Ghost, GhostAnimations, GhostBundle,
|
||||||
GhostBundle, GhostCollider, GlobalState, ItemBundle, ItemCollider, MapTextureResource, PacmanCollider, PlayerBundle,
|
GhostCollider, GlobalState, ItemBundle, ItemCollider, MapTextureResource, PacmanCollider, PlayerBundle, PlayerControlled,
|
||||||
PlayerControlled, Renderable, ScoreResource, StartupSequence, SystemTimings,
|
Renderable, ScoreResource, StartupSequence, SystemTimings,
|
||||||
};
|
};
|
||||||
use crate::texture::animated::AnimatedTexture;
|
use crate::texture::animated::{DirectionalTiles, TileSequence};
|
||||||
use crate::texture::sprite::AtlasTile;
|
use crate::texture::sprite::AtlasTile;
|
||||||
use bevy_ecs::event::EventRegistry;
|
use bevy_ecs::event::EventRegistry;
|
||||||
use bevy_ecs::observer::Trigger;
|
use bevy_ecs::observer::Trigger;
|
||||||
@@ -33,11 +36,9 @@ use sdl2::render::{BlendMode, Canvas, ScaleMode, TextureCreator};
|
|||||||
use sdl2::rwops::RWops;
|
use sdl2::rwops::RWops;
|
||||||
use sdl2::video::{Window, WindowContext};
|
use sdl2::video::{Window, WindowContext};
|
||||||
use sdl2::EventPump;
|
use sdl2::EventPump;
|
||||||
use smallvec::smallvec;
|
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
asset::{get_asset_bytes, Asset},
|
asset::{get_asset_bytes, Asset},
|
||||||
constants,
|
|
||||||
events::GameCommand,
|
events::GameCommand,
|
||||||
map::render::MapRenderer,
|
map::render::MapRenderer,
|
||||||
systems::input::{Bindings, CursorPosition},
|
systems::input::{Bindings, CursorPosition},
|
||||||
@@ -150,30 +151,61 @@ impl Game {
|
|||||||
let map = Map::new(constants::RAW_BOARD)?;
|
let map = Map::new(constants::RAW_BOARD)?;
|
||||||
|
|
||||||
// Create directional animated textures for Pac-Man
|
// Create directional animated textures for Pac-Man
|
||||||
let mut textures = [None, None, None, None];
|
let up_moving_tiles = [
|
||||||
let mut stopped_textures = [None, None, None, None];
|
SpriteAtlas::get_tile(&atlas, "pacman/up_a.png")
|
||||||
for direction in Direction::DIRECTIONS {
|
.ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound("pacman/up_a.png".to_string())))?,
|
||||||
let moving_prefix = match direction {
|
SpriteAtlas::get_tile(&atlas, "pacman/up_b.png")
|
||||||
Direction::Up => "pacman/up",
|
.ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound("pacman/up_b.png".to_string())))?,
|
||||||
Direction::Down => "pacman/down",
|
SpriteAtlas::get_tile(&atlas, "pacman/full.png")
|
||||||
Direction::Left => "pacman/left",
|
.ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound("pacman/full.png".to_string())))?,
|
||||||
Direction::Right => "pacman/right",
|
];
|
||||||
};
|
let down_moving_tiles = [
|
||||||
let moving_tiles = smallvec![
|
SpriteAtlas::get_tile(&atlas, "pacman/down_a.png")
|
||||||
SpriteAtlas::get_tile(&atlas, &format!("{moving_prefix}_a.png"))
|
.ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound("pacman/down_a.png".to_string())))?,
|
||||||
.ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound(format!("{moving_prefix}_a.png"))))?,
|
SpriteAtlas::get_tile(&atlas, "pacman/down_b.png")
|
||||||
SpriteAtlas::get_tile(&atlas, &format!("{moving_prefix}_b.png"))
|
.ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound("pacman/down_b.png".to_string())))?,
|
||||||
.ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound(format!("{moving_prefix}_b.png"))))?,
|
SpriteAtlas::get_tile(&atlas, "pacman/full.png")
|
||||||
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())))?,
|
];
|
||||||
];
|
let left_moving_tiles = [
|
||||||
|
SpriteAtlas::get_tile(&atlas, "pacman/left_a.png")
|
||||||
|
.ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound("pacman/left_a.png".to_string())))?,
|
||||||
|
SpriteAtlas::get_tile(&atlas, "pacman/left_b.png")
|
||||||
|
.ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound("pacman/left_b.png".to_string())))?,
|
||||||
|
SpriteAtlas::get_tile(&atlas, "pacman/full.png")
|
||||||
|
.ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound("pacman/full.png".to_string())))?,
|
||||||
|
];
|
||||||
|
let right_moving_tiles = [
|
||||||
|
SpriteAtlas::get_tile(&atlas, "pacman/right_a.png")
|
||||||
|
.ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound("pacman/right_a.png".to_string())))?,
|
||||||
|
SpriteAtlas::get_tile(&atlas, "pacman/right_b.png")
|
||||||
|
.ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound("pacman/right_b.png".to_string())))?,
|
||||||
|
SpriteAtlas::get_tile(&atlas, "pacman/full.png")
|
||||||
|
.ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound("pacman/full.png".to_string())))?,
|
||||||
|
];
|
||||||
|
|
||||||
let stopped_tiles = smallvec![SpriteAtlas::get_tile(&atlas, &format!("{moving_prefix}_b.png"))
|
let moving_tiles = DirectionalTiles::new(
|
||||||
.ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound(format!("{moving_prefix}_b.png"))))?];
|
TileSequence::new(&up_moving_tiles),
|
||||||
|
TileSequence::new(&down_moving_tiles),
|
||||||
|
TileSequence::new(&left_moving_tiles),
|
||||||
|
TileSequence::new(&right_moving_tiles),
|
||||||
|
);
|
||||||
|
|
||||||
textures[direction.as_usize()] = Some(AnimatedTexture::new(moving_tiles, 0.08)?);
|
let up_stopped_tile = SpriteAtlas::get_tile(&atlas, "pacman/up_b.png")
|
||||||
stopped_textures[direction.as_usize()] = Some(AnimatedTexture::new(stopped_tiles, 0.1)?);
|
.ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound("pacman/up_b.png".to_string())))?;
|
||||||
}
|
let down_stopped_tile = SpriteAtlas::get_tile(&atlas, "pacman/down_b.png")
|
||||||
|
.ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound("pacman/down_b.png".to_string())))?;
|
||||||
|
let left_stopped_tile = SpriteAtlas::get_tile(&atlas, "pacman/left_b.png")
|
||||||
|
.ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound("pacman/left_b.png".to_string())))?;
|
||||||
|
let right_stopped_tile = SpriteAtlas::get_tile(&atlas, "pacman/right_b.png")
|
||||||
|
.ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound("pacman/right_b.png".to_string())))?;
|
||||||
|
|
||||||
|
let stopped_tiles = DirectionalTiles::new(
|
||||||
|
TileSequence::new(&[up_stopped_tile]),
|
||||||
|
TileSequence::new(&[down_stopped_tile]),
|
||||||
|
TileSequence::new(&[left_stopped_tile]),
|
||||||
|
TileSequence::new(&[right_stopped_tile]),
|
||||||
|
);
|
||||||
|
|
||||||
let player = PlayerBundle {
|
let player = PlayerBundle {
|
||||||
player: PlayerControlled,
|
player: PlayerControlled,
|
||||||
@@ -191,10 +223,7 @@ impl Game {
|
|||||||
.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,
|
||||||
},
|
},
|
||||||
directional_animated: DirectionalAnimated {
|
directional_animation: DirectionalAnimation::new(moving_tiles, stopped_tiles, 5),
|
||||||
textures,
|
|
||||||
stopped_textures,
|
|
||||||
},
|
|
||||||
entity_type: EntityType::Player,
|
entity_type: EntityType::Player,
|
||||||
collider: Collider {
|
collider: Collider {
|
||||||
size: constants::CELL_SIZE as f32 * 1.375,
|
size: constants::CELL_SIZE as f32 * 1.375,
|
||||||
@@ -247,17 +276,18 @@ impl Game {
|
|||||||
let ghost_movement_system = profile(SystemId::Ghost, ghost_movement_system);
|
let ghost_movement_system = profile(SystemId::Ghost, ghost_movement_system);
|
||||||
let collision_system = profile(SystemId::Collision, collision_system);
|
let collision_system = profile(SystemId::Collision, collision_system);
|
||||||
let ghost_collision_system = profile(SystemId::GhostCollision, ghost_collision_system);
|
let ghost_collision_system = profile(SystemId::GhostCollision, ghost_collision_system);
|
||||||
let vulnerable_tick_system = profile(SystemId::Ghost, systems::vulnerable_tick_system);
|
|
||||||
let item_system = profile(SystemId::Item, item_system);
|
let item_system = profile(SystemId::Item, item_system);
|
||||||
let audio_system = profile(SystemId::Audio, audio_system);
|
let audio_system = profile(SystemId::Audio, audio_system);
|
||||||
let blinking_system = profile(SystemId::Blinking, blinking_system);
|
let blinking_system = profile(SystemId::Blinking, blinking_system);
|
||||||
let directional_render_system = profile(SystemId::DirectionalRender, directional_render_system);
|
let directional_render_system = profile(SystemId::DirectionalRender, directional_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 render_system = profile(SystemId::Render, render_system);
|
let render_system = profile(SystemId::Render, render_system);
|
||||||
let hud_render_system = profile(SystemId::HudRender, hud_render_system);
|
let hud_render_system = profile(SystemId::HudRender, hud_render_system);
|
||||||
let debug_render_system = profile(SystemId::DebugRender, debug_render_system);
|
let debug_render_system = profile(SystemId::DebugRender, debug_render_system);
|
||||||
let present_system = profile(SystemId::Present, present_system);
|
let present_system = profile(SystemId::Present, present_system);
|
||||||
let ghost_state_animation_system = profile(SystemId::GhostStateAnimation, ghost_state_animation_system);
|
let unified_ghost_state_system = profile(SystemId::GhostStateAnimation, ghost_state_system);
|
||||||
|
|
||||||
let forced_dirty_system = |mut dirty: ResMut<RenderDirty>| {
|
let forced_dirty_system = |mut dirty: ResMut<RenderDirty>| {
|
||||||
dirty.0 = true;
|
dirty.0 = true;
|
||||||
@@ -275,13 +305,13 @@ impl Game {
|
|||||||
player_tunnel_slowdown_system,
|
player_tunnel_slowdown_system,
|
||||||
ghost_movement_system,
|
ghost_movement_system,
|
||||||
profile(SystemId::EatenGhost, eaten_ghost_system),
|
profile(SystemId::EatenGhost, eaten_ghost_system),
|
||||||
vulnerable_tick_system,
|
unified_ghost_state_system,
|
||||||
ghost_state_animation_system,
|
|
||||||
(collision_system, ghost_collision_system, item_system).chain(),
|
(collision_system, ghost_collision_system, item_system).chain(),
|
||||||
audio_system,
|
audio_system,
|
||||||
blinking_system,
|
blinking_system,
|
||||||
(
|
(
|
||||||
directional_render_system,
|
directional_render_system,
|
||||||
|
linear_render_system,
|
||||||
dirty_render_system,
|
dirty_render_system,
|
||||||
render_system,
|
render_system,
|
||||||
hud_render_system,
|
hud_render_system,
|
||||||
@@ -358,7 +388,7 @@ impl Game {
|
|||||||
for (ghost_type, start_node) in ghost_start_positions {
|
for (ghost_type, start_node) in ghost_start_positions {
|
||||||
// Create the ghost bundle in a separate scope to manage borrows
|
// Create the ghost bundle in a separate scope to manage borrows
|
||||||
let ghost = {
|
let ghost = {
|
||||||
let animations = world.resource::<GhostAnimations>().0.get(&ghost_type).unwrap().clone();
|
let animations = *world.resource::<GhostAnimations>().get_normal(&ghost_type).unwrap();
|
||||||
let atlas = world.non_send_resource::<SpriteAtlas>();
|
let atlas = world.non_send_resource::<SpriteAtlas>();
|
||||||
|
|
||||||
GhostBundle {
|
GhostBundle {
|
||||||
@@ -379,12 +409,14 @@ impl Game {
|
|||||||
)?,
|
)?,
|
||||||
layer: 0,
|
layer: 0,
|
||||||
},
|
},
|
||||||
directional_animated: animations.normal().unwrap().clone(),
|
directional_animation: animations,
|
||||||
entity_type: EntityType::Ghost,
|
entity_type: EntityType::Ghost,
|
||||||
collider: Collider {
|
collider: Collider {
|
||||||
size: crate::constants::CELL_SIZE as f32 * 1.375,
|
size: constants::CELL_SIZE as f32 * 1.375,
|
||||||
},
|
},
|
||||||
ghost_collider: GhostCollider,
|
ghost_collider: GhostCollider,
|
||||||
|
ghost_state: GhostState::Normal,
|
||||||
|
last_animation_state: LastAnimationState(GhostAnimation::Normal),
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -395,103 +427,144 @@ impl Game {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn create_ghost_animations(atlas: &SpriteAtlas) -> GameResult<GhostAnimations> {
|
fn create_ghost_animations(atlas: &SpriteAtlas) -> GameResult<GhostAnimations> {
|
||||||
let mut animations = std::collections::HashMap::new();
|
// Eaten (eyes) animations - single tile per direction
|
||||||
|
let up_eye = atlas
|
||||||
|
.get_tile("ghost/eyes/up.png")
|
||||||
|
.ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound("ghost/eyes/up.png".to_string())))?;
|
||||||
|
let down_eye = atlas
|
||||||
|
.get_tile("ghost/eyes/down.png")
|
||||||
|
.ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound("ghost/eyes/down.png".to_string())))?;
|
||||||
|
let left_eye = atlas
|
||||||
|
.get_tile("ghost/eyes/left.png")
|
||||||
|
.ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound("ghost/eyes/left.png".to_string())))?;
|
||||||
|
let right_eye = atlas
|
||||||
|
.get_tile("ghost/eyes/right.png")
|
||||||
|
.ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound("ghost/eyes/right.png".to_string())))?;
|
||||||
|
|
||||||
|
let eyes_tiles = DirectionalTiles::new(
|
||||||
|
TileSequence::new(&[up_eye]),
|
||||||
|
TileSequence::new(&[down_eye]),
|
||||||
|
TileSequence::new(&[left_eye]),
|
||||||
|
TileSequence::new(&[right_eye]),
|
||||||
|
);
|
||||||
|
let eyes = DirectionalAnimation::new(eyes_tiles, eyes_tiles, animation::GHOST_EATEN_SPEED);
|
||||||
|
|
||||||
|
let mut animations = HashMap::new();
|
||||||
|
|
||||||
for ghost_type in [Ghost::Blinky, Ghost::Pinky, Ghost::Inky, Ghost::Clyde] {
|
for ghost_type in [Ghost::Blinky, Ghost::Pinky, Ghost::Inky, Ghost::Clyde] {
|
||||||
// Normal animations
|
// Normal animations - create directional tiles for each direction
|
||||||
let mut normal_textures = [None, None, None, None];
|
let up_tiles = [
|
||||||
for direction in Direction::DIRECTIONS {
|
atlas
|
||||||
let dir_str = direction.as_ref();
|
.get_tile(&format!("ghost/{}/up_a.png", ghost_type.as_str()))
|
||||||
let tile_a = atlas
|
|
||||||
.get_tile(&format!("ghost/{}/{}_a.png", ghost_type.as_str(), dir_str))
|
|
||||||
.ok_or_else(|| {
|
.ok_or_else(|| {
|
||||||
GameError::Texture(TextureError::AtlasTileNotFound(format!(
|
GameError::Texture(TextureError::AtlasTileNotFound(format!(
|
||||||
"ghost/{}/{}_a.png",
|
"ghost/{}/up_a.png",
|
||||||
ghost_type.as_str(),
|
ghost_type.as_str()
|
||||||
dir_str
|
|
||||||
)))
|
)))
|
||||||
})?;
|
})?,
|
||||||
let tile_b = atlas
|
atlas
|
||||||
.get_tile(&format!("ghost/{}/{}_b.png", ghost_type.as_str(), dir_str))
|
.get_tile(&format!("ghost/{}/up_b.png", ghost_type.as_str()))
|
||||||
.ok_or_else(|| {
|
.ok_or_else(|| {
|
||||||
GameError::Texture(TextureError::AtlasTileNotFound(format!(
|
GameError::Texture(TextureError::AtlasTileNotFound(format!(
|
||||||
"ghost/{}/{}_b.png",
|
"ghost/{}/up_b.png",
|
||||||
ghost_type.as_str(),
|
ghost_type.as_str()
|
||||||
dir_str
|
|
||||||
)))
|
)))
|
||||||
})?;
|
})?,
|
||||||
let tiles = smallvec![tile_a, tile_b];
|
];
|
||||||
normal_textures[direction.as_usize()] = Some(AnimatedTexture::new(tiles, animation::GHOST_NORMAL_SPEED)?);
|
let down_tiles = [
|
||||||
}
|
atlas
|
||||||
let normal = DirectionalAnimated {
|
.get_tile(&format!("ghost/{}/down_a.png", ghost_type.as_str()))
|
||||||
textures: normal_textures.clone(),
|
.ok_or_else(|| {
|
||||||
stopped_textures: normal_textures,
|
GameError::Texture(TextureError::AtlasTileNotFound(format!(
|
||||||
};
|
"ghost/{}/down_a.png",
|
||||||
|
ghost_type.as_str()
|
||||||
|
)))
|
||||||
|
})?,
|
||||||
|
atlas
|
||||||
|
.get_tile(&format!("ghost/{}/down_b.png", ghost_type.as_str()))
|
||||||
|
.ok_or_else(|| {
|
||||||
|
GameError::Texture(TextureError::AtlasTileNotFound(format!(
|
||||||
|
"ghost/{}/down_b.png",
|
||||||
|
ghost_type.as_str()
|
||||||
|
)))
|
||||||
|
})?,
|
||||||
|
];
|
||||||
|
let left_tiles = [
|
||||||
|
atlas
|
||||||
|
.get_tile(&format!("ghost/{}/left_a.png", ghost_type.as_str()))
|
||||||
|
.ok_or_else(|| {
|
||||||
|
GameError::Texture(TextureError::AtlasTileNotFound(format!(
|
||||||
|
"ghost/{}/left_a.png",
|
||||||
|
ghost_type.as_str()
|
||||||
|
)))
|
||||||
|
})?,
|
||||||
|
atlas
|
||||||
|
.get_tile(&format!("ghost/{}/left_b.png", ghost_type.as_str()))
|
||||||
|
.ok_or_else(|| {
|
||||||
|
GameError::Texture(TextureError::AtlasTileNotFound(format!(
|
||||||
|
"ghost/{}/left_b.png",
|
||||||
|
ghost_type.as_str()
|
||||||
|
)))
|
||||||
|
})?,
|
||||||
|
];
|
||||||
|
let right_tiles = [
|
||||||
|
atlas
|
||||||
|
.get_tile(&format!("ghost/{}/right_a.png", ghost_type.as_str()))
|
||||||
|
.ok_or_else(|| {
|
||||||
|
GameError::Texture(TextureError::AtlasTileNotFound(format!(
|
||||||
|
"ghost/{}/right_a.png",
|
||||||
|
ghost_type.as_str()
|
||||||
|
)))
|
||||||
|
})?,
|
||||||
|
atlas
|
||||||
|
.get_tile(&format!("ghost/{}/right_b.png", ghost_type.as_str()))
|
||||||
|
.ok_or_else(|| {
|
||||||
|
GameError::Texture(TextureError::AtlasTileNotFound(format!(
|
||||||
|
"ghost/{}/right_b.png",
|
||||||
|
ghost_type.as_str()
|
||||||
|
)))
|
||||||
|
})?,
|
||||||
|
];
|
||||||
|
|
||||||
// Eaten (eyes) animations
|
let normal_moving = DirectionalTiles::new(
|
||||||
let mut eaten_textures = [None, None, None, None];
|
TileSequence::new(&up_tiles),
|
||||||
for direction in Direction::DIRECTIONS {
|
TileSequence::new(&down_tiles),
|
||||||
let dir_str = direction.as_ref();
|
TileSequence::new(&left_tiles),
|
||||||
let tile = atlas
|
TileSequence::new(&right_tiles),
|
||||||
.get_tile(&format!("ghost/eyes/{}.png", dir_str))
|
);
|
||||||
.ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound(format!("ghost/eyes/{}.png", dir_str))))?;
|
let normal = DirectionalAnimation::new(normal_moving, normal_moving, animation::GHOST_NORMAL_SPEED);
|
||||||
eaten_textures[direction.as_usize()] = Some(AnimatedTexture::new(smallvec![tile], animation::GHOST_EATEN_SPEED)?);
|
|
||||||
}
|
|
||||||
let eaten = DirectionalAnimated {
|
|
||||||
textures: eaten_textures.clone(),
|
|
||||||
stopped_textures: eaten_textures,
|
|
||||||
};
|
|
||||||
|
|
||||||
animations.insert(
|
animations.insert(ghost_type, normal);
|
||||||
ghost_type,
|
}
|
||||||
GhostAnimationSet::new(
|
|
||||||
normal,
|
let (frightened, frightened_flashing) = {
|
||||||
DirectionalAnimated::default(), // Placeholder for frightened
|
// Load frightened animation tiles (same for all ghosts)
|
||||||
DirectionalAnimated::default(), // Placeholder for frightened_flashing
|
let frightened_blue_a = atlas
|
||||||
eaten,
|
.get_tile("ghost/frightened/blue_a.png")
|
||||||
|
.ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound("ghost/frightened/blue_a.png".to_string())))?;
|
||||||
|
let frightened_blue_b = atlas
|
||||||
|
.get_tile("ghost/frightened/blue_b.png")
|
||||||
|
.ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound("ghost/frightened/blue_b.png".to_string())))?;
|
||||||
|
let frightened_white_a = atlas
|
||||||
|
.get_tile("ghost/frightened/white_a.png")
|
||||||
|
.ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound("ghost/frightened/white_a.png".to_string())))?;
|
||||||
|
let frightened_white_b = atlas
|
||||||
|
.get_tile("ghost/frightened/white_b.png")
|
||||||
|
.ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound("ghost/frightened/white_b.png".to_string())))?;
|
||||||
|
|
||||||
|
(
|
||||||
|
LinearAnimation::new(
|
||||||
|
TileSequence::new(&[frightened_blue_a, frightened_blue_b]),
|
||||||
|
animation::GHOST_NORMAL_SPEED,
|
||||||
),
|
),
|
||||||
);
|
LinearAnimation::new(
|
||||||
}
|
TileSequence::new(&[frightened_blue_a, frightened_white_a, frightened_blue_b, frightened_white_b]),
|
||||||
|
animation::GHOST_FRIGHTENED_SPEED,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
// Frightened animations (same for all ghosts)
|
Ok(GhostAnimations::new(animations, eyes, frightened, frightened_flashing))
|
||||||
let frightened_blue_a = atlas
|
|
||||||
.get_tile("ghost/frightened/blue_a.png")
|
|
||||||
.ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound("ghost/frightened/blue_a.png".to_string())))?;
|
|
||||||
let frightened_blue_b = atlas
|
|
||||||
.get_tile("ghost/frightened/blue_b.png")
|
|
||||||
.ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound("ghost/frightened/blue_b.png".to_string())))?;
|
|
||||||
let frightened_white_a = atlas
|
|
||||||
.get_tile("ghost/frightened/white_a.png")
|
|
||||||
.ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound("ghost/frightened/white_a.png".to_string())))?;
|
|
||||||
let frightened_white_b = atlas
|
|
||||||
.get_tile("ghost/frightened/white_b.png")
|
|
||||||
.ok_or_else(|| GameError::Texture(TextureError::AtlasTileNotFound("ghost/frightened/white_b.png".to_string())))?;
|
|
||||||
|
|
||||||
let frightened_anim = AnimatedTexture::new(
|
|
||||||
smallvec![frightened_blue_a, frightened_blue_b],
|
|
||||||
animation::GHOST_FRIGHTENED_SPEED,
|
|
||||||
)?;
|
|
||||||
let flashing_anim = AnimatedTexture::new(
|
|
||||||
smallvec![frightened_blue_a, frightened_white_a, frightened_blue_b, frightened_white_b],
|
|
||||||
animation::GHOST_FLASHING_SPEED,
|
|
||||||
)?;
|
|
||||||
|
|
||||||
let frightened_da = DirectionalAnimated::from_animation(frightened_anim);
|
|
||||||
let frightened_flashing_da = DirectionalAnimated::from_animation(flashing_anim);
|
|
||||||
|
|
||||||
for ghost_type in [Ghost::Blinky, Ghost::Pinky, Ghost::Inky, Ghost::Clyde] {
|
|
||||||
let entry = animations.get_mut(&ghost_type).unwrap();
|
|
||||||
entry.animations.insert(
|
|
||||||
crate::systems::GhostAnimation::Frightened { flash: false },
|
|
||||||
frightened_da.clone(),
|
|
||||||
);
|
|
||||||
entry.animations.insert(
|
|
||||||
crate::systems::GhostAnimation::Frightened { flash: true },
|
|
||||||
frightened_flashing_da.clone(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(GhostAnimations(animations))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Executes one frame of game logic by running all scheduled ECS systems.
|
/// Executes one frame of game logic by running all scheduled ECS systems.
|
||||||
|
|||||||
@@ -2,13 +2,13 @@ use bevy_ecs::component::Component;
|
|||||||
use bevy_ecs::entity::Entity;
|
use bevy_ecs::entity::Entity;
|
||||||
use bevy_ecs::event::{EventReader, EventWriter};
|
use bevy_ecs::event::{EventReader, EventWriter};
|
||||||
use bevy_ecs::query::With;
|
use bevy_ecs::query::With;
|
||||||
use bevy_ecs::system::{Commands, Query, Res, ResMut};
|
use bevy_ecs::system::{Query, Res, ResMut};
|
||||||
|
|
||||||
use crate::error::GameError;
|
use crate::error::GameError;
|
||||||
use crate::events::GameEvent;
|
use crate::events::GameEvent;
|
||||||
use crate::map::builder::Map;
|
use crate::map::builder::Map;
|
||||||
use crate::systems::movement::Position;
|
use crate::systems::movement::Position;
|
||||||
use crate::systems::{AudioEvent, Eaten, Ghost, PlayerControlled, ScoreResource, Vulnerable};
|
use crate::systems::{AudioEvent, Ghost, GhostState, PlayerControlled, ScoreResource};
|
||||||
|
|
||||||
#[derive(Component)]
|
#[derive(Component)]
|
||||||
pub struct Collider {
|
pub struct Collider {
|
||||||
@@ -108,12 +108,11 @@ pub fn collision_system(
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn ghost_collision_system(
|
pub fn ghost_collision_system(
|
||||||
mut commands: Commands,
|
|
||||||
mut collision_events: EventReader<GameEvent>,
|
mut collision_events: EventReader<GameEvent>,
|
||||||
mut score: ResMut<ScoreResource>,
|
mut score: ResMut<ScoreResource>,
|
||||||
pacman_query: Query<(), With<PlayerControlled>>,
|
pacman_query: Query<(), With<PlayerControlled>>,
|
||||||
ghost_query: Query<(Entity, &Ghost), With<GhostCollider>>,
|
ghost_query: Query<(Entity, &Ghost), With<GhostCollider>>,
|
||||||
vulnerable_query: Query<Entity, With<Vulnerable>>,
|
mut ghost_state_query: Query<&mut GhostState>,
|
||||||
mut events: EventWriter<AudioEvent>,
|
mut events: EventWriter<AudioEvent>,
|
||||||
) {
|
) {
|
||||||
for event in collision_events.read() {
|
for event in collision_events.read() {
|
||||||
@@ -127,23 +126,25 @@ pub fn ghost_collision_system(
|
|||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Check if the ghost is vulnerable
|
// Check if the ghost is frightened
|
||||||
if let Ok((ghost_ent, _ghost_type)) = ghost_query.get(ghost_entity) {
|
if let Ok((ghost_ent, _ghost_type)) = ghost_query.get(ghost_entity) {
|
||||||
// Check if ghost has Vulnerable component
|
if let Ok(mut ghost_state) = ghost_state_query.get_mut(ghost_ent) {
|
||||||
if vulnerable_query.get(ghost_ent).is_ok() {
|
// Check if ghost is in frightened state
|
||||||
// Pac-Man eats the ghost
|
if matches!(*ghost_state, GhostState::Frightened { .. }) {
|
||||||
// Add score (200 points per ghost eaten)
|
// Pac-Man eats the ghost
|
||||||
score.0 += 200;
|
// Add score (200 points per ghost eaten)
|
||||||
|
score.0 += 200;
|
||||||
|
|
||||||
// Remove the ghost
|
// Set ghost state to Eyes
|
||||||
commands.entity(ghost_ent).remove::<Vulnerable>().insert(Eaten);
|
*ghost_state = GhostState::Eyes;
|
||||||
|
|
||||||
// Play eat sound
|
// Play eat sound
|
||||||
events.write(AudioEvent::PlayEat);
|
events.write(AudioEvent::PlayEat);
|
||||||
} else {
|
} else {
|
||||||
// Pac-Man dies (this would need a death system)
|
// Pac-Man dies (this would need a death system)
|
||||||
// For now, just log it
|
// For now, just log it
|
||||||
tracing::warn!("Pac-Man collided with ghost while not vulnerable!");
|
tracing::warn!("Pac-Man collided with ghost while not frightened!");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
use bevy_ecs::{bundle::Bundle, component::Component, resource::Resource};
|
use bevy_ecs::{bundle::Bundle, component::Component, resource::Resource};
|
||||||
use bitflags::bitflags;
|
use bitflags::bitflags;
|
||||||
|
|
||||||
@@ -7,9 +9,11 @@ use crate::{
|
|||||||
movement::{BufferedDirection, Position, Velocity},
|
movement::{BufferedDirection, Position, Velocity},
|
||||||
Collider, GhostCollider, ItemCollider, PacmanCollider,
|
Collider, GhostCollider, ItemCollider, PacmanCollider,
|
||||||
},
|
},
|
||||||
texture::{animated::AnimatedTexture, sprite::AtlasTile},
|
texture::{
|
||||||
|
animated::{DirectionalTiles, TileSequence},
|
||||||
|
sprite::AtlasTile,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
use micromap::Map;
|
|
||||||
|
|
||||||
/// A tag component for entities that are controlled by the player.
|
/// A tag component for entities that are controlled by the player.
|
||||||
#[derive(Default, Component)]
|
#[derive(Default, Component)]
|
||||||
@@ -96,30 +100,46 @@ pub struct Renderable {
|
|||||||
pub layer: u8,
|
pub layer: u8,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A component for entities that have a directional animated texture.
|
/// Directional animation component with shared timing across all directions
|
||||||
#[derive(Component, Clone, Default)]
|
#[derive(Component, Clone, Copy)]
|
||||||
pub struct DirectionalAnimated {
|
pub struct DirectionalAnimation {
|
||||||
pub textures: [Option<AnimatedTexture>; 4],
|
pub moving_tiles: DirectionalTiles,
|
||||||
pub stopped_textures: [Option<AnimatedTexture>; 4],
|
pub stopped_tiles: DirectionalTiles,
|
||||||
|
pub current_frame: usize,
|
||||||
|
pub time_bank: u16,
|
||||||
|
pub frame_duration: u16,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl DirectionalAnimated {
|
impl DirectionalAnimation {
|
||||||
pub fn from_animation(animation: AnimatedTexture) -> Self {
|
/// Creates a new directional animation with the given tiles and frame duration
|
||||||
// Create 4 copies of the animation - necessary for independent state per direction
|
pub fn new(moving_tiles: DirectionalTiles, stopped_tiles: DirectionalTiles, frame_duration: u16) -> Self {
|
||||||
// This is initialization-time only, so the cloning cost is acceptable
|
|
||||||
Self {
|
Self {
|
||||||
textures: [
|
moving_tiles,
|
||||||
Some(animation.clone()),
|
stopped_tiles,
|
||||||
Some(animation.clone()),
|
current_frame: 0,
|
||||||
Some(animation.clone()),
|
time_bank: 0,
|
||||||
Some(animation.clone()),
|
frame_duration,
|
||||||
],
|
}
|
||||||
stopped_textures: [
|
}
|
||||||
Some(animation.clone()),
|
}
|
||||||
Some(animation.clone()),
|
|
||||||
Some(animation.clone()),
|
/// Linear animation component for non-directional animations (frightened ghosts)
|
||||||
Some(animation),
|
#[derive(Component, Clone, Copy)]
|
||||||
],
|
pub struct LinearAnimation {
|
||||||
|
pub tiles: TileSequence,
|
||||||
|
pub current_frame: usize,
|
||||||
|
pub time_bank: u16,
|
||||||
|
pub frame_duration: u16,
|
||||||
|
}
|
||||||
|
|
||||||
|
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,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -170,10 +190,75 @@ pub struct Frozen;
|
|||||||
#[derive(Component, Debug, Clone, Copy)]
|
#[derive(Component, Debug, Clone, Copy)]
|
||||||
pub struct Eaten;
|
pub struct Eaten;
|
||||||
|
|
||||||
/// Component for ghosts that are vulnerable to Pac-Man
|
|
||||||
#[derive(Component, Debug, Clone, Copy)]
|
#[derive(Component, Debug, Clone, Copy)]
|
||||||
pub struct Vulnerable {
|
pub enum GhostState {
|
||||||
pub remaining_ticks: u32,
|
/// 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.
|
/// Enumeration of different ghost animation states.
|
||||||
@@ -189,58 +274,6 @@ pub enum GhostAnimation {
|
|||||||
Eyes,
|
Eyes,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A complete set of animations for a ghost in different behavioral states.
|
|
||||||
///
|
|
||||||
/// Each ghost maintains animations mapped by their current gameplay state.
|
|
||||||
/// The animation system automatically switches between these states based on
|
|
||||||
/// the presence of `Vulnerable` and `Eaten` components on the ghost entity.
|
|
||||||
#[derive(Component, Clone)]
|
|
||||||
pub struct GhostAnimationSet {
|
|
||||||
pub animations: Map<GhostAnimation, DirectionalAnimated, 4>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl GhostAnimationSet {
|
|
||||||
/// Creates a new GhostAnimationSet with the provided animations.
|
|
||||||
pub fn new(
|
|
||||||
normal: DirectionalAnimated,
|
|
||||||
frightened: DirectionalAnimated,
|
|
||||||
frightened_flashing: DirectionalAnimated,
|
|
||||||
eyes: DirectionalAnimated,
|
|
||||||
) -> Self {
|
|
||||||
let mut animations = Map::new();
|
|
||||||
animations.insert(GhostAnimation::Normal, normal);
|
|
||||||
animations.insert(GhostAnimation::Frightened { flash: false }, frightened);
|
|
||||||
animations.insert(GhostAnimation::Frightened { flash: true }, frightened_flashing);
|
|
||||||
animations.insert(GhostAnimation::Eyes, eyes);
|
|
||||||
Self { animations }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Gets the animation for the specified ghost animation state.
|
|
||||||
pub fn get(&self, animation: GhostAnimation) -> Option<&DirectionalAnimated> {
|
|
||||||
self.animations.get(&animation)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Gets the normal animation state.
|
|
||||||
pub fn normal(&self) -> Option<&DirectionalAnimated> {
|
|
||||||
self.get(GhostAnimation::Normal)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Gets the frightened animation state (non-flashing).
|
|
||||||
pub fn frightened(&self) -> Option<&DirectionalAnimated> {
|
|
||||||
self.get(GhostAnimation::Frightened { flash: false })
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Gets the frightened flashing animation state.
|
|
||||||
pub fn frightened_flashing(&self) -> Option<&DirectionalAnimated> {
|
|
||||||
self.get(GhostAnimation::Frightened { flash: true })
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Gets the eyes animation state (for eaten ghosts).
|
|
||||||
pub fn eyes(&self) -> Option<&DirectionalAnimated> {
|
|
||||||
self.get(GhostAnimation::Eyes)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Global resource containing pre-loaded animation sets for all ghost types.
|
/// Global resource containing pre-loaded animation sets for all ghost types.
|
||||||
///
|
///
|
||||||
/// This resource is initialized once during game startup and provides O(1) access
|
/// This resource is initialized once during game startup and provides O(1) access
|
||||||
@@ -248,9 +281,50 @@ impl GhostAnimationSet {
|
|||||||
/// to efficiently switch between different ghost states without runtime asset loading.
|
/// to efficiently switch between different ghost states without runtime asset loading.
|
||||||
///
|
///
|
||||||
/// The HashMap is keyed by `Ghost` enum variants (Blinky, Pinky, Inky, Clyde) and
|
/// The HashMap is keyed by `Ghost` enum variants (Blinky, Pinky, Inky, Clyde) and
|
||||||
/// contains complete animation sets mapped by GhostAnimation states.
|
/// contains the normal directional animation for each ghost type.
|
||||||
#[derive(Resource)]
|
#[derive(Resource)]
|
||||||
pub struct GhostAnimations(pub std::collections::HashMap<Ghost, GhostAnimationSet>);
|
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)]
|
#[derive(Bundle)]
|
||||||
pub struct PlayerBundle {
|
pub struct PlayerBundle {
|
||||||
@@ -259,7 +333,7 @@ pub struct PlayerBundle {
|
|||||||
pub velocity: Velocity,
|
pub velocity: Velocity,
|
||||||
pub buffered_direction: BufferedDirection,
|
pub buffered_direction: BufferedDirection,
|
||||||
pub sprite: Renderable,
|
pub sprite: Renderable,
|
||||||
pub directional_animated: DirectionalAnimated,
|
pub directional_animation: DirectionalAnimation,
|
||||||
pub entity_type: EntityType,
|
pub entity_type: EntityType,
|
||||||
pub collider: Collider,
|
pub collider: Collider,
|
||||||
pub movement_modifiers: MovementModifiers,
|
pub movement_modifiers: MovementModifiers,
|
||||||
@@ -281,8 +355,10 @@ pub struct GhostBundle {
|
|||||||
pub position: Position,
|
pub position: Position,
|
||||||
pub velocity: Velocity,
|
pub velocity: Velocity,
|
||||||
pub sprite: Renderable,
|
pub sprite: Renderable,
|
||||||
pub directional_animated: DirectionalAnimated,
|
pub directional_animation: DirectionalAnimation,
|
||||||
pub entity_type: EntityType,
|
pub entity_type: EntityType,
|
||||||
pub collider: Collider,
|
pub collider: Collider,
|
||||||
pub ghost_collider: GhostCollider,
|
pub ghost_collider: GhostCollider,
|
||||||
|
pub ghost_state: GhostState,
|
||||||
|
pub last_animation_state: LastAnimationState,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::systems::components::Frozen;
|
use crate::systems::components::{DirectionalAnimation, Frozen, GhostAnimation, GhostState, LastAnimationState, LinearAnimation};
|
||||||
use crate::{
|
use crate::{
|
||||||
map::{
|
map::{
|
||||||
builder::Map,
|
builder::Map,
|
||||||
@@ -11,15 +11,9 @@ use crate::{
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
use bevy_ecs::{
|
use crate::systems::GhostAnimations;
|
||||||
query::Added,
|
use bevy_ecs::query::Without;
|
||||||
removal_detection::RemovedComponents,
|
use bevy_ecs::system::{Commands, Query, Res};
|
||||||
system::{Commands, Query, Res},
|
|
||||||
};
|
|
||||||
|
|
||||||
use crate::systems::{Eaten, GhostAnimations, Vulnerable};
|
|
||||||
|
|
||||||
use bevy_ecs::query::{With, Without};
|
|
||||||
use rand::rngs::SmallRng;
|
use rand::rngs::SmallRng;
|
||||||
use rand::seq::IndexedRandom;
|
use rand::seq::IndexedRandom;
|
||||||
use rand::SeedableRng;
|
use rand::SeedableRng;
|
||||||
@@ -77,58 +71,6 @@ pub fn ghost_movement_system(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// System that manages ghost animation state transitions based on ghost behavior.
|
|
||||||
///
|
|
||||||
/// This system handles the following animation state changes:
|
|
||||||
/// - When a ghost becomes vulnerable (power pellet eaten): switches to frightened animation
|
|
||||||
/// - When a ghost is eaten by Pac-Man: switches to eaten (eyes) animation
|
|
||||||
/// - When vulnerability ends: switches back to normal animation
|
|
||||||
///
|
|
||||||
/// The system uses ECS change detection to efficiently track state transitions:
|
|
||||||
/// - `Added<Vulnerable>` detects when ghosts become frightened
|
|
||||||
/// - `Added<Eaten>` detects when ghosts are consumed
|
|
||||||
/// - `RemovedComponents<Vulnerable>` detects when fright period ends
|
|
||||||
///
|
|
||||||
/// This ensures smooth visual feedback for gameplay state changes while maintaining
|
|
||||||
/// separation between game logic and animation state.
|
|
||||||
pub fn ghost_state_animation_system(
|
|
||||||
mut commands: Commands,
|
|
||||||
animations: Res<GhostAnimations>,
|
|
||||||
mut vulnerable_added: Query<(bevy_ecs::entity::Entity, &Ghost), Added<Vulnerable>>,
|
|
||||||
mut eaten_added: Query<(bevy_ecs::entity::Entity, &Ghost), Added<Eaten>>,
|
|
||||||
mut vulnerable_removed: RemovedComponents<Vulnerable>,
|
|
||||||
ghosts: Query<&Ghost>,
|
|
||||||
) {
|
|
||||||
// When a ghost becomes vulnerable, switch to the frightened animation
|
|
||||||
for (entity, ghost_type) in vulnerable_added.iter_mut() {
|
|
||||||
if let Some(animation_set) = animations.0.get(ghost_type) {
|
|
||||||
if let Some(animation) = animation_set.frightened() {
|
|
||||||
commands.entity(entity).insert(animation.clone());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// When a ghost is eaten, switch to the eaten animation
|
|
||||||
for (entity, ghost_type) in eaten_added.iter_mut() {
|
|
||||||
if let Some(animation_set) = animations.0.get(ghost_type) {
|
|
||||||
if let Some(animation) = animation_set.eyes() {
|
|
||||||
commands.entity(entity).insert(animation.clone());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// When a ghost is no longer vulnerable, switch back to the normal animation
|
|
||||||
for entity in vulnerable_removed.read() {
|
|
||||||
if let Ok(ghost_type) = ghosts.get(entity) {
|
|
||||||
if let Some(animation_set) = animations.0.get(ghost_type) {
|
|
||||||
if let Some(animation) = animation_set.normal() {
|
|
||||||
commands.entity(entity).insert(animation.clone());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// System that handles eaten ghost behavior and respawn logic.
|
/// System that handles eaten ghost behavior and respawn logic.
|
||||||
///
|
///
|
||||||
/// When a ghost is eaten by Pac-Man, it enters an "eaten" state where:
|
/// When a ghost is eaten by Pac-Man, it enters an "eaten" state where:
|
||||||
@@ -140,11 +82,13 @@ pub fn ghost_state_animation_system(
|
|||||||
pub fn eaten_ghost_system(
|
pub fn eaten_ghost_system(
|
||||||
map: Res<Map>,
|
map: Res<Map>,
|
||||||
delta_time: Res<DeltaTime>,
|
delta_time: Res<DeltaTime>,
|
||||||
animations: Res<GhostAnimations>,
|
mut eaten_ghosts: Query<(&Ghost, &mut Position, &mut Velocity, &mut GhostState)>,
|
||||||
mut commands: Commands,
|
|
||||||
mut eaten_ghosts: Query<(bevy_ecs::entity::Entity, &Ghost, &mut Position, &mut Velocity), With<Eaten>>,
|
|
||||||
) {
|
) {
|
||||||
for (entity, ghost_type, mut position, mut velocity) in eaten_ghosts.iter_mut() {
|
for (ghost_type, mut position, mut velocity, mut ghost_state) in eaten_ghosts.iter_mut() {
|
||||||
|
// Only process ghosts that are in Eyes state
|
||||||
|
if !matches!(*ghost_state, GhostState::Eyes) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
// Set higher speed for eaten ghosts returning to ghost house
|
// Set higher speed for eaten ghosts returning to ghost house
|
||||||
let original_speed = velocity.speed;
|
let original_speed = velocity.speed;
|
||||||
velocity.speed = ghost_type.base_speed() * 2.0; // Move twice as fast when eaten
|
velocity.speed = ghost_type.base_speed() * 2.0; // Move twice as fast when eaten
|
||||||
@@ -172,13 +116,8 @@ pub fn eaten_ghost_system(
|
|||||||
if let Some(_overflow) = position.tick(distance) {
|
if let Some(_overflow) = position.tick(distance) {
|
||||||
// Reached target node, check if we're at ghost house center
|
// Reached target node, check if we're at ghost house center
|
||||||
if to == ghost_house_center {
|
if to == ghost_house_center {
|
||||||
// Respawn the ghost - remove Eaten component and switch to normal animation
|
// Respawn the ghost - set state back to normal
|
||||||
commands.entity(entity).remove::<Eaten>();
|
*ghost_state = GhostState::Normal;
|
||||||
if let Some(animation_set) = animations.0.get(ghost_type) {
|
|
||||||
if let Some(animation) = animation_set.normal() {
|
|
||||||
commands.entity(entity).insert(animation.clone());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Reset to stopped at ghost house center
|
// Reset to stopped at ghost house center
|
||||||
*position = Position::Stopped {
|
*position = Position::Stopped {
|
||||||
node: ghost_house_center,
|
node: ghost_house_center,
|
||||||
@@ -240,3 +179,41 @@ fn find_direction_to_target(
|
|||||||
|
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Unified system that manages ghost state transitions and animations with component swapping
|
||||||
|
pub fn ghost_state_system(
|
||||||
|
mut commands: Commands,
|
||||||
|
animations: Res<GhostAnimations>,
|
||||||
|
mut ghosts: Query<(bevy_ecs::entity::Entity, &Ghost, &mut GhostState, &mut LastAnimationState)>,
|
||||||
|
) {
|
||||||
|
for (entity, ghost_type, mut ghost_state, mut last_animation_state) in ghosts.iter_mut() {
|
||||||
|
// Tick the ghost state to handle internal transitions (like flashing)
|
||||||
|
let _ = ghost_state.tick();
|
||||||
|
|
||||||
|
// Only update animation if the animation state actually changed
|
||||||
|
let current_animation_state = ghost_state.animation_state();
|
||||||
|
if last_animation_state.0 != current_animation_state {
|
||||||
|
match current_animation_state {
|
||||||
|
GhostAnimation::Frightened { flash } => {
|
||||||
|
// Remove DirectionalAnimation, add LinearAnimation
|
||||||
|
commands
|
||||||
|
.entity(entity)
|
||||||
|
.remove::<DirectionalAnimation>()
|
||||||
|
.insert(*animations.frightened(flash));
|
||||||
|
}
|
||||||
|
GhostAnimation::Normal => {
|
||||||
|
// Remove LinearAnimation, add DirectionalAnimation
|
||||||
|
commands
|
||||||
|
.entity(entity)
|
||||||
|
.remove::<LinearAnimation>()
|
||||||
|
.insert(*animations.get_normal(ghost_type).unwrap());
|
||||||
|
}
|
||||||
|
GhostAnimation::Eyes => {
|
||||||
|
// Remove LinearAnimation, add DirectionalAnimation (eyes animation)
|
||||||
|
commands.entity(entity).remove::<LinearAnimation>().insert(*animations.eyes());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
last_animation_state.0 = current_animation_state;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -6,8 +6,9 @@ use bevy_ecs::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
|
constants::animation::FRIGHTENED_FLASH_START_TICKS,
|
||||||
events::GameEvent,
|
events::GameEvent,
|
||||||
systems::{AudioEvent, EntityType, GhostCollider, ItemCollider, PacmanCollider, ScoreResource, Vulnerable},
|
systems::{AudioEvent, EntityType, GhostCollider, GhostState, ItemCollider, PacmanCollider, ScoreResource},
|
||||||
};
|
};
|
||||||
|
|
||||||
/// 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.
|
||||||
@@ -27,7 +28,7 @@ pub fn item_system(
|
|||||||
mut score: ResMut<ScoreResource>,
|
mut score: ResMut<ScoreResource>,
|
||||||
pacman_query: Query<Entity, With<PacmanCollider>>,
|
pacman_query: Query<Entity, With<PacmanCollider>>,
|
||||||
item_query: Query<(Entity, &EntityType), With<ItemCollider>>,
|
item_query: Query<(Entity, &EntityType), With<ItemCollider>>,
|
||||||
ghost_query: Query<Entity, With<GhostCollider>>,
|
mut ghost_query: Query<&mut GhostState, With<GhostCollider>>,
|
||||||
mut events: EventWriter<AudioEvent>,
|
mut events: EventWriter<AudioEvent>,
|
||||||
) {
|
) {
|
||||||
for event in collision_events.read() {
|
for event in collision_events.read() {
|
||||||
@@ -54,16 +55,14 @@ pub fn item_system(
|
|||||||
events.write(AudioEvent::PlayEat);
|
events.write(AudioEvent::PlayEat);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Make ghosts vulnerable when power pellet is collected
|
// Make ghosts frightened 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 = 60 * 5;
|
let total_ticks = 60 * 5; // 5 seconds total
|
||||||
|
|
||||||
// Add Vulnerable component to all ghosts
|
// Set all ghosts to frightened state
|
||||||
for ghost_entity in ghost_query.iter() {
|
for mut ghost_state in ghost_query.iter_mut() {
|
||||||
commands.entity(ghost_entity).insert(Vulnerable {
|
*ghost_state = GhostState::new_frightened(total_ticks, FRIGHTENED_FLASH_START_TICKS);
|
||||||
remaining_ticks: total_ticks,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ pub mod player;
|
|||||||
pub mod profiling;
|
pub mod profiling;
|
||||||
pub mod render;
|
pub mod render;
|
||||||
pub mod stage;
|
pub mod stage;
|
||||||
pub mod vulnerable;
|
|
||||||
|
|
||||||
pub use self::audio::*;
|
pub use self::audio::*;
|
||||||
pub use self::blinking::*;
|
pub use self::blinking::*;
|
||||||
@@ -31,4 +30,3 @@ pub use self::player::*;
|
|||||||
pub use self::profiling::*;
|
pub use self::profiling::*;
|
||||||
pub use self::render::*;
|
pub use self::render::*;
|
||||||
pub use self::stage::*;
|
pub use self::stage::*;
|
||||||
pub use self::vulnerable::*;
|
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ pub enum SystemId {
|
|||||||
Audio,
|
Audio,
|
||||||
Blinking,
|
Blinking,
|
||||||
DirectionalRender,
|
DirectionalRender,
|
||||||
|
LinearRender,
|
||||||
DirtyRender,
|
DirtyRender,
|
||||||
HudRender,
|
HudRender,
|
||||||
Render,
|
Render,
|
||||||
|
|||||||
@@ -2,8 +2,8 @@ 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::{
|
||||||
DebugState, DebugTextureResource, DeltaTime, DirectionalAnimated, Position, Renderable, ScoreResource, StartupSequence,
|
DebugState, DebugTextureResource, DeltaTime, DirectionalAnimation, LinearAnimation, Position, Renderable, ScoreResource,
|
||||||
Velocity,
|
StartupSequence, Velocity,
|
||||||
};
|
};
|
||||||
use crate::texture::sprite::SpriteAtlas;
|
use crate::texture::sprite::SpriteAtlas;
|
||||||
use crate::texture::text::TextTexture;
|
use crate::texture::text::TextTexture;
|
||||||
@@ -37,35 +37,64 @@ pub fn dirty_render_system(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Updates the directional animated texture of an entity.
|
/// Updates directional animated entities with synchronized timing across directions.
|
||||||
///
|
///
|
||||||
/// This runs before the render system so it can update the sprite based on the current direction of travel, as well as whether the entity is moving.
|
/// 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(
|
pub fn directional_render_system(
|
||||||
dt: Res<DeltaTime>,
|
dt: Res<DeltaTime>,
|
||||||
mut renderables: Query<(&Position, &Velocity, &mut DirectionalAnimated, &mut Renderable)>,
|
mut query: Query<(&Position, &Velocity, &mut DirectionalAnimation, &mut Renderable)>,
|
||||||
mut errors: EventWriter<GameError>,
|
|
||||||
) {
|
) {
|
||||||
for (position, velocity, mut texture, mut renderable) in renderables.iter_mut() {
|
let ticks = (dt.0 * 60.0).round() as u16; // Convert from seconds to ticks at 60 ticks/sec
|
||||||
let stopped = matches!(position, Position::Stopped { .. });
|
|
||||||
let current_direction = velocity.direction;
|
|
||||||
|
|
||||||
let texture = if stopped {
|
for (position, velocity, mut anim, mut renderable) in query.iter_mut() {
|
||||||
texture.stopped_textures[current_direction.as_usize()].as_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 {
|
} else {
|
||||||
texture.textures[current_direction.as_usize()].as_mut()
|
anim.moving_tiles.get(velocity.direction)
|
||||||
};
|
};
|
||||||
|
|
||||||
if let Some(texture) = texture {
|
if !tiles.is_empty() {
|
||||||
if !stopped {
|
let new_tile = tiles.get_tile(anim.current_frame);
|
||||||
texture.tick(dt.0);
|
if renderable.sprite != new_tile {
|
||||||
}
|
renderable.sprite = new_tile;
|
||||||
let new_tile = *texture.current_tile();
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Updates linear animated entities (used for non-directional animations like frightened ghosts).
|
||||||
|
///
|
||||||
|
/// This system handles entities that use LinearAnimation component for simple frame cycling.
|
||||||
|
pub fn linear_render_system(dt: Res<DeltaTime>, mut query: Query<(&mut LinearAnimation, &mut Renderable)>) {
|
||||||
|
let ticks = (dt.0 * 60.0).round() as u16; // Convert from seconds to ticks at 60 ticks/sec
|
||||||
|
|
||||||
|
for (mut anim, mut renderable) in query.iter_mut() {
|
||||||
|
// Tick animation
|
||||||
|
anim.time_bank += ticks;
|
||||||
|
while anim.time_bank >= anim.frame_duration {
|
||||||
|
anim.time_bank -= anim.frame_duration;
|
||||||
|
anim.current_frame += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if !anim.tiles.is_empty() {
|
||||||
|
let new_tile = anim.tiles.get_tile(anim.current_frame);
|
||||||
if renderable.sprite != new_tile {
|
if renderable.sprite != new_tile {
|
||||||
renderable.sprite = new_tile;
|
renderable.sprite = new_tile;
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
errors.write(TextureError::RenderFailed("Entity has no texture".to_string()).into());
|
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,33 +0,0 @@
|
|||||||
use bevy_ecs::{
|
|
||||||
query::With,
|
|
||||||
system::{Commands, Query, Res},
|
|
||||||
};
|
|
||||||
|
|
||||||
use crate::constants::animation::FRIGHTENED_FLASH_START_TICKS;
|
|
||||||
use crate::systems::{Ghost, GhostAnimations, GhostCollider, Vulnerable};
|
|
||||||
|
|
||||||
/// System that decrements the remaining_ticks on Vulnerable components and removes them when they reach zero
|
|
||||||
pub fn vulnerable_tick_system(
|
|
||||||
mut commands: Commands,
|
|
||||||
animations: Res<GhostAnimations>,
|
|
||||||
mut vulnerable_query: Query<(bevy_ecs::entity::Entity, &mut Vulnerable, &Ghost), With<GhostCollider>>,
|
|
||||||
) {
|
|
||||||
for (entity, mut vulnerable, ghost_type) in vulnerable_query.iter_mut() {
|
|
||||||
if vulnerable.remaining_ticks > 0 {
|
|
||||||
vulnerable.remaining_ticks -= 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// When 2 seconds are remaining, start flashing
|
|
||||||
if vulnerable.remaining_ticks == FRIGHTENED_FLASH_START_TICKS {
|
|
||||||
if let Some(animation_set) = animations.0.get(ghost_type) {
|
|
||||||
if let Some(animation) = animation_set.frightened_flashing() {
|
|
||||||
commands.entity(entity).insert(animation.clone());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if vulnerable.remaining_ticks == 0 {
|
|
||||||
commands.entity(entity).remove::<Vulnerable>();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,83 +1,73 @@
|
|||||||
use smallvec::SmallVec;
|
use crate::map::direction::Direction;
|
||||||
|
|
||||||
use crate::error::{AnimatedTextureError, GameError, GameResult, TextureError};
|
|
||||||
use crate::texture::sprite::AtlasTile;
|
use crate::texture::sprite::AtlasTile;
|
||||||
|
|
||||||
/// Frame-based animation system for cycling through multiple sprite tiles.
|
/// Fixed-size tile sequence that avoids heap allocation
|
||||||
///
|
#[derive(Clone, Copy, Debug)]
|
||||||
/// Manages automatic frame progression based on elapsed time.
|
pub struct TileSequence {
|
||||||
/// Uses a time banking system to ensure consistent animation speed regardless of frame rate variations.
|
tiles: [AtlasTile; 4], // Fixed array, max 4 frames
|
||||||
#[derive(Debug, Clone)]
|
count: usize, // Actual number of frames used
|
||||||
pub struct AnimatedTexture {
|
|
||||||
/// Sequence of sprite tiles that make up the animation frames
|
|
||||||
tiles: SmallVec<[AtlasTile; 4]>,
|
|
||||||
/// Duration each frame should be displayed (in seconds)
|
|
||||||
frame_duration: f32,
|
|
||||||
/// Index of the currently active frame in the tiles vector
|
|
||||||
current_frame: usize,
|
|
||||||
/// Accumulated time since the last frame change (for smooth timing)
|
|
||||||
time_bank: f32,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AnimatedTexture {
|
impl TileSequence {
|
||||||
pub fn new(tiles: SmallVec<[AtlasTile; 4]>, frame_duration: f32) -> GameResult<Self> {
|
/// Creates a new tile sequence from a slice of tiles
|
||||||
if frame_duration <= 0.0 {
|
pub fn new(tiles: &[AtlasTile]) -> Self {
|
||||||
return Err(GameError::Texture(TextureError::Animated(
|
let mut tile_array = [AtlasTile {
|
||||||
AnimatedTextureError::InvalidFrameDuration(frame_duration),
|
pos: glam::U16Vec2::ZERO,
|
||||||
)));
|
size: glam::U16Vec2::ZERO,
|
||||||
}
|
color: None,
|
||||||
|
}; 4];
|
||||||
|
|
||||||
Ok(Self {
|
let count = tiles.len().min(4);
|
||||||
tiles,
|
tile_array[..count].copy_from_slice(&tiles[..count]);
|
||||||
frame_duration,
|
|
||||||
current_frame: 0,
|
|
||||||
time_bank: 0.0,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Advances the animation by the specified time delta with automatic frame cycling.
|
Self {
|
||||||
///
|
tiles: tile_array,
|
||||||
/// Accumulates time in the time bank and progresses through frames when enough
|
count,
|
||||||
/// time has elapsed. Supports frame rates independent of game frame rate by
|
|
||||||
/// potentially advancing multiple frames in a single call if `dt` is large.
|
|
||||||
/// Animation loops automatically when reaching the final frame.
|
|
||||||
///
|
|
||||||
/// # Arguments
|
|
||||||
///
|
|
||||||
/// * `dt` - Time elapsed since the last tick (typically frame delta time)
|
|
||||||
pub fn tick(&mut self, dt: f32) {
|
|
||||||
self.time_bank += dt;
|
|
||||||
while self.time_bank >= self.frame_duration {
|
|
||||||
self.time_bank -= self.frame_duration;
|
|
||||||
self.current_frame = (self.current_frame + 1) % self.tiles.len();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn current_tile(&self) -> &AtlasTile {
|
/// Returns the tile at the given frame index, wrapping if necessary
|
||||||
&self.tiles[self.current_frame]
|
pub fn get_tile(&self, frame: usize) -> AtlasTile {
|
||||||
|
if self.count == 0 {
|
||||||
|
// Return a default empty tile if no tiles
|
||||||
|
AtlasTile {
|
||||||
|
pos: glam::U16Vec2::ZERO,
|
||||||
|
size: glam::U16Vec2::ZERO,
|
||||||
|
color: None,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
self.tiles[frame % self.count]
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the current frame index.
|
/// Returns true if this sequence has no tiles
|
||||||
#[allow(dead_code)]
|
pub fn is_empty(&self) -> bool {
|
||||||
pub fn current_frame(&self) -> usize {
|
self.count == 0
|
||||||
self.current_frame
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the time bank.
|
/// Type-safe directional tile storage with named fields
|
||||||
#[allow(dead_code)]
|
#[derive(Clone, Copy, Debug)]
|
||||||
pub fn time_bank(&self) -> f32 {
|
pub struct DirectionalTiles {
|
||||||
self.time_bank
|
pub up: TileSequence,
|
||||||
}
|
pub down: TileSequence,
|
||||||
|
pub left: TileSequence,
|
||||||
/// Returns the frame duration.
|
pub right: TileSequence,
|
||||||
#[allow(dead_code)]
|
}
|
||||||
pub fn frame_duration(&self) -> f32 {
|
|
||||||
self.frame_duration
|
impl DirectionalTiles {
|
||||||
}
|
/// Creates a new DirectionalTiles with different sequences per direction
|
||||||
|
pub fn new(up: TileSequence, down: TileSequence, left: TileSequence, right: TileSequence) -> Self {
|
||||||
/// Returns the number of tiles in the animation.
|
Self { up, down, left, right }
|
||||||
#[allow(dead_code)]
|
}
|
||||||
pub fn tiles_len(&self) -> usize {
|
|
||||||
self.tiles.len()
|
/// Gets the tile sequence for the given direction
|
||||||
|
pub fn get(&self, direction: Direction) -> &TileSequence {
|
||||||
|
match direction {
|
||||||
|
Direction::Up => &self.up,
|
||||||
|
Direction::Down => &self.down,
|
||||||
|
Direction::Left => &self.left,
|
||||||
|
Direction::Right => &self.right,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,63 +1,57 @@
|
|||||||
use glam::U16Vec2;
|
// use glam::U16Vec2;
|
||||||
use pacman::error::{AnimatedTextureError, GameError, TextureError};
|
// use pacman::error::{AnimatedTextureError, GameError, TextureError};
|
||||||
use pacman::texture::animated::AnimatedTexture;
|
// use pacman::texture::sprite::AtlasTile;
|
||||||
use pacman::texture::sprite::AtlasTile;
|
// use sdl2::pixels::Color;
|
||||||
use sdl2::pixels::Color;
|
// use smallvec::smallvec;
|
||||||
use smallvec::smallvec;
|
|
||||||
|
|
||||||
fn mock_atlas_tile(id: u32) -> AtlasTile {
|
// fn mock_atlas_tile(id: u32) -> AtlasTile {
|
||||||
AtlasTile {
|
// AtlasTile {
|
||||||
pos: U16Vec2::new(0, 0),
|
// pos: U16Vec2::new(0, 0),
|
||||||
size: U16Vec2::new(16, 16),
|
// size: U16Vec2::new(16, 16),
|
||||||
color: Some(Color::RGB(id as u8, 0, 0)),
|
// color: Some(Color::RGB(id as u8, 0, 0)),
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
|
|
||||||
#[test]
|
// #[test]
|
||||||
fn test_animated_texture_creation_errors() {
|
// fn test_animated_texture_creation_errors() {
|
||||||
let tiles = smallvec![mock_atlas_tile(1), mock_atlas_tile(2)];
|
// let tiles = smallvec![mock_atlas_tile(1), mock_atlas_tile(2)];
|
||||||
|
|
||||||
assert!(matches!(
|
// assert!(matches!(
|
||||||
AnimatedTexture::new(tiles.clone(), 0.0).unwrap_err(),
|
// AnimatedTexture::new(tiles.clone(), 0).unwrap_err(),
|
||||||
GameError::Texture(TextureError::Animated(AnimatedTextureError::InvalidFrameDuration(0.0)))
|
// GameError::Texture(TextureError::Animated(AnimatedTextureError::InvalidFrameDuration(0)))
|
||||||
));
|
// ));
|
||||||
|
// }
|
||||||
|
|
||||||
assert!(matches!(
|
// #[test]
|
||||||
AnimatedTexture::new(tiles, -0.1).unwrap_err(),
|
// fn test_animated_texture_advancement() {
|
||||||
GameError::Texture(TextureError::Animated(AnimatedTextureError::InvalidFrameDuration(-0.1)))
|
// let tiles = smallvec![mock_atlas_tile(1), mock_atlas_tile(2), mock_atlas_tile(3)];
|
||||||
));
|
// let mut texture = AnimatedTexture::new(tiles, 10).unwrap();
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
// assert_eq!(texture.current_frame(), 0);
|
||||||
fn test_animated_texture_advancement() {
|
|
||||||
let tiles = smallvec![mock_atlas_tile(1), mock_atlas_tile(2), mock_atlas_tile(3)];
|
|
||||||
let mut texture = AnimatedTexture::new(tiles, 0.1).unwrap();
|
|
||||||
|
|
||||||
assert_eq!(texture.current_frame(), 0);
|
// texture.tick(25);
|
||||||
|
// assert_eq!(texture.current_frame(), 2);
|
||||||
|
// assert_eq!(texture.time_bank(), 5);
|
||||||
|
// }
|
||||||
|
|
||||||
texture.tick(0.25);
|
// #[test]
|
||||||
assert_eq!(texture.current_frame(), 2);
|
// fn test_animated_texture_wrap_around() {
|
||||||
assert!((texture.time_bank() - 0.05).abs() < 0.001);
|
// let tiles = smallvec![mock_atlas_tile(1), mock_atlas_tile(2)];
|
||||||
}
|
// let mut texture = AnimatedTexture::new(tiles, 10).unwrap();
|
||||||
|
|
||||||
#[test]
|
// texture.tick(10);
|
||||||
fn test_animated_texture_wrap_around() {
|
// assert_eq!(texture.current_frame(), 1);
|
||||||
let tiles = smallvec![mock_atlas_tile(1), mock_atlas_tile(2)];
|
|
||||||
let mut texture = AnimatedTexture::new(tiles, 0.1).unwrap();
|
|
||||||
|
|
||||||
texture.tick(0.1);
|
// texture.tick(10);
|
||||||
assert_eq!(texture.current_frame(), 1);
|
// assert_eq!(texture.current_frame(), 0);
|
||||||
|
// }
|
||||||
|
|
||||||
texture.tick(0.1);
|
// #[test]
|
||||||
assert_eq!(texture.current_frame(), 0);
|
// fn test_animated_texture_single_frame() {
|
||||||
}
|
// let tiles = smallvec![mock_atlas_tile(1)];
|
||||||
|
// let mut texture = AnimatedTexture::new(tiles, 10).unwrap();
|
||||||
|
|
||||||
#[test]
|
// texture.tick(10);
|
||||||
fn test_animated_texture_single_frame() {
|
// assert_eq!(texture.current_frame(), 0);
|
||||||
let tiles = smallvec![mock_atlas_tile(1)];
|
// assert_eq!(texture.current_tile().color.unwrap().r, 1);
|
||||||
let mut texture = AnimatedTexture::new(tiles, 0.1).unwrap();
|
// }
|
||||||
|
|
||||||
texture.tick(0.1);
|
|
||||||
assert_eq!(texture.current_frame(), 0);
|
|
||||||
assert_eq!(texture.current_tile().color.unwrap().r, 1);
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
use pacman::error::{
|
use pacman::error::{
|
||||||
AnimatedTextureError, AssetError, EntityError, GameError, GameResult, IntoGameError, MapError, OptionExt, ParseError,
|
AssetError, EntityError, GameError, GameResult, IntoGameError, MapError, OptionExt, ParseError, ResultExt, TextureError,
|
||||||
ResultExt, TextureError,
|
|
||||||
};
|
};
|
||||||
use std::io;
|
use std::io;
|
||||||
|
|
||||||
@@ -46,13 +45,6 @@ fn test_game_error_from_io_error() {
|
|||||||
assert!(matches!(game_error, GameError::Io(_)));
|
assert!(matches!(game_error, GameError::Io(_)));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_texture_error_from_animated_error() {
|
|
||||||
let animated_error = AnimatedTextureError::InvalidFrameDuration(-1.0);
|
|
||||||
let texture_error: TextureError = animated_error.into();
|
|
||||||
assert!(matches!(texture_error, TextureError::Animated(_)));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_asset_error_from_io_error() {
|
fn test_asset_error_from_io_error() {
|
||||||
let io_error = io::Error::new(io::ErrorKind::PermissionDenied, "Permission denied");
|
let io_error = io::Error::new(io::ErrorKind::PermissionDenied, "Permission denied");
|
||||||
@@ -78,12 +70,6 @@ fn test_entity_error_display() {
|
|||||||
assert_eq!(error.to_string(), "Edge not found: from 1 to 2");
|
assert_eq!(error.to_string(), "Edge not found: from 1 to 2");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_animated_texture_error_display() {
|
|
||||||
let error = AnimatedTextureError::InvalidFrameDuration(0.0);
|
|
||||||
assert_eq!(error.to_string(), "Frame duration must be positive, got 0");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_into_game_error_trait() {
|
fn test_into_game_error_trait() {
|
||||||
let result: Result<i32, io::Error> = Err(io::Error::new(io::ErrorKind::Other, "test error"));
|
let result: Result<i32, io::Error> = Err(io::Error::new(io::ErrorKind::Other, "test error"));
|
||||||
@@ -146,13 +132,3 @@ fn test_result_ext_error() {
|
|||||||
panic!("Expected InvalidState error");
|
panic!("Expected InvalidState error");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_error_chain_conversions() {
|
|
||||||
// Test that we can convert through multiple levels
|
|
||||||
let animated_error = AnimatedTextureError::InvalidFrameDuration(-5.0);
|
|
||||||
let texture_error: TextureError = animated_error.into();
|
|
||||||
let game_error: GameError = texture_error.into();
|
|
||||||
|
|
||||||
assert!(matches!(game_error, GameError::Texture(TextureError::Animated(_))));
|
|
||||||
}
|
|
||||||
|
|||||||
Reference in New Issue
Block a user