mirror of
https://github.com/Xevion/Pac-Man.git
synced 2025-12-10 12:07:56 -06:00
Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5d56b31353 | ||
|
|
b4990af109 | ||
|
|
088c496ad9 |
2
Cargo.lock
generated
2
Cargo.lock
generated
@@ -663,7 +663,7 @@ checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pacman"
|
name = "pacman"
|
||||||
version = "0.78.3"
|
version = "0.78.4"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"bevy_ecs",
|
"bevy_ecs",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "pacman"
|
name = "pacman"
|
||||||
version = "0.78.3"
|
version = "0.78.4"
|
||||||
authors = ["Xevion"]
|
authors = ["Xevion"]
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
rust-version = "1.86.0"
|
rust-version = "1.86.0"
|
||||||
|
|||||||
@@ -79,6 +79,8 @@ pub mod collider {
|
|||||||
pub const PELLET_SIZE: f32 = CELL_SIZE as f32 * 0.4;
|
pub const PELLET_SIZE: f32 = CELL_SIZE as f32 * 0.4;
|
||||||
/// Collider size for power pellets/energizers (0.95x cell size)
|
/// Collider size for power pellets/energizers (0.95x cell size)
|
||||||
pub const POWER_PELLET_SIZE: f32 = CELL_SIZE as f32 * 0.95;
|
pub const POWER_PELLET_SIZE: f32 = CELL_SIZE as f32 * 0.95;
|
||||||
|
/// Collider size for fruits (0.8x cell size)
|
||||||
|
pub const FRUIT_SIZE: f32 = CELL_SIZE as f32 * 1.375;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// UI and rendering constants
|
/// UI and rendering constants
|
||||||
|
|||||||
@@ -42,8 +42,7 @@ use crate::{
|
|||||||
asset::{get_asset_bytes, Asset},
|
asset::{get_asset_bytes, Asset},
|
||||||
events::GameCommand,
|
events::GameCommand,
|
||||||
map::render::MapRenderer,
|
map::render::MapRenderer,
|
||||||
systems::debug::{BatchedLinesResource, TtfAtlasResource},
|
systems::{BatchedLinesResource, Bindings, CursorPosition, TtfAtlasResource},
|
||||||
systems::input::{Bindings, CursorPosition},
|
|
||||||
texture::sprite::{AtlasMapper, SpriteAtlas},
|
texture::sprite::{AtlasMapper, SpriteAtlas},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -128,6 +127,8 @@ impl Game {
|
|||||||
debug!("Setting up ECS event registry and observers");
|
debug!("Setting up ECS event registry and observers");
|
||||||
Self::setup_ecs(&mut world);
|
Self::setup_ecs(&mut world);
|
||||||
|
|
||||||
|
world.add_observer(systems::spawn_fruit_observer);
|
||||||
|
|
||||||
debug!("Inserting resources into ECS world");
|
debug!("Inserting resources into ECS world");
|
||||||
Self::insert_resources(
|
Self::insert_resources(
|
||||||
&mut world,
|
&mut world,
|
||||||
@@ -410,6 +411,7 @@ impl Game {
|
|||||||
world.insert_resource(GlobalState { exit: false });
|
world.insert_resource(GlobalState { exit: false });
|
||||||
world.insert_resource(PlayerLives::default());
|
world.insert_resource(PlayerLives::default());
|
||||||
world.insert_resource(ScoreResource(0));
|
world.insert_resource(ScoreResource(0));
|
||||||
|
world.insert_resource(crate::systems::item::PelletCount(0));
|
||||||
world.insert_resource(SystemTimings::default());
|
world.insert_resource(SystemTimings::default());
|
||||||
world.insert_resource(Timing::default());
|
world.insert_resource(Timing::default());
|
||||||
world.insert_resource(Bindings::default());
|
world.insert_resource(Bindings::default());
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ use crate::constants::{MapTile, BOARD_CELL_SIZE, CELL_SIZE};
|
|||||||
use crate::map::direction::Direction;
|
use crate::map::direction::Direction;
|
||||||
use crate::map::graph::{Graph, Node, TraversalFlags};
|
use crate::map::graph::{Graph, Node, TraversalFlags};
|
||||||
use crate::map::parser::MapTileParser;
|
use crate::map::parser::MapTileParser;
|
||||||
use crate::systems::movement::NodeId;
|
use crate::systems::{NodeId, Position};
|
||||||
use bevy_ecs::resource::Resource;
|
use bevy_ecs::resource::Resource;
|
||||||
use glam::{I8Vec2, IVec2, Vec2};
|
use glam::{I8Vec2, IVec2, Vec2};
|
||||||
use std::collections::{HashMap, VecDeque};
|
use std::collections::{HashMap, VecDeque};
|
||||||
@@ -25,6 +25,8 @@ pub struct NodePositions {
|
|||||||
pub inky: NodeId,
|
pub inky: NodeId,
|
||||||
/// Clyde starts in the center of the ghost house
|
/// Clyde starts in the center of the ghost house
|
||||||
pub clyde: NodeId,
|
pub clyde: NodeId,
|
||||||
|
/// Fruit spawn location directly below the ghost house
|
||||||
|
pub fruit_spawn: Position,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Complete maze representation combining visual layout with navigation pathfinding.
|
/// Complete maze representation combining visual layout with navigation pathfinding.
|
||||||
@@ -154,12 +156,37 @@ impl Map {
|
|||||||
let (house_entrance_node_id, left_center_node_id, center_center_node_id, right_center_node_id) =
|
let (house_entrance_node_id, left_center_node_id, center_center_node_id, right_center_node_id) =
|
||||||
Self::build_house(&mut graph, &grid_to_node, &house_door)?;
|
Self::build_house(&mut graph, &grid_to_node, &house_door)?;
|
||||||
|
|
||||||
|
// Find fruit spawn location (directly below ghost house)
|
||||||
|
let left_node_position = I8Vec2::new(13, 17);
|
||||||
|
let left_node_id = grid_to_node.get(&left_node_position).unwrap();
|
||||||
|
let right_node_position = I8Vec2::new(14, 17);
|
||||||
|
let right_node_id = grid_to_node.get(&right_node_position).unwrap();
|
||||||
|
|
||||||
|
let distance = graph
|
||||||
|
.get_node(*right_node_id)
|
||||||
|
.unwrap()
|
||||||
|
.position
|
||||||
|
.distance(graph.get_node(*left_node_id).unwrap().position);
|
||||||
|
|
||||||
|
// interpolate between the two nodes
|
||||||
|
let fruit_spawn_position: Position = Position::Moving {
|
||||||
|
from: *left_node_id,
|
||||||
|
to: *right_node_id,
|
||||||
|
remaining_distance: distance / 2.0,
|
||||||
|
};
|
||||||
|
|
||||||
|
tracing::warn!(
|
||||||
|
fruit_spawn_position = ?fruit_spawn_position,
|
||||||
|
"Fruit spawn position found"
|
||||||
|
);
|
||||||
|
|
||||||
let start_positions = NodePositions {
|
let start_positions = NodePositions {
|
||||||
pacman: grid_to_node[&start_pos],
|
pacman: grid_to_node[&start_pos],
|
||||||
blinky: house_entrance_node_id,
|
blinky: house_entrance_node_id,
|
||||||
pinky: left_center_node_id,
|
pinky: left_center_node_id,
|
||||||
inky: right_center_node_id,
|
inky: right_center_node_id,
|
||||||
clyde: center_center_node_id,
|
clyde: center_center_node_id,
|
||||||
|
fruit_spawn: fruit_spawn_position,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Build tunnel connections
|
// Build tunnel connections
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use glam::Vec2;
|
use glam::Vec2;
|
||||||
|
|
||||||
use crate::systems::movement::NodeId;
|
use crate::systems::NodeId;
|
||||||
|
|
||||||
use super::direction::Direction;
|
use super::direction::Direction;
|
||||||
|
|
||||||
|
|||||||
132
src/systems/animation.rs
Normal file
132
src/systems/animation.rs
Normal file
@@ -0,0 +1,132 @@
|
|||||||
|
use bevy_ecs::{
|
||||||
|
component::Component,
|
||||||
|
query::{Has, Or, With, Without},
|
||||||
|
resource::Resource,
|
||||||
|
system::{Query, Res},
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
systems::{DeltaTime, Dying, Frozen, Position, Renderable, Velocity},
|
||||||
|
texture::animated::{DirectionalTiles, TileSequence},
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Directional animation component with shared timing across all directions
|
||||||
|
#[derive(Component, Clone)]
|
||||||
|
pub struct DirectionalAnimation {
|
||||||
|
pub moving_tiles: DirectionalTiles,
|
||||||
|
pub stopped_tiles: DirectionalTiles,
|
||||||
|
pub current_frame: usize,
|
||||||
|
pub time_bank: u16,
|
||||||
|
pub frame_duration: u16,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DirectionalAnimation {
|
||||||
|
/// Creates a new directional animation with the given tiles and frame duration
|
||||||
|
pub fn new(moving_tiles: DirectionalTiles, stopped_tiles: DirectionalTiles, frame_duration: u16) -> Self {
|
||||||
|
Self {
|
||||||
|
moving_tiles,
|
||||||
|
stopped_tiles,
|
||||||
|
current_frame: 0,
|
||||||
|
time_bank: 0,
|
||||||
|
frame_duration,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tag component to mark animations that should loop when they reach the end
|
||||||
|
#[derive(Component, Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub struct Looping;
|
||||||
|
|
||||||
|
/// Linear animation component for non-directional animations (frightened ghosts)
|
||||||
|
#[derive(Component, Resource, Clone)]
|
||||||
|
pub struct LinearAnimation {
|
||||||
|
pub tiles: TileSequence,
|
||||||
|
pub current_frame: usize,
|
||||||
|
pub time_bank: u16,
|
||||||
|
pub frame_duration: u16,
|
||||||
|
pub finished: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LinearAnimation {
|
||||||
|
/// Creates a new linear animation with the given tiles and frame duration
|
||||||
|
pub fn new(tiles: TileSequence, frame_duration: u16) -> Self {
|
||||||
|
Self {
|
||||||
|
tiles,
|
||||||
|
current_frame: 0,
|
||||||
|
time_bank: 0,
|
||||||
|
frame_duration,
|
||||||
|
finished: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Updates directional animated entities with synchronized timing across directions.
|
||||||
|
///
|
||||||
|
/// This runs before the render system to update sprites based on current direction and movement state.
|
||||||
|
/// All directions share the same frame timing to ensure perfect synchronization.
|
||||||
|
pub fn directional_render_system(
|
||||||
|
dt: Res<DeltaTime>,
|
||||||
|
mut query: Query<(&Position, &Velocity, &mut DirectionalAnimation, &mut Renderable), Without<Frozen>>,
|
||||||
|
) {
|
||||||
|
let ticks = (dt.seconds * 60.0).round() as u16; // Convert from seconds to ticks at 60 ticks/sec
|
||||||
|
|
||||||
|
for (position, velocity, mut anim, mut renderable) in query.iter_mut() {
|
||||||
|
let stopped = matches!(position, Position::Stopped { .. });
|
||||||
|
|
||||||
|
// Only tick animation when moving to preserve stopped frame
|
||||||
|
if !stopped {
|
||||||
|
// Tick shared animation state
|
||||||
|
anim.time_bank += ticks;
|
||||||
|
while anim.time_bank >= anim.frame_duration {
|
||||||
|
anim.time_bank -= anim.frame_duration;
|
||||||
|
anim.current_frame += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get tiles for current direction and movement state
|
||||||
|
let tiles = if stopped {
|
||||||
|
anim.stopped_tiles.get(velocity.direction)
|
||||||
|
} else {
|
||||||
|
anim.moving_tiles.get(velocity.direction)
|
||||||
|
};
|
||||||
|
|
||||||
|
if !tiles.is_empty() {
|
||||||
|
let new_tile = tiles.get_tile(anim.current_frame);
|
||||||
|
if renderable.sprite != new_tile {
|
||||||
|
renderable.sprite = new_tile;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// System that updates `Renderable` sprites for entities with `LinearAnimation`.
|
||||||
|
#[allow(clippy::type_complexity)]
|
||||||
|
pub fn linear_render_system(
|
||||||
|
dt: Res<DeltaTime>,
|
||||||
|
mut query: Query<(&mut LinearAnimation, &mut Renderable, Has<Looping>), Or<(Without<Frozen>, With<Dying>)>>,
|
||||||
|
) {
|
||||||
|
for (mut anim, mut renderable, looping) in query.iter_mut() {
|
||||||
|
if anim.finished {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
anim.time_bank += dt.ticks as u16;
|
||||||
|
let frames_to_advance = (anim.time_bank / anim.frame_duration) as usize;
|
||||||
|
|
||||||
|
if frames_to_advance == 0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let total_frames = anim.tiles.len();
|
||||||
|
|
||||||
|
if !looping && anim.current_frame + frames_to_advance >= total_frames {
|
||||||
|
anim.finished = true;
|
||||||
|
anim.current_frame = total_frames - 1;
|
||||||
|
} else {
|
||||||
|
anim.current_frame += frames_to_advance;
|
||||||
|
}
|
||||||
|
|
||||||
|
anim.time_bank %= anim.frame_duration;
|
||||||
|
renderable.sprite = anim.tiles.get_tile(anim.current_frame);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,10 +5,7 @@ use bevy_ecs::{
|
|||||||
system::{Commands, Query, Res},
|
system::{Commands, Query, Res},
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::systems::{
|
use crate::systems::{DeltaTime, Frozen, Hidden, Renderable};
|
||||||
components::{DeltaTime, Renderable},
|
|
||||||
Frozen, Hidden,
|
|
||||||
};
|
|
||||||
|
|
||||||
#[derive(Component, Debug)]
|
#[derive(Component, Debug)]
|
||||||
pub struct Blinking {
|
pub struct Blinking {
|
||||||
|
|||||||
@@ -7,13 +7,10 @@ use bevy_ecs::{
|
|||||||
};
|
};
|
||||||
use tracing::{debug, trace, warn};
|
use tracing::{debug, trace, warn};
|
||||||
|
|
||||||
use crate::error::GameError;
|
|
||||||
use crate::events::{GameEvent, StageTransition};
|
use crate::events::{GameEvent, StageTransition};
|
||||||
use crate::map::builder::Map;
|
use crate::map::builder::Map;
|
||||||
use crate::systems::{
|
use crate::systems::{movement::Position, AudioEvent, DyingSequence, Frozen, GameStage, Ghost, PlayerControlled, ScoreResource};
|
||||||
components::GhostState, movement::Position, AudioEvent, DyingSequence, Frozen, GameStage, Ghost, PlayerControlled,
|
use crate::{error::GameError, systems::GhostState};
|
||||||
ScoreResource,
|
|
||||||
};
|
|
||||||
|
|
||||||
/// A component for defining the collision area of an entity.
|
/// A component for defining the collision area of an entity.
|
||||||
#[derive(Component)]
|
#[derive(Component)]
|
||||||
|
|||||||
43
src/systems/common/bundles.rs
Normal file
43
src/systems/common/bundles.rs
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
use bevy_ecs::bundle::Bundle;
|
||||||
|
|
||||||
|
use crate::systems::{
|
||||||
|
BufferedDirection, Collider, DirectionalAnimation, EntityType, Ghost, GhostCollider, GhostState, ItemCollider,
|
||||||
|
LastAnimationState, MovementModifiers, PacmanCollider, PlayerControlled, Position, Renderable, Velocity,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[derive(Bundle)]
|
||||||
|
pub struct PlayerBundle {
|
||||||
|
pub player: PlayerControlled,
|
||||||
|
pub position: Position,
|
||||||
|
pub velocity: Velocity,
|
||||||
|
pub buffered_direction: BufferedDirection,
|
||||||
|
pub sprite: Renderable,
|
||||||
|
pub directional_animation: DirectionalAnimation,
|
||||||
|
pub entity_type: EntityType,
|
||||||
|
pub collider: Collider,
|
||||||
|
pub movement_modifiers: MovementModifiers,
|
||||||
|
pub pacman_collider: PacmanCollider,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Bundle)]
|
||||||
|
pub struct ItemBundle {
|
||||||
|
pub position: Position,
|
||||||
|
pub sprite: Renderable,
|
||||||
|
pub entity_type: EntityType,
|
||||||
|
pub collider: Collider,
|
||||||
|
pub item_collider: ItemCollider,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Bundle)]
|
||||||
|
pub struct GhostBundle {
|
||||||
|
pub ghost: Ghost,
|
||||||
|
pub position: Position,
|
||||||
|
pub velocity: Velocity,
|
||||||
|
pub sprite: Renderable,
|
||||||
|
pub directional_animation: DirectionalAnimation,
|
||||||
|
pub entity_type: EntityType,
|
||||||
|
pub collider: Collider,
|
||||||
|
pub ghost_collider: GhostCollider,
|
||||||
|
pub ghost_state: GhostState,
|
||||||
|
pub last_animation_state: LastAnimationState,
|
||||||
|
}
|
||||||
105
src/systems/common/components.rs
Normal file
105
src/systems/common/components.rs
Normal file
@@ -0,0 +1,105 @@
|
|||||||
|
use bevy_ecs::{component::Component, resource::Resource};
|
||||||
|
|
||||||
|
use crate::map::graph::TraversalFlags;
|
||||||
|
|
||||||
|
/// A tag component denoting the type of entity.
|
||||||
|
#[derive(Component, Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
|
pub enum EntityType {
|
||||||
|
Player,
|
||||||
|
Ghost,
|
||||||
|
Pellet,
|
||||||
|
PowerPellet,
|
||||||
|
Fruit(crate::texture::sprites::FruitSprite),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EntityType {
|
||||||
|
/// Returns the traversal flags for this entity type.
|
||||||
|
pub fn traversal_flags(&self) -> TraversalFlags {
|
||||||
|
match self {
|
||||||
|
EntityType::Player => TraversalFlags::PACMAN,
|
||||||
|
EntityType::Ghost => TraversalFlags::GHOST,
|
||||||
|
_ => TraversalFlags::empty(), // Static entities don't traverse
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn score_value(&self) -> Option<u32> {
|
||||||
|
match self {
|
||||||
|
EntityType::Pellet => Some(10),
|
||||||
|
EntityType::PowerPellet => Some(50),
|
||||||
|
EntityType::Fruit(fruit_type) => Some(fruit_type.score_value()),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_collectible(&self) -> bool {
|
||||||
|
matches!(self, EntityType::Pellet | EntityType::PowerPellet | EntityType::Fruit(_))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Resource)]
|
||||||
|
pub struct GlobalState {
|
||||||
|
pub exit: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Resource)]
|
||||||
|
pub struct ScoreResource(pub u32);
|
||||||
|
|
||||||
|
#[derive(Resource)]
|
||||||
|
pub struct DeltaTime {
|
||||||
|
/// Floating-point delta time in seconds
|
||||||
|
pub seconds: f32,
|
||||||
|
/// Integer tick delta (usually 1, but can be different for testing)
|
||||||
|
pub ticks: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
impl DeltaTime {
|
||||||
|
/// Creates a new DeltaTime from a floating-point delta time in seconds
|
||||||
|
///
|
||||||
|
/// While this method exists as a helper, it does not mean that seconds and ticks are interchangeable.
|
||||||
|
pub fn from_seconds(seconds: f32) -> Self {
|
||||||
|
Self {
|
||||||
|
seconds,
|
||||||
|
ticks: (seconds * 60.0).round() as u32,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates a new DeltaTime from an integer tick delta
|
||||||
|
///
|
||||||
|
/// While this method exists as a helper, it does not mean that seconds and ticks are interchangeable.
|
||||||
|
pub fn from_ticks(ticks: u32) -> Self {
|
||||||
|
Self {
|
||||||
|
seconds: ticks as f32 / 60.0,
|
||||||
|
ticks,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Movement modifiers that can affect Pac-Man's speed or handling.
|
||||||
|
#[derive(Component, Debug, Clone, Copy)]
|
||||||
|
pub struct MovementModifiers {
|
||||||
|
/// Multiplier applied to base speed (e.g., tunnels)
|
||||||
|
pub speed_multiplier: f32,
|
||||||
|
/// True when currently in a tunnel slowdown region
|
||||||
|
pub tunnel_slowdown_active: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for MovementModifiers {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
speed_multiplier: 1.0,
|
||||||
|
tunnel_slowdown_active: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tag component for entities that should be frozen during startup
|
||||||
|
#[derive(Component, Debug, Clone, Copy)]
|
||||||
|
pub struct Frozen;
|
||||||
|
|
||||||
|
/// Component for HUD life sprite entities.
|
||||||
|
/// Each life sprite entity has an index indicating its position from left to right (0, 1, 2, etc.).
|
||||||
|
/// This mostly functions as a tag component for sprites.
|
||||||
|
#[derive(Component, Debug, Clone, Copy)]
|
||||||
|
pub struct PlayerLife {
|
||||||
|
pub index: u32,
|
||||||
|
}
|
||||||
5
src/systems/common/mod.rs
Normal file
5
src/systems/common/mod.rs
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
pub mod bundles;
|
||||||
|
pub mod components;
|
||||||
|
|
||||||
|
pub use self::bundles::*;
|
||||||
|
pub use self::components::*;
|
||||||
@@ -1,411 +0,0 @@
|
|||||||
use std::collections::HashMap;
|
|
||||||
|
|
||||||
use bevy_ecs::{bundle::Bundle, component::Component, resource::Resource};
|
|
||||||
use bitflags::bitflags;
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
map::graph::TraversalFlags,
|
|
||||||
systems::{
|
|
||||||
movement::{BufferedDirection, Position, Velocity},
|
|
||||||
Collider, GhostCollider, ItemCollider, PacmanCollider,
|
|
||||||
},
|
|
||||||
texture::{
|
|
||||||
animated::{DirectionalTiles, TileSequence},
|
|
||||||
sprite::AtlasTile,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
/// A tag component for entities that are controlled by the player.
|
|
||||||
#[derive(Default, Component)]
|
|
||||||
pub struct PlayerControlled;
|
|
||||||
|
|
||||||
#[derive(Component, Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
|
||||||
pub enum Ghost {
|
|
||||||
Blinky,
|
|
||||||
Pinky,
|
|
||||||
Inky,
|
|
||||||
Clyde,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Ghost {
|
|
||||||
/// Returns the ghost type name for atlas lookups.
|
|
||||||
pub fn as_str(self) -> &'static str {
|
|
||||||
match self {
|
|
||||||
Ghost::Blinky => "blinky",
|
|
||||||
Ghost::Pinky => "pinky",
|
|
||||||
Ghost::Inky => "inky",
|
|
||||||
Ghost::Clyde => "clyde",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the base movement speed for this ghost type.
|
|
||||||
pub fn base_speed(self) -> f32 {
|
|
||||||
match self {
|
|
||||||
Ghost::Blinky => 1.0,
|
|
||||||
Ghost::Pinky => 0.95,
|
|
||||||
Ghost::Inky => 0.9,
|
|
||||||
Ghost::Clyde => 0.85,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the ghost's color for debug rendering.
|
|
||||||
#[allow(dead_code)]
|
|
||||||
pub fn debug_color(&self) -> sdl2::pixels::Color {
|
|
||||||
match self {
|
|
||||||
Ghost::Blinky => sdl2::pixels::Color::RGB(255, 0, 0), // Red
|
|
||||||
Ghost::Pinky => sdl2::pixels::Color::RGB(255, 182, 255), // Pink
|
|
||||||
Ghost::Inky => sdl2::pixels::Color::RGB(0, 255, 255), // Cyan
|
|
||||||
Ghost::Clyde => sdl2::pixels::Color::RGB(255, 182, 85), // Orange
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A tag component denoting the type of entity.
|
|
||||||
#[derive(Component, Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
|
||||||
pub enum EntityType {
|
|
||||||
Player,
|
|
||||||
Ghost,
|
|
||||||
Pellet,
|
|
||||||
PowerPellet,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl EntityType {
|
|
||||||
/// Returns the traversal flags for this entity type.
|
|
||||||
pub fn traversal_flags(&self) -> TraversalFlags {
|
|
||||||
match self {
|
|
||||||
EntityType::Player => TraversalFlags::PACMAN,
|
|
||||||
EntityType::Ghost => TraversalFlags::GHOST,
|
|
||||||
_ => TraversalFlags::empty(), // Static entities don't traverse
|
|
||||||
}
|
|
||||||
}
|
|
||||||
pub fn score_value(&self) -> Option<u32> {
|
|
||||||
match self {
|
|
||||||
EntityType::Pellet => Some(10),
|
|
||||||
EntityType::PowerPellet => Some(50),
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn is_collectible(&self) -> bool {
|
|
||||||
matches!(self, EntityType::Pellet | EntityType::PowerPellet)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A component for entities that have a sprite, with a layer for ordering.
|
|
||||||
///
|
|
||||||
/// This is intended to be modified by other entities allowing animation.
|
|
||||||
#[derive(Component)]
|
|
||||||
pub struct Renderable {
|
|
||||||
pub sprite: AtlasTile,
|
|
||||||
pub layer: u8,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Directional animation component with shared timing across all directions
|
|
||||||
#[derive(Component, Clone)]
|
|
||||||
pub struct DirectionalAnimation {
|
|
||||||
pub moving_tiles: DirectionalTiles,
|
|
||||||
pub stopped_tiles: DirectionalTiles,
|
|
||||||
pub current_frame: usize,
|
|
||||||
pub time_bank: u16,
|
|
||||||
pub frame_duration: u16,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl DirectionalAnimation {
|
|
||||||
/// Creates a new directional animation with the given tiles and frame duration
|
|
||||||
pub fn new(moving_tiles: DirectionalTiles, stopped_tiles: DirectionalTiles, frame_duration: u16) -> Self {
|
|
||||||
Self {
|
|
||||||
moving_tiles,
|
|
||||||
stopped_tiles,
|
|
||||||
current_frame: 0,
|
|
||||||
time_bank: 0,
|
|
||||||
frame_duration,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Tag component to mark animations that should loop when they reach the end
|
|
||||||
#[derive(Component, Clone, Copy, Debug, PartialEq, Eq)]
|
|
||||||
pub struct Looping;
|
|
||||||
|
|
||||||
/// Linear animation component for non-directional animations (frightened ghosts)
|
|
||||||
#[derive(Component, Resource, Clone)]
|
|
||||||
pub struct LinearAnimation {
|
|
||||||
pub tiles: TileSequence,
|
|
||||||
pub current_frame: usize,
|
|
||||||
pub time_bank: u16,
|
|
||||||
pub frame_duration: u16,
|
|
||||||
pub finished: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl LinearAnimation {
|
|
||||||
/// Creates a new linear animation with the given tiles and frame duration
|
|
||||||
pub fn new(tiles: TileSequence, frame_duration: u16) -> Self {
|
|
||||||
Self {
|
|
||||||
tiles,
|
|
||||||
current_frame: 0,
|
|
||||||
time_bank: 0,
|
|
||||||
frame_duration,
|
|
||||||
finished: false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
bitflags! {
|
|
||||||
#[derive(Component, Default, Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
|
||||||
pub struct CollisionLayer: u8 {
|
|
||||||
const PACMAN = 1 << 0;
|
|
||||||
const GHOST = 1 << 1;
|
|
||||||
const ITEM = 1 << 2;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Resource)]
|
|
||||||
pub struct GlobalState {
|
|
||||||
pub exit: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Resource)]
|
|
||||||
pub struct ScoreResource(pub u32);
|
|
||||||
|
|
||||||
#[derive(Resource)]
|
|
||||||
pub struct DeltaTime {
|
|
||||||
/// Floating-point delta time in seconds
|
|
||||||
pub seconds: f32,
|
|
||||||
/// Integer tick delta (usually 1, but can be different for testing)
|
|
||||||
pub ticks: u32,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[allow(dead_code)]
|
|
||||||
impl DeltaTime {
|
|
||||||
/// Creates a new DeltaTime from a floating-point delta time in seconds
|
|
||||||
///
|
|
||||||
/// While this method exists as a helper, it does not mean that seconds and ticks are interchangeable.
|
|
||||||
pub fn from_seconds(seconds: f32) -> Self {
|
|
||||||
Self {
|
|
||||||
seconds,
|
|
||||||
ticks: (seconds * 60.0).round() as u32,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates a new DeltaTime from an integer tick delta
|
|
||||||
///
|
|
||||||
/// While this method exists as a helper, it does not mean that seconds and ticks are interchangeable.
|
|
||||||
pub fn from_ticks(ticks: u32) -> Self {
|
|
||||||
Self {
|
|
||||||
seconds: ticks as f32 / 60.0,
|
|
||||||
ticks,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Movement modifiers that can affect Pac-Man's speed or handling.
|
|
||||||
#[derive(Component, Debug, Clone, Copy)]
|
|
||||||
pub struct MovementModifiers {
|
|
||||||
/// Multiplier applied to base speed (e.g., tunnels)
|
|
||||||
pub speed_multiplier: f32,
|
|
||||||
/// True when currently in a tunnel slowdown region
|
|
||||||
pub tunnel_slowdown_active: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for MovementModifiers {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self {
|
|
||||||
speed_multiplier: 1.0,
|
|
||||||
tunnel_slowdown_active: false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Tag component for entities that should be frozen during startup
|
|
||||||
#[derive(Component, Debug, Clone, Copy)]
|
|
||||||
pub struct Frozen;
|
|
||||||
|
|
||||||
/// Tag component for eaten ghosts
|
|
||||||
#[derive(Component, Debug, Clone, Copy)]
|
|
||||||
pub struct Eaten;
|
|
||||||
|
|
||||||
/// Tag component for Pac-Man during his death animation.
|
|
||||||
/// This is mainly because the Frozen tag would stop both movement and animation, while the Dying tag can signal that the animation should continue despite being frozen.
|
|
||||||
#[derive(Component, Debug, Clone, Copy)]
|
|
||||||
pub struct Dying;
|
|
||||||
|
|
||||||
/// Component for HUD life sprite entities.
|
|
||||||
/// Each life sprite entity has an index indicating its position from left to right (0, 1, 2, etc.).
|
|
||||||
/// This mostly functions as a tag component for sprites.
|
|
||||||
#[derive(Component, Debug, Clone, Copy)]
|
|
||||||
pub struct PlayerLife {
|
|
||||||
pub index: u32,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Component, Debug, Clone, Copy)]
|
|
||||||
pub enum GhostState {
|
|
||||||
/// Normal ghost behavior - chasing Pac-Man
|
|
||||||
Normal,
|
|
||||||
/// Frightened state after power pellet - ghost can be eaten
|
|
||||||
Frightened {
|
|
||||||
remaining_ticks: u32,
|
|
||||||
flash: bool,
|
|
||||||
remaining_flash_ticks: u32,
|
|
||||||
},
|
|
||||||
/// Eyes state - ghost has been eaten and is returning to ghost house
|
|
||||||
Eyes,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Component to track the last animation state for efficient change detection
|
|
||||||
#[derive(Component, Debug, Clone, Copy, PartialEq)]
|
|
||||||
pub struct LastAnimationState(pub GhostAnimation);
|
|
||||||
|
|
||||||
impl GhostState {
|
|
||||||
/// Creates a new frightened state with the specified duration
|
|
||||||
pub fn new_frightened(total_ticks: u32, flash_start_ticks: u32) -> Self {
|
|
||||||
Self::Frightened {
|
|
||||||
remaining_ticks: total_ticks,
|
|
||||||
flash: false,
|
|
||||||
remaining_flash_ticks: flash_start_ticks, // Time until flashing starts
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Ticks the ghost state, returning true if the state changed.
|
|
||||||
pub fn tick(&mut self) -> bool {
|
|
||||||
if let GhostState::Frightened {
|
|
||||||
remaining_ticks,
|
|
||||||
flash,
|
|
||||||
remaining_flash_ticks,
|
|
||||||
} = self
|
|
||||||
{
|
|
||||||
// Transition out of frightened state
|
|
||||||
if *remaining_ticks == 0 {
|
|
||||||
*self = GhostState::Normal;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
*remaining_ticks -= 1;
|
|
||||||
|
|
||||||
if *remaining_flash_ticks > 0 {
|
|
||||||
*remaining_flash_ticks = remaining_flash_ticks.saturating_sub(1);
|
|
||||||
if *remaining_flash_ticks == 0 {
|
|
||||||
*flash = true;
|
|
||||||
true
|
|
||||||
} else {
|
|
||||||
false
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
false
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the appropriate animation state for this ghost state
|
|
||||||
pub fn animation_state(&self) -> GhostAnimation {
|
|
||||||
match self {
|
|
||||||
GhostState::Normal => GhostAnimation::Normal,
|
|
||||||
GhostState::Eyes => GhostAnimation::Eyes,
|
|
||||||
GhostState::Frightened { flash: false, .. } => GhostAnimation::Frightened { flash: false },
|
|
||||||
GhostState::Frightened { flash: true, .. } => GhostAnimation::Frightened { flash: true },
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Enumeration of different ghost animation states.
|
|
||||||
/// Note that this is used in micromap which has a fixed size based on the number of variants,
|
|
||||||
/// so extending this should be done with caution, and will require updating the micromap's capacity.
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
|
||||||
pub enum GhostAnimation {
|
|
||||||
/// Normal ghost appearance with directional movement animations
|
|
||||||
Normal,
|
|
||||||
/// Blue ghost appearance when vulnerable (power pellet active)
|
|
||||||
Frightened { flash: bool },
|
|
||||||
/// Eyes-only animation when ghost has been consumed by Pac-Man (Eaten state)
|
|
||||||
Eyes,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Global resource containing pre-loaded animation sets for all ghost types.
|
|
||||||
///
|
|
||||||
/// This resource is initialized once during game startup and provides O(1) access
|
|
||||||
/// to animation sets for each ghost type. The animation system uses this resource
|
|
||||||
/// to efficiently switch between different ghost states without runtime asset loading.
|
|
||||||
///
|
|
||||||
/// The HashMap is keyed by `Ghost` enum variants (Blinky, Pinky, Inky, Clyde) and
|
|
||||||
/// contains the normal directional animation for each ghost type.
|
|
||||||
#[derive(Resource)]
|
|
||||||
pub struct GhostAnimations {
|
|
||||||
pub normal: HashMap<Ghost, DirectionalAnimation>,
|
|
||||||
pub eyes: DirectionalAnimation,
|
|
||||||
pub frightened: LinearAnimation,
|
|
||||||
pub frightened_flashing: LinearAnimation,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl GhostAnimations {
|
|
||||||
/// Creates a new GhostAnimations resource with the provided data.
|
|
||||||
pub fn new(
|
|
||||||
normal: HashMap<Ghost, DirectionalAnimation>,
|
|
||||||
eyes: DirectionalAnimation,
|
|
||||||
frightened: LinearAnimation,
|
|
||||||
frightened_flashing: LinearAnimation,
|
|
||||||
) -> Self {
|
|
||||||
Self {
|
|
||||||
normal,
|
|
||||||
eyes,
|
|
||||||
frightened,
|
|
||||||
frightened_flashing,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Gets the normal directional animation for the specified ghost type.
|
|
||||||
pub fn get_normal(&self, ghost_type: &Ghost) -> Option<&DirectionalAnimation> {
|
|
||||||
self.normal.get(ghost_type)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Gets the eyes animation (shared across all ghosts).
|
|
||||||
pub fn eyes(&self) -> &DirectionalAnimation {
|
|
||||||
&self.eyes
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Gets the frightened animations (shared across all ghosts).
|
|
||||||
pub fn frightened(&self, flash: bool) -> &LinearAnimation {
|
|
||||||
if flash {
|
|
||||||
&self.frightened_flashing
|
|
||||||
} else {
|
|
||||||
&self.frightened
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Bundle)]
|
|
||||||
pub struct PlayerBundle {
|
|
||||||
pub player: PlayerControlled,
|
|
||||||
pub position: Position,
|
|
||||||
pub velocity: Velocity,
|
|
||||||
pub buffered_direction: BufferedDirection,
|
|
||||||
pub sprite: Renderable,
|
|
||||||
pub directional_animation: DirectionalAnimation,
|
|
||||||
pub entity_type: EntityType,
|
|
||||||
pub collider: Collider,
|
|
||||||
pub movement_modifiers: MovementModifiers,
|
|
||||||
pub pacman_collider: PacmanCollider,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Bundle)]
|
|
||||||
pub struct ItemBundle {
|
|
||||||
pub position: Position,
|
|
||||||
pub sprite: Renderable,
|
|
||||||
pub entity_type: EntityType,
|
|
||||||
pub collider: Collider,
|
|
||||||
pub item_collider: ItemCollider,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Bundle)]
|
|
||||||
pub struct GhostBundle {
|
|
||||||
pub ghost: Ghost,
|
|
||||||
pub position: Position,
|
|
||||||
pub velocity: Velocity,
|
|
||||||
pub sprite: Renderable,
|
|
||||||
pub directional_animation: DirectionalAnimation,
|
|
||||||
pub entity_type: EntityType,
|
|
||||||
pub collider: Collider,
|
|
||||||
pub ghost_collider: GhostCollider,
|
|
||||||
pub ghost_state: GhostState,
|
|
||||||
pub last_animation_state: LastAnimationState,
|
|
||||||
}
|
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
use crate::platform;
|
use crate::platform;
|
||||||
use crate::systems::components::{
|
use crate::systems::{DirectionalAnimation, Frozen, LinearAnimation, Looping};
|
||||||
DirectionalAnimation, Frozen, GhostAnimation, GhostState, LastAnimationState, LinearAnimation, Looping,
|
|
||||||
};
|
|
||||||
use crate::{
|
use crate::{
|
||||||
map::{
|
map::{
|
||||||
builder::Map,
|
builder::Map,
|
||||||
@@ -9,18 +9,201 @@ use crate::{
|
|||||||
graph::{Edge, TraversalFlags},
|
graph::{Edge, TraversalFlags},
|
||||||
},
|
},
|
||||||
systems::{
|
systems::{
|
||||||
components::{DeltaTime, Ghost},
|
components::DeltaTime,
|
||||||
movement::{Position, Velocity},
|
movement::{Position, Velocity},
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
use bevy_ecs::component::Component;
|
||||||
|
use bevy_ecs::resource::Resource;
|
||||||
use tracing::{debug, trace, warn};
|
use tracing::{debug, trace, warn};
|
||||||
|
|
||||||
use crate::systems::GhostAnimations;
|
|
||||||
use bevy_ecs::query::Without;
|
use bevy_ecs::query::Without;
|
||||||
use bevy_ecs::system::{Commands, Query, Res};
|
use bevy_ecs::system::{Commands, Query, Res};
|
||||||
use rand::seq::IndexedRandom;
|
use rand::seq::IndexedRandom;
|
||||||
use smallvec::SmallVec;
|
use smallvec::SmallVec;
|
||||||
|
|
||||||
|
/// Tag component for eaten ghosts
|
||||||
|
#[derive(Component, Debug, Clone, Copy)]
|
||||||
|
pub struct Eaten;
|
||||||
|
|
||||||
|
/// Tag component for Pac-Man during his death animation.
|
||||||
|
/// This is mainly because the Frozen tag would stop both movement and animation, while the Dying tag can signal that the animation should continue despite being frozen.
|
||||||
|
#[derive(Component, Debug, Clone, Copy)]
|
||||||
|
pub struct Dying;
|
||||||
|
|
||||||
|
#[derive(Component, Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
|
pub enum Ghost {
|
||||||
|
Blinky,
|
||||||
|
Pinky,
|
||||||
|
Inky,
|
||||||
|
Clyde,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Ghost {
|
||||||
|
/// Returns the ghost type name for atlas lookups.
|
||||||
|
pub fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Ghost::Blinky => "blinky",
|
||||||
|
Ghost::Pinky => "pinky",
|
||||||
|
Ghost::Inky => "inky",
|
||||||
|
Ghost::Clyde => "clyde",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the base movement speed for this ghost type.
|
||||||
|
pub fn base_speed(self) -> f32 {
|
||||||
|
match self {
|
||||||
|
Ghost::Blinky => 1.0,
|
||||||
|
Ghost::Pinky => 0.95,
|
||||||
|
Ghost::Inky => 0.9,
|
||||||
|
Ghost::Clyde => 0.85,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the ghost's color for debug rendering.
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn debug_color(&self) -> sdl2::pixels::Color {
|
||||||
|
match self {
|
||||||
|
Ghost::Blinky => sdl2::pixels::Color::RGB(255, 0, 0), // Red
|
||||||
|
Ghost::Pinky => sdl2::pixels::Color::RGB(255, 182, 255), // Pink
|
||||||
|
Ghost::Inky => sdl2::pixels::Color::RGB(0, 255, 255), // Cyan
|
||||||
|
Ghost::Clyde => sdl2::pixels::Color::RGB(255, 182, 85), // Orange
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Component, Debug, Clone, Copy)]
|
||||||
|
pub enum GhostState {
|
||||||
|
/// Normal ghost behavior - chasing Pac-Man
|
||||||
|
Normal,
|
||||||
|
/// Frightened state after power pellet - ghost can be eaten
|
||||||
|
Frightened {
|
||||||
|
remaining_ticks: u32,
|
||||||
|
flash: bool,
|
||||||
|
remaining_flash_ticks: u32,
|
||||||
|
},
|
||||||
|
/// Eyes state - ghost has been eaten and is returning to ghost house
|
||||||
|
Eyes,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GhostState {
|
||||||
|
/// Creates a new frightened state with the specified duration
|
||||||
|
pub fn new_frightened(total_ticks: u32, flash_start_ticks: u32) -> Self {
|
||||||
|
Self::Frightened {
|
||||||
|
remaining_ticks: total_ticks,
|
||||||
|
flash: false,
|
||||||
|
remaining_flash_ticks: flash_start_ticks, // Time until flashing starts
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ticks the ghost state, returning true if the state changed.
|
||||||
|
pub fn tick(&mut self) -> bool {
|
||||||
|
if let GhostState::Frightened {
|
||||||
|
remaining_ticks,
|
||||||
|
flash,
|
||||||
|
remaining_flash_ticks,
|
||||||
|
} = self
|
||||||
|
{
|
||||||
|
// Transition out of frightened state
|
||||||
|
if *remaining_ticks == 0 {
|
||||||
|
*self = GhostState::Normal;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
*remaining_ticks -= 1;
|
||||||
|
|
||||||
|
if *remaining_flash_ticks > 0 {
|
||||||
|
*remaining_flash_ticks = remaining_flash_ticks.saturating_sub(1);
|
||||||
|
if *remaining_flash_ticks == 0 {
|
||||||
|
*flash = true;
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the appropriate animation state for this ghost state
|
||||||
|
pub fn animation_state(&self) -> GhostAnimation {
|
||||||
|
match self {
|
||||||
|
GhostState::Normal => GhostAnimation::Normal,
|
||||||
|
GhostState::Eyes => GhostAnimation::Eyes,
|
||||||
|
GhostState::Frightened { flash: false, .. } => GhostAnimation::Frightened { flash: false },
|
||||||
|
GhostState::Frightened { flash: true, .. } => GhostAnimation::Frightened { flash: true },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Enumeration of different ghost animation states.
|
||||||
|
/// Note that this is used in micromap which has a fixed size based on the number of variants,
|
||||||
|
/// so extending this should be done with caution, and will require updating the micromap's capacity.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
|
pub enum GhostAnimation {
|
||||||
|
/// Normal ghost appearance with directional movement animations
|
||||||
|
Normal,
|
||||||
|
/// Blue ghost appearance when vulnerable (power pellet active)
|
||||||
|
Frightened { flash: bool },
|
||||||
|
/// Eyes-only animation when ghost has been consumed by Pac-Man (Eaten state)
|
||||||
|
Eyes,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Global resource containing pre-loaded animation sets for all ghost types.
|
||||||
|
///
|
||||||
|
/// This resource is initialized once during game startup and provides O(1) access
|
||||||
|
/// to animation sets for each ghost type. The animation system uses this resource
|
||||||
|
/// to efficiently switch between different ghost states without runtime asset loading.
|
||||||
|
///
|
||||||
|
/// The HashMap is keyed by `Ghost` enum variants (Blinky, Pinky, Inky, Clyde) and
|
||||||
|
/// contains the normal directional animation for each ghost type.
|
||||||
|
#[derive(Resource)]
|
||||||
|
pub struct GhostAnimations {
|
||||||
|
pub normal: HashMap<Ghost, DirectionalAnimation>,
|
||||||
|
pub eyes: DirectionalAnimation,
|
||||||
|
pub frightened: LinearAnimation,
|
||||||
|
pub frightened_flashing: LinearAnimation,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GhostAnimations {
|
||||||
|
/// Creates a new GhostAnimations resource with the provided data.
|
||||||
|
pub fn new(
|
||||||
|
normal: HashMap<Ghost, DirectionalAnimation>,
|
||||||
|
eyes: DirectionalAnimation,
|
||||||
|
frightened: LinearAnimation,
|
||||||
|
frightened_flashing: LinearAnimation,
|
||||||
|
) -> Self {
|
||||||
|
Self {
|
||||||
|
normal,
|
||||||
|
eyes,
|
||||||
|
frightened,
|
||||||
|
frightened_flashing,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Gets the normal directional animation for the specified ghost type.
|
||||||
|
pub fn get_normal(&self, ghost_type: &Ghost) -> Option<&DirectionalAnimation> {
|
||||||
|
self.normal.get(ghost_type)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Gets the eyes animation (shared across all ghosts).
|
||||||
|
pub fn eyes(&self) -> &DirectionalAnimation {
|
||||||
|
&self.eyes
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Gets the frightened animations (shared across all ghosts).
|
||||||
|
pub fn frightened(&self, flash: bool) -> &LinearAnimation {
|
||||||
|
if flash {
|
||||||
|
&self.frightened_flashing
|
||||||
|
} else {
|
||||||
|
&self.frightened
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Autonomous ghost AI system implementing randomized movement with backtracking avoidance.
|
/// Autonomous ghost AI system implementing randomized movement with backtracking avoidance.
|
||||||
pub fn ghost_movement_system(
|
pub fn ghost_movement_system(
|
||||||
map: Res<Map>,
|
map: Res<Map>,
|
||||||
@@ -185,6 +368,10 @@ fn find_direction_to_target(
|
|||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Component to track the last animation state for efficient change detection
|
||||||
|
#[derive(Component, Debug, Clone, Copy, PartialEq)]
|
||||||
|
pub struct LastAnimationState(pub GhostAnimation);
|
||||||
|
|
||||||
/// Unified system that manages ghost state transitions and animations with component swapping
|
/// Unified system that manages ghost state transitions and animations with component swapping
|
||||||
pub fn ghost_state_system(
|
pub fn ghost_state_system(
|
||||||
mut commands: Commands,
|
mut commands: Commands,
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ use sdl2::{
|
|||||||
};
|
};
|
||||||
use smallvec::{smallvec, SmallVec};
|
use smallvec::{smallvec, SmallVec};
|
||||||
|
|
||||||
use crate::systems::components::DeltaTime;
|
use crate::systems::DeltaTime;
|
||||||
use crate::{
|
use crate::{
|
||||||
events::{GameCommand, GameEvent},
|
events::{GameCommand, GameEvent},
|
||||||
map::direction::Direction,
|
map::direction::Direction,
|
||||||
|
|||||||
@@ -1,17 +1,65 @@
|
|||||||
use bevy_ecs::{
|
use bevy_ecs::{
|
||||||
entity::Entity,
|
entity::Entity,
|
||||||
event::{EventReader, EventWriter},
|
event::{Event, EventReader, EventWriter},
|
||||||
|
observer::Trigger,
|
||||||
query::With,
|
query::With,
|
||||||
system::{Commands, Query, ResMut},
|
system::{Commands, NonSendMut, Query, Res, ResMut, Single},
|
||||||
};
|
};
|
||||||
use tracing::{debug, trace};
|
use tracing::{debug, trace};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
constants::collider::FRUIT_SIZE,
|
||||||
|
map::builder::Map,
|
||||||
|
systems::{common::bundles::ItemBundle, Collider, Position, Renderable},
|
||||||
|
texture::{sprite::SpriteAtlas, sprites::GameSprite},
|
||||||
|
};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
constants::animation::FRIGHTENED_FLASH_START_TICKS,
|
constants::animation::FRIGHTENED_FLASH_START_TICKS,
|
||||||
events::GameEvent,
|
events::GameEvent,
|
||||||
systems::{AudioEvent, EntityType, GhostCollider, GhostState, ItemCollider, PacmanCollider, ScoreResource},
|
systems::common::components::EntityType,
|
||||||
|
systems::lifetime::TimeToLive,
|
||||||
|
systems::{AudioEvent, GhostCollider, GhostState, ItemCollider, LinearAnimation, PacmanCollider, ScoreResource},
|
||||||
|
texture::animated::TileSequence,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/// Tracks the number of pellets consumed by the player for fruit spawning mechanics.
|
||||||
|
#[derive(bevy_ecs::resource::Resource, Debug, Default)]
|
||||||
|
pub struct PelletCount(pub u32);
|
||||||
|
|
||||||
|
/// Maps fruit score values to bonus sprite indices for displaying bonus points
|
||||||
|
fn fruit_score_to_sprite_index(score: u32) -> u8 {
|
||||||
|
match score {
|
||||||
|
100 => 0, // Cherry
|
||||||
|
300 => 2, // Strawberry
|
||||||
|
500 => 3, // Orange
|
||||||
|
700 => 4, // Apple
|
||||||
|
1000 => 6, // Melon
|
||||||
|
2000 => 8, // Galaxian
|
||||||
|
3000 => 9, // Bell
|
||||||
|
5000 => 10, // Key
|
||||||
|
_ => 0, // Default to 100 points sprite
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Maps sprite index to the corresponding effect sprite path (same as in state.rs)
|
||||||
|
fn sprite_index_to_path(index: u8) -> &'static str {
|
||||||
|
match index {
|
||||||
|
0 => "effects/100.png",
|
||||||
|
1 => "effects/200.png",
|
||||||
|
2 => "effects/300.png",
|
||||||
|
3 => "effects/400.png",
|
||||||
|
4 => "effects/700.png",
|
||||||
|
5 => "effects/800.png",
|
||||||
|
6 => "effects/1000.png",
|
||||||
|
7 => "effects/1600.png",
|
||||||
|
8 => "effects/2000.png",
|
||||||
|
9 => "effects/3000.png",
|
||||||
|
10 => "effects/5000.png",
|
||||||
|
_ => "effects/100.png", // fallback to index 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Determines if a collision between two entity types should be handled by the item system.
|
/// Determines if a collision between two entity types should be handled by the item system.
|
||||||
///
|
///
|
||||||
/// Returns `true` if one entity is a player and the other is a collectible item.
|
/// Returns `true` if one entity is a player and the other is a collectible item.
|
||||||
@@ -23,42 +71,83 @@ pub fn is_valid_item_collision(entity1: EntityType, entity2: EntityType) -> bool
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
pub fn item_system(
|
pub fn item_system(
|
||||||
mut commands: Commands,
|
mut commands: Commands,
|
||||||
mut collision_events: EventReader<GameEvent>,
|
mut collision_events: EventReader<GameEvent>,
|
||||||
mut score: ResMut<ScoreResource>,
|
mut score: ResMut<ScoreResource>,
|
||||||
pacman_query: Query<Entity, With<PacmanCollider>>,
|
mut pellet_count: ResMut<PelletCount>,
|
||||||
item_query: Query<(Entity, &EntityType), With<ItemCollider>>,
|
pacman: Single<Entity, With<PacmanCollider>>,
|
||||||
|
item_query: Query<(Entity, &EntityType, &Position), With<ItemCollider>>,
|
||||||
mut ghost_query: Query<&mut GhostState, With<GhostCollider>>,
|
mut ghost_query: Query<&mut GhostState, With<GhostCollider>>,
|
||||||
mut events: EventWriter<AudioEvent>,
|
mut events: EventWriter<AudioEvent>,
|
||||||
|
atlas: NonSendMut<SpriteAtlas>,
|
||||||
) {
|
) {
|
||||||
for event in collision_events.read() {
|
for event in collision_events.read() {
|
||||||
if let GameEvent::Collision(entity1, entity2) = event {
|
if let GameEvent::Collision(entity1, entity2) = event {
|
||||||
// Check if one is Pacman and the other is an item
|
// Check if one is Pacman and the other is an item
|
||||||
let (_pacman_entity, item_entity) = if pacman_query.get(*entity1).is_ok() && item_query.get(*entity2).is_ok() {
|
let (_, item_entity) = if *pacman == *entity1 && item_query.get(*entity2).is_ok() {
|
||||||
(*entity1, *entity2)
|
(*pacman, *entity2)
|
||||||
} else if pacman_query.get(*entity2).is_ok() && item_query.get(*entity1).is_ok() {
|
} else if *pacman == *entity2 && item_query.get(*entity1).is_ok() {
|
||||||
(*entity2, *entity1)
|
(*pacman, *entity1)
|
||||||
} else {
|
} else {
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Get the item type and update score
|
// Get the item type and update score
|
||||||
if let Ok((item_ent, entity_type)) = item_query.get(item_entity) {
|
if let Ok((item_ent, entity_type, item_position)) = item_query.get(item_entity) {
|
||||||
if let Some(score_value) = entity_type.score_value() {
|
if let Some(score_value) = entity_type.score_value() {
|
||||||
trace!(item_entity = ?item_ent, item_type = ?entity_type, score_value, new_score = score.0 + score_value, "Item collected by player");
|
trace!(item_entity = ?item_ent, item_type = ?entity_type, score_value, new_score = score.0 + score_value, "Item collected by player");
|
||||||
score.0 += score_value;
|
score.0 += score_value;
|
||||||
|
|
||||||
|
// Spawn bonus sprite for fruits at the fruit's position (similar to ghost eating bonus)
|
||||||
|
if matches!(entity_type, EntityType::Fruit(_)) {
|
||||||
|
let sprite_index = fruit_score_to_sprite_index(score_value);
|
||||||
|
let sprite_path = sprite_index_to_path(sprite_index);
|
||||||
|
|
||||||
|
if let Ok(sprite_tile) = SpriteAtlas::get_tile(&atlas, sprite_path) {
|
||||||
|
let tile_sequence = TileSequence::single(sprite_tile);
|
||||||
|
let animation = LinearAnimation::new(tile_sequence, 1);
|
||||||
|
|
||||||
|
commands.spawn((
|
||||||
|
*item_position,
|
||||||
|
Renderable {
|
||||||
|
sprite: sprite_tile,
|
||||||
|
layer: 2, // Above other entities
|
||||||
|
},
|
||||||
|
animation,
|
||||||
|
TimeToLive::new(120), // 2 seconds at 60 FPS
|
||||||
|
));
|
||||||
|
|
||||||
|
debug!(
|
||||||
|
fruit_score = score_value,
|
||||||
|
sprite_index, "Fruit bonus sprite spawned at fruit position"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Remove the collected item
|
// Remove the collected item
|
||||||
commands.entity(item_ent).despawn();
|
commands.entity(item_ent).despawn();
|
||||||
|
|
||||||
|
// Track pellet consumption for fruit spawning
|
||||||
|
if *entity_type == EntityType::Pellet {
|
||||||
|
pellet_count.0 += 1;
|
||||||
|
trace!(pellet_count = pellet_count.0, "Pellet consumed");
|
||||||
|
|
||||||
|
// Check if we should spawn a fruit
|
||||||
|
if pellet_count.0 == 70 || pellet_count.0 == 170 {
|
||||||
|
debug!(pellet_count = pellet_count.0, "Fruit spawn milestone reached");
|
||||||
|
commands.trigger(SpawnFruitTrigger);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Trigger audio if appropriate
|
// Trigger audio if appropriate
|
||||||
if entity_type.is_collectible() {
|
if entity_type.is_collectible() {
|
||||||
events.write(AudioEvent::PlayEat);
|
events.write(AudioEvent::PlayEat);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Make ghosts frightened when power pellet is collected
|
// Make ghosts frightened when power pellet is collected
|
||||||
if *entity_type == EntityType::PowerPellet {
|
if matches!(*entity_type, EntityType::PowerPellet) {
|
||||||
// Convert seconds to frames (assumes 60 FPS)
|
// Convert seconds to frames (assumes 60 FPS)
|
||||||
let total_ticks = 60 * 5; // 5 seconds total
|
let total_ticks = 60 * 5; // 5 seconds total
|
||||||
debug!(duration_ticks = total_ticks, "Power pellet collected, frightening ghosts");
|
debug!(duration_ticks = total_ticks, "Power pellet collected, frightening ghosts");
|
||||||
@@ -78,3 +167,32 @@ pub fn item_system(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Trigger to spawn a fruit
|
||||||
|
#[derive(Event, Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub struct SpawnFruitTrigger;
|
||||||
|
|
||||||
|
pub fn spawn_fruit_observer(
|
||||||
|
_: Trigger<SpawnFruitTrigger>,
|
||||||
|
mut commands: Commands,
|
||||||
|
atlas: NonSendMut<SpriteAtlas>,
|
||||||
|
map: Res<Map>,
|
||||||
|
) {
|
||||||
|
// Use cherry sprite as the default fruit (first fruit in original Pac-Man)
|
||||||
|
let fruit_sprite = &atlas
|
||||||
|
.get_tile(&GameSprite::Fruit(crate::texture::sprites::FruitSprite::Cherry).to_path())
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let fruit_entity = commands.spawn(ItemBundle {
|
||||||
|
position: map.start_positions.fruit_spawn,
|
||||||
|
sprite: Renderable {
|
||||||
|
sprite: *fruit_sprite,
|
||||||
|
layer: 1,
|
||||||
|
},
|
||||||
|
entity_type: EntityType::Fruit(crate::texture::sprites::FruitSprite::Cherry),
|
||||||
|
collider: Collider { size: FRUIT_SIZE },
|
||||||
|
item_collider: ItemCollider,
|
||||||
|
});
|
||||||
|
|
||||||
|
debug!(fruit_entity = ?fruit_entity.id(), fruit_spawn_node = ?map.start_positions.fruit_spawn, "Fruit spawned");
|
||||||
|
}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ use bevy_ecs::{
|
|||||||
system::{Commands, Query, Res},
|
system::{Commands, Query, Res},
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::systems::components::DeltaTime;
|
use crate::systems::DeltaTime;
|
||||||
|
|
||||||
/// Component for entities that should be automatically deleted after a certain number of ticks
|
/// Component for entities that should be automatically deleted after a certain number of ticks
|
||||||
#[derive(Component, Debug, Clone, Copy)]
|
#[derive(Component, Debug, Clone, Copy)]
|
||||||
|
|||||||
@@ -9,9 +9,10 @@ pub mod profiling;
|
|||||||
#[cfg_attr(coverage_nightly, coverage(off))]
|
#[cfg_attr(coverage_nightly, coverage(off))]
|
||||||
pub mod render;
|
pub mod render;
|
||||||
|
|
||||||
|
pub mod animation;
|
||||||
pub mod blinking;
|
pub mod blinking;
|
||||||
pub mod collision;
|
pub mod collision;
|
||||||
pub mod components;
|
pub mod common;
|
||||||
pub mod ghost;
|
pub mod ghost;
|
||||||
pub mod input;
|
pub mod input;
|
||||||
pub mod item;
|
pub mod item;
|
||||||
@@ -22,10 +23,11 @@ pub mod state;
|
|||||||
|
|
||||||
// Re-export all the modules. Do not fine-tune the exports.
|
// Re-export all the modules. Do not fine-tune the exports.
|
||||||
|
|
||||||
|
pub use self::animation::*;
|
||||||
pub use self::audio::*;
|
pub use self::audio::*;
|
||||||
pub use self::blinking::*;
|
pub use self::blinking::*;
|
||||||
pub use self::collision::*;
|
pub use self::collision::*;
|
||||||
pub use self::components::*;
|
pub use self::common::*;
|
||||||
pub use self::debug::*;
|
pub use self::debug::*;
|
||||||
pub use self::ghost::*;
|
pub use self::ghost::*;
|
||||||
pub use self::input::*;
|
pub use self::input::*;
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
use bevy_ecs::{
|
use bevy_ecs::{
|
||||||
|
component::Component,
|
||||||
event::EventReader,
|
event::EventReader,
|
||||||
query::{With, Without},
|
query::{With, Without},
|
||||||
system::{Query, Res, ResMut, Single},
|
system::{Query, Res, ResMut, Single},
|
||||||
@@ -9,13 +10,17 @@ use crate::{
|
|||||||
events::{GameCommand, GameEvent},
|
events::{GameCommand, GameEvent},
|
||||||
map::{builder::Map, graph::Edge},
|
map::{builder::Map, graph::Edge},
|
||||||
systems::{
|
systems::{
|
||||||
components::{DeltaTime, EntityType, Frozen, GlobalState, MovementModifiers, PlayerControlled},
|
components::{DeltaTime, EntityType, Frozen, GlobalState, MovementModifiers},
|
||||||
debug::DebugState,
|
debug::DebugState,
|
||||||
movement::{BufferedDirection, Position, Velocity},
|
movement::{BufferedDirection, Position, Velocity},
|
||||||
AudioState,
|
AudioState,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/// A tag component for entities that are controlled by the player.
|
||||||
|
#[derive(Default, Component)]
|
||||||
|
pub struct PlayerControlled;
|
||||||
|
|
||||||
pub fn can_traverse(entity_type: EntityType, edge: Edge) -> bool {
|
pub fn can_traverse(entity_type: EntityType, edge: Edge) -> bool {
|
||||||
let entity_flags = entity_type.traversal_flags();
|
let entity_flags = entity_type.traversal_flags();
|
||||||
edge.traversal_flags.contains(entity_flags)
|
edge.traversal_flags.contains(entity_flags)
|
||||||
@@ -27,6 +32,7 @@ pub fn can_traverse(entity_type: EntityType, edge: Edge) -> bool {
|
|||||||
/// toggling, audio muting, and game exit requests. Movement commands are buffered
|
/// toggling, audio muting, and game exit requests. Movement commands are buffered
|
||||||
/// to allow direction changes before reaching intersections, improving gameplay
|
/// to allow direction changes before reaching intersections, improving gameplay
|
||||||
/// responsiveness. Non-movement commands immediately modify global game state.
|
/// responsiveness. Non-movement commands immediately modify global game state.
|
||||||
|
#[allow(clippy::type_complexity)]
|
||||||
pub fn player_control_system(
|
pub fn player_control_system(
|
||||||
mut events: EventReader<GameEvent>,
|
mut events: EventReader<GameEvent>,
|
||||||
mut state: ResMut<GlobalState>,
|
mut state: ResMut<GlobalState>,
|
||||||
|
|||||||
@@ -1,12 +1,10 @@
|
|||||||
use crate::map::builder::Map;
|
use crate::map::builder::Map;
|
||||||
use crate::map::direction::Direction;
|
use crate::map::direction::Direction;
|
||||||
use crate::systems::input::TouchState;
|
|
||||||
use crate::systems::{
|
use crate::systems::{
|
||||||
debug_render_system, BatchedLinesResource, Collider, CursorPosition, DebugState, DebugTextureResource, DeltaTime,
|
debug_render_system, BatchedLinesResource, Collider, CursorPosition, DebugState, DebugTextureResource, GameStage, PlayerLife,
|
||||||
DirectionalAnimation, Dying, Frozen, GameStage, LinearAnimation, Looping, PlayerLife, PlayerLives, Position, Renderable,
|
PlayerLives, Position, ScoreResource, StartupSequence, SystemId, SystemTimings, TouchState, TtfAtlasResource,
|
||||||
ScoreResource, StartupSequence, SystemId, SystemTimings, TtfAtlasResource, Velocity,
|
|
||||||
};
|
};
|
||||||
use crate::texture::sprite::SpriteAtlas;
|
use crate::texture::sprite::{AtlasTile, SpriteAtlas};
|
||||||
use crate::texture::sprites::{GameSprite, PacmanSprite};
|
use crate::texture::sprites::{GameSprite, PacmanSprite};
|
||||||
use crate::texture::text::TextTexture;
|
use crate::texture::text::TextTexture;
|
||||||
use crate::{
|
use crate::{
|
||||||
@@ -16,7 +14,7 @@ use crate::{
|
|||||||
use bevy_ecs::component::Component;
|
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, Has, Or, With, Without};
|
use bevy_ecs::query::{Changed, Or, With, Without};
|
||||||
use bevy_ecs::removal_detection::RemovedComponents;
|
use bevy_ecs::removal_detection::RemovedComponents;
|
||||||
use bevy_ecs::resource::Resource;
|
use bevy_ecs::resource::Resource;
|
||||||
use bevy_ecs::system::{Commands, NonSendMut, Query, Res, ResMut};
|
use bevy_ecs::system::{Commands, NonSendMut, Query, Res, ResMut};
|
||||||
@@ -25,8 +23,18 @@ use sdl2::pixels::Color;
|
|||||||
use sdl2::rect::{Point, Rect};
|
use sdl2::rect::{Point, Rect};
|
||||||
use sdl2::render::{BlendMode, Canvas, Texture};
|
use sdl2::render::{BlendMode, Canvas, Texture};
|
||||||
use sdl2::video::Window;
|
use sdl2::video::Window;
|
||||||
|
use std::cmp::Ordering;
|
||||||
use std::time::Instant;
|
use std::time::Instant;
|
||||||
|
|
||||||
|
/// A component for entities that have a sprite, with a layer for ordering.
|
||||||
|
///
|
||||||
|
/// This is intended to be modified by other entities allowing animation.
|
||||||
|
#[derive(Component)]
|
||||||
|
pub struct Renderable {
|
||||||
|
pub sprite: AtlasTile,
|
||||||
|
pub layer: u8,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Resource, Default)]
|
#[derive(Resource, Default)]
|
||||||
pub struct RenderDirty(pub bool);
|
pub struct RenderDirty(pub bool);
|
||||||
|
|
||||||
@@ -56,77 +64,6 @@ pub fn dirty_render_system(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Updates directional animated entities with synchronized timing across directions.
|
|
||||||
///
|
|
||||||
/// This runs before the render system to update sprites based on current direction and movement state.
|
|
||||||
/// All directions share the same frame timing to ensure perfect synchronization.
|
|
||||||
pub fn directional_render_system(
|
|
||||||
dt: Res<DeltaTime>,
|
|
||||||
mut query: Query<(&Position, &Velocity, &mut DirectionalAnimation, &mut Renderable), Without<Frozen>>,
|
|
||||||
) {
|
|
||||||
let ticks = (dt.seconds * 60.0).round() as u16; // Convert from seconds to ticks at 60 ticks/sec
|
|
||||||
|
|
||||||
for (position, velocity, mut anim, mut renderable) in query.iter_mut() {
|
|
||||||
let stopped = matches!(position, Position::Stopped { .. });
|
|
||||||
|
|
||||||
// Only tick animation when moving to preserve stopped frame
|
|
||||||
if !stopped {
|
|
||||||
// Tick shared animation state
|
|
||||||
anim.time_bank += ticks;
|
|
||||||
while anim.time_bank >= anim.frame_duration {
|
|
||||||
anim.time_bank -= anim.frame_duration;
|
|
||||||
anim.current_frame += 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get tiles for current direction and movement state
|
|
||||||
let tiles = if stopped {
|
|
||||||
anim.stopped_tiles.get(velocity.direction)
|
|
||||||
} else {
|
|
||||||
anim.moving_tiles.get(velocity.direction)
|
|
||||||
};
|
|
||||||
|
|
||||||
if !tiles.is_empty() {
|
|
||||||
let new_tile = tiles.get_tile(anim.current_frame);
|
|
||||||
if renderable.sprite != new_tile {
|
|
||||||
renderable.sprite = new_tile;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// System that updates `Renderable` sprites for entities with `LinearAnimation`.
|
|
||||||
#[allow(clippy::type_complexity)]
|
|
||||||
pub fn linear_render_system(
|
|
||||||
dt: Res<DeltaTime>,
|
|
||||||
mut query: Query<(&mut LinearAnimation, &mut Renderable, Has<Looping>), Or<(Without<Frozen>, With<Dying>)>>,
|
|
||||||
) {
|
|
||||||
for (mut anim, mut renderable, looping) in query.iter_mut() {
|
|
||||||
if anim.finished {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
anim.time_bank += dt.ticks as u16;
|
|
||||||
let frames_to_advance = (anim.time_bank / anim.frame_duration) as usize;
|
|
||||||
|
|
||||||
if frames_to_advance == 0 {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
let total_frames = anim.tiles.len();
|
|
||||||
|
|
||||||
if !looping && anim.current_frame + frames_to_advance >= total_frames {
|
|
||||||
anim.finished = true;
|
|
||||||
anim.current_frame = total_frames - 1;
|
|
||||||
} else {
|
|
||||||
anim.current_frame += frames_to_advance;
|
|
||||||
}
|
|
||||||
|
|
||||||
anim.time_bank %= anim.frame_duration;
|
|
||||||
renderable.sprite = anim.tiles.get_tile(anim.current_frame);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// System that manages player life sprite entities.
|
/// System that manages player life sprite entities.
|
||||||
/// Spawns and despawns life sprite entities based on changes to PlayerLives resource.
|
/// Spawns and despawns life sprite entities based on changes to PlayerLives resource.
|
||||||
/// Each life sprite is positioned based on its index (0, 1, 2, etc. from left to right).
|
/// Each life sprite is positioned based on its index (0, 1, 2, etc. from left to right).
|
||||||
@@ -147,8 +84,11 @@ pub fn player_life_sprite_system(
|
|||||||
// Calculate the difference
|
// Calculate the difference
|
||||||
let diff = (displayed_lives as i8) - (current_count as i8);
|
let diff = (displayed_lives as i8) - (current_count as i8);
|
||||||
|
|
||||||
if diff > 0 {
|
match diff.cmp(&0) {
|
||||||
|
// Ignore when the number of lives displayed is correct
|
||||||
|
Ordering::Equal => {}
|
||||||
// Spawn new life sprites
|
// Spawn new life sprites
|
||||||
|
Ordering::Greater => {
|
||||||
let life_sprite = match atlas.get_tile(&GameSprite::Pacman(PacmanSprite::Moving(Direction::Left, 1)).to_path()) {
|
let life_sprite = match atlas.get_tile(&GameSprite::Pacman(PacmanSprite::Moving(Direction::Left, 1)).to_path()) {
|
||||||
Ok(sprite) => sprite,
|
Ok(sprite) => sprite,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
@@ -157,7 +97,7 @@ pub fn player_life_sprite_system(
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
for i in 0..diff.abs() {
|
for i in 0..diff {
|
||||||
let position = calculate_life_sprite_position(i as u32);
|
let position = calculate_life_sprite_position(i as u32);
|
||||||
|
|
||||||
commands.spawn((
|
commands.spawn((
|
||||||
@@ -171,9 +111,10 @@ pub fn player_life_sprite_system(
|
|||||||
},
|
},
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
} else if diff < 0 {
|
}
|
||||||
// Remove excess life sprites (highest indices first)
|
// Remove excess life sprites (highest indices first)
|
||||||
let to_remove = diff.abs() as usize;
|
Ordering::Less => {
|
||||||
|
let to_remove = diff.unsigned_abs();
|
||||||
let sprites_to_remove: Vec<_> = current_sprites
|
let sprites_to_remove: Vec<_> = current_sprites
|
||||||
.iter()
|
.iter()
|
||||||
.rev() // Start from highest index
|
.rev() // Start from highest index
|
||||||
@@ -185,6 +126,7 @@ pub fn player_life_sprite_system(
|
|||||||
commands.entity(entity).despawn();
|
commands.entity(entity).despawn();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Component for Renderables to store an exact pixel position
|
/// Component for Renderables to store an exact pixel position
|
||||||
@@ -361,6 +303,7 @@ pub fn hud_render_system(
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[allow(clippy::too_many_arguments)]
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
#[allow(clippy::type_complexity)]
|
||||||
pub fn render_system(
|
pub fn render_system(
|
||||||
canvas: &mut Canvas<Window>,
|
canvas: &mut Canvas<Window>,
|
||||||
map_texture: &NonSendMut<MapTextureResource>,
|
map_texture: &NonSendMut<MapTextureResource>,
|
||||||
@@ -426,6 +369,7 @@ pub fn render_system(
|
|||||||
/// Combined render system that renders to both backbuffer and debug textures in a single
|
/// Combined render system that renders to both backbuffer and debug textures in a single
|
||||||
/// with_multiple_texture_canvas call for reduced overhead
|
/// with_multiple_texture_canvas call for reduced overhead
|
||||||
#[allow(clippy::too_many_arguments)]
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
#[allow(clippy::type_complexity)]
|
||||||
pub fn combined_render_system(
|
pub fn combined_render_system(
|
||||||
mut canvas: NonSendMut<&mut Canvas<Window>>,
|
mut canvas: NonSendMut<&mut Canvas<Window>>,
|
||||||
map_texture: NonSendMut<MapTextureResource>,
|
map_texture: NonSendMut<MapTextureResource>,
|
||||||
|
|||||||
@@ -5,8 +5,7 @@
|
|||||||
//! The `GameSprite` enum is the main entry point, and its `to_path` method
|
//! The `GameSprite` enum is the main entry point, and its `to_path` method
|
||||||
//! generates the correct path for a given sprite in the texture atlas.
|
//! generates the correct path for a given sprite in the texture atlas.
|
||||||
|
|
||||||
use crate::map::direction::Direction;
|
use crate::{map::direction::Direction, systems::Ghost};
|
||||||
use crate::systems::components::Ghost;
|
|
||||||
|
|
||||||
/// Represents the different sprites for Pac-Man.
|
/// Represents the different sprites for Pac-Man.
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
@@ -48,12 +47,43 @@ pub enum MazeSprite {
|
|||||||
Energizer,
|
Energizer,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Represents the different fruit sprites that can appear as bonus items.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub enum FruitSprite {
|
||||||
|
Cherry,
|
||||||
|
Strawberry,
|
||||||
|
Orange,
|
||||||
|
Apple,
|
||||||
|
Melon,
|
||||||
|
Galaxian,
|
||||||
|
Bell,
|
||||||
|
Key,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FruitSprite {
|
||||||
|
/// Returns the score value for this fruit type.
|
||||||
|
pub fn score_value(self) -> u32 {
|
||||||
|
match self {
|
||||||
|
FruitSprite::Cherry => 100,
|
||||||
|
FruitSprite::Strawberry => 300,
|
||||||
|
FruitSprite::Orange => 500,
|
||||||
|
FruitSprite::Apple => 700,
|
||||||
|
FruitSprite::Melon => 1000,
|
||||||
|
FruitSprite::Galaxian => 2000,
|
||||||
|
FruitSprite::Bell => 3000,
|
||||||
|
FruitSprite::Key => 5000,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// A top-level enum that encompasses all game sprites.
|
/// A top-level enum that encompasses all game sprites.
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
pub enum GameSprite {
|
pub enum GameSprite {
|
||||||
Pacman(PacmanSprite),
|
Pacman(PacmanSprite),
|
||||||
Ghost(GhostSprite),
|
Ghost(GhostSprite),
|
||||||
Maze(MazeSprite),
|
Maze(MazeSprite),
|
||||||
|
Fruit(FruitSprite),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl GameSprite {
|
impl GameSprite {
|
||||||
@@ -106,6 +136,16 @@ impl GameSprite {
|
|||||||
GameSprite::Maze(MazeSprite::Tile(index)) => format!("maze/tiles/{}.png", index),
|
GameSprite::Maze(MazeSprite::Tile(index)) => format!("maze/tiles/{}.png", index),
|
||||||
GameSprite::Maze(MazeSprite::Pellet) => "maze/pellet.png".to_string(),
|
GameSprite::Maze(MazeSprite::Pellet) => "maze/pellet.png".to_string(),
|
||||||
GameSprite::Maze(MazeSprite::Energizer) => "maze/energizer.png".to_string(),
|
GameSprite::Maze(MazeSprite::Energizer) => "maze/energizer.png".to_string(),
|
||||||
|
|
||||||
|
// Fruit sprites
|
||||||
|
GameSprite::Fruit(FruitSprite::Cherry) => "edible/cherry.png".to_string(),
|
||||||
|
GameSprite::Fruit(FruitSprite::Strawberry) => "edible/strawberry.png".to_string(),
|
||||||
|
GameSprite::Fruit(FruitSprite::Orange) => "edible/orange.png".to_string(),
|
||||||
|
GameSprite::Fruit(FruitSprite::Apple) => "edible/apple.png".to_string(),
|
||||||
|
GameSprite::Fruit(FruitSprite::Melon) => "edible/melon.png".to_string(),
|
||||||
|
GameSprite::Fruit(FruitSprite::Galaxian) => "edible/galaxian.png".to_string(),
|
||||||
|
GameSprite::Fruit(FruitSprite::Bell) => "edible/bell.png".to_string(),
|
||||||
|
GameSprite::Fruit(FruitSprite::Key) => "edible/key.png".to_string(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,5 @@
|
|||||||
use bevy_ecs::{entity::Entity, system::RunSystemOnce, world::World};
|
use bevy_ecs::{entity::Entity, system::RunSystemOnce, world::World};
|
||||||
use pacman::systems::{
|
use pacman::systems::{blinking_system, Blinking, DeltaTime, Frozen, Hidden, Renderable};
|
||||||
blinking::{blinking_system, Blinking},
|
|
||||||
components::{DeltaTime, Renderable},
|
|
||||||
Frozen, Hidden,
|
|
||||||
};
|
|
||||||
use speculoos::prelude::*;
|
use speculoos::prelude::*;
|
||||||
|
|
||||||
mod common;
|
mod common;
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
use pacman::{
|
use pacman::{
|
||||||
game::ATLAS_FRAMES,
|
game::ATLAS_FRAMES,
|
||||||
map::direction::Direction,
|
map::direction::Direction,
|
||||||
systems::components::Ghost,
|
systems::Ghost,
|
||||||
texture::sprites::{FrightenedColor, GameSprite, GhostSprite, MazeSprite, PacmanSprite},
|
texture::sprites::{FrightenedColor, GameSprite, GhostSprite, MazeSprite, PacmanSprite},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user