mirror of
https://github.com/Xevion/Pac-Man.git
synced 2025-12-07 07:15:45 -06:00
Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a887fae00f | ||
|
|
273385dfe4 | ||
|
|
82cedf7e4a |
2
Cargo.lock
generated
2
Cargo.lock
generated
@@ -711,7 +711,7 @@ checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
|
||||
|
||||
[[package]]
|
||||
name = "pacman"
|
||||
version = "0.80.2"
|
||||
version = "0.80.3"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bevy_ecs",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "pacman"
|
||||
version = "0.80.2"
|
||||
version = "0.80.3"
|
||||
authors = ["Xevion"]
|
||||
edition = "2021"
|
||||
rust-version = "1.86.0"
|
||||
|
||||
3
Justfile
3
Justfile
@@ -42,3 +42,6 @@ web *args:
|
||||
fix:
|
||||
cargo fix --workspace --lib --allow-dirty
|
||||
cargo fmt --all
|
||||
|
||||
push:
|
||||
git push origin --tags && git push
|
||||
|
||||
190
src/audio.rs
190
src/audio.rs
@@ -2,12 +2,18 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::asset::Asset;
|
||||
use anyhow::{anyhow, Result};
|
||||
use sdl2::{
|
||||
mixer::{self, Chunk, InitFlag, LoaderRWops, AUDIO_S16LSB, DEFAULT_CHANNELS},
|
||||
mixer::{self, Chunk, InitFlag, LoaderRWops, AUDIO_S16LSB},
|
||||
rwops::RWops,
|
||||
};
|
||||
use strum::IntoEnumIterator;
|
||||
|
||||
const AUDIO_FREQUENCY: i32 = 16_000;
|
||||
const AUDIO_CHANNELS: i32 = 4;
|
||||
const DEFAULT_VOLUME: u8 = 32;
|
||||
const WAKA_SOUND_COUNT: u8 = 4;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum Sound {
|
||||
Waka(u8),
|
||||
@@ -23,19 +29,16 @@ impl IntoEnumIterator for Sound {
|
||||
type Iterator = std::vec::IntoIter<Sound>;
|
||||
|
||||
fn iter() -> Self::Iterator {
|
||||
vec![
|
||||
Sound::Waka(0),
|
||||
Sound::Waka(1),
|
||||
Sound::Waka(2),
|
||||
Sound::Waka(3),
|
||||
let mut sounds = vec![
|
||||
Sound::PacmanDeath,
|
||||
Sound::ExtraLife,
|
||||
Sound::Fruit,
|
||||
Sound::Ghost,
|
||||
Sound::Beginning,
|
||||
Sound::Intermission,
|
||||
]
|
||||
.into_iter()
|
||||
];
|
||||
sounds.extend((0..WAKA_SOUND_COUNT).map(Sound::Waka));
|
||||
sounds.into_iter()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,8 +51,14 @@ pub struct Audio {
|
||||
_mixer_context: Option<mixer::Sdl2MixerContext>,
|
||||
sounds: HashMap<Sound, Chunk>,
|
||||
next_waka_index: u8,
|
||||
muted: bool,
|
||||
disabled: bool,
|
||||
state: AudioState,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum AudioState {
|
||||
Enabled { volume: u8 },
|
||||
Muted { previous_volume: u8 },
|
||||
Disabled,
|
||||
}
|
||||
|
||||
impl Default for Audio {
|
||||
@@ -64,7 +73,21 @@ impl Audio {
|
||||
/// If audio fails to initialize, the audio system will be disabled and
|
||||
/// all functions will silently do nothing.
|
||||
pub fn new() -> Self {
|
||||
let frequency = 16_000;
|
||||
match Self::try_new() {
|
||||
Ok(audio) => audio,
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to initialize audio: {}. Audio will be disabled.", e);
|
||||
Self {
|
||||
_mixer_context: None,
|
||||
sounds: HashMap::new(),
|
||||
next_waka_index: 0,
|
||||
state: AudioState::Disabled,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn try_new() -> Result<Self> {
|
||||
let format = AUDIO_S16LSB;
|
||||
let chunk_size = {
|
||||
// 256 is the minimum for Emscripten, but in practice 1024 is much more reliable
|
||||
@@ -81,103 +104,52 @@ impl Audio {
|
||||
};
|
||||
|
||||
// Try to open audio, but don't panic if it fails
|
||||
if let Err(e) = mixer::open_audio(frequency, format, DEFAULT_CHANNELS, chunk_size) {
|
||||
tracing::warn!("Failed to open audio: {}. Audio will be disabled.", e);
|
||||
return Self {
|
||||
_mixer_context: None,
|
||||
sounds: HashMap::new(),
|
||||
next_waka_index: 0u8,
|
||||
muted: false,
|
||||
disabled: true,
|
||||
};
|
||||
}
|
||||
mixer::open_audio(AUDIO_FREQUENCY, format, AUDIO_CHANNELS, chunk_size)
|
||||
.map_err(|e| anyhow!("Failed to open audio: {}", e))?;
|
||||
|
||||
let channels = 4;
|
||||
mixer::allocate_channels(4);
|
||||
mixer::allocate_channels(AUDIO_CHANNELS);
|
||||
|
||||
// set channel volume
|
||||
for i in 0..channels {
|
||||
mixer::Channel(i).set_volume(32);
|
||||
for i in 0..AUDIO_CHANNELS {
|
||||
mixer::Channel(i).set_volume(DEFAULT_VOLUME as i32);
|
||||
}
|
||||
|
||||
// Try to initialize mixer, but don't panic if it fails
|
||||
let mixer_context = match mixer::init(InitFlag::OGG) {
|
||||
Ok(ctx) => ctx,
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to initialize SDL2_mixer: {}. Audio will be disabled.", e);
|
||||
return Self {
|
||||
_mixer_context: None,
|
||||
sounds: HashMap::new(),
|
||||
next_waka_index: 0u8,
|
||||
muted: false,
|
||||
disabled: true,
|
||||
};
|
||||
}
|
||||
};
|
||||
let mixer_context = mixer::init(InitFlag::OGG).map_err(|e| anyhow!("Failed to initialize SDL2_mixer: {}", e))?;
|
||||
|
||||
// Try to load sounds, but don't panic if any fail
|
||||
let mut sounds = HashMap::new();
|
||||
for (i, sound_type) in Sound::iter().enumerate() {
|
||||
let asset = Asset::SoundFile(sound_type);
|
||||
match asset.get_bytes() {
|
||||
Ok(data) => match RWops::from_bytes(&data) {
|
||||
Ok(rwops) => match rwops.load_wav() {
|
||||
Ok(chunk) => {
|
||||
sounds.insert(sound_type, chunk);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to load sound {} from asset API: {}", i + 1, e);
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to create RWops for sound {}: {}", i + 1, e);
|
||||
}
|
||||
},
|
||||
let sounds: HashMap<Sound, Chunk> = Sound::iter()
|
||||
.filter_map(|sound_type| match Self::load_sound(sound_type) {
|
||||
Ok(chunk) => Some((sound_type, chunk)),
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to load sound asset {}: {}", i + 1, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let death_sound = match Asset::SoundFile(Sound::PacmanDeath).get_bytes() {
|
||||
Ok(data) => match RWops::from_bytes(&data) {
|
||||
Ok(rwops) => match rwops.load_wav() {
|
||||
Ok(chunk) => Some(chunk),
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to load death sound from asset API: {}", e);
|
||||
None
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to create RWops for death sound: {}", e);
|
||||
tracing::warn!("Failed to load sound {:?}: {}", sound_type, e);
|
||||
None
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to load death sound asset: {}", e);
|
||||
None
|
||||
}
|
||||
};
|
||||
})
|
||||
.collect();
|
||||
|
||||
// If no sounds loaded successfully, disable audio
|
||||
if sounds.is_empty() && death_sound.is_none() {
|
||||
tracing::warn!("No sounds loaded successfully. Audio will be disabled.");
|
||||
return Self {
|
||||
_mixer_context: Some(mixer_context),
|
||||
sounds: HashMap::new(),
|
||||
next_waka_index: 0u8,
|
||||
muted: false,
|
||||
disabled: true,
|
||||
};
|
||||
if sounds.is_empty() {
|
||||
return Err(anyhow!("No sounds loaded successfully"));
|
||||
}
|
||||
|
||||
Audio {
|
||||
Ok(Audio {
|
||||
_mixer_context: Some(mixer_context),
|
||||
sounds,
|
||||
next_waka_index: 0u8,
|
||||
muted: false,
|
||||
disabled: false,
|
||||
}
|
||||
state: AudioState::Enabled { volume: DEFAULT_VOLUME },
|
||||
})
|
||||
}
|
||||
|
||||
fn load_sound(sound_type: Sound) -> Result<Chunk> {
|
||||
let asset = Asset::SoundFile(sound_type);
|
||||
let data = asset
|
||||
.get_bytes()
|
||||
.map_err(|e| anyhow!("Failed to get bytes for {:?}: {}", sound_type, e))?;
|
||||
let rwops = RWops::from_bytes(&data).map_err(|e| anyhow!("Failed to create RWops for {:?}: {}", sound_type, e))?;
|
||||
rwops
|
||||
.load_wav()
|
||||
.map_err(|e| anyhow!("Failed to load wav for {:?}: {}", sound_type, e))
|
||||
}
|
||||
|
||||
/// Plays the next waka eating sound in the cycle of four variants.
|
||||
@@ -186,7 +158,7 @@ impl Audio {
|
||||
/// advances to the next variant. Silently returns if audio is disabled, muted,
|
||||
/// or no sounds were loaded successfully.
|
||||
pub fn waka(&mut self) {
|
||||
if self.disabled || self.muted || self.sounds.is_empty() {
|
||||
if !matches!(self.state, AudioState::Enabled { .. }) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -200,12 +172,12 @@ impl Audio {
|
||||
}
|
||||
}
|
||||
}
|
||||
self.next_waka_index = (self.next_waka_index + 1) & 3;
|
||||
self.next_waka_index = (self.next_waka_index + 1) % WAKA_SOUND_COUNT;
|
||||
}
|
||||
|
||||
/// Plays the provided sound effect once.
|
||||
pub fn play(&mut self, sound: Sound) {
|
||||
if self.disabled || self.muted {
|
||||
if !matches!(self.state, AudioState::Enabled { .. }) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -216,21 +188,21 @@ impl Audio {
|
||||
|
||||
/// Halts all currently playing audio channels.
|
||||
pub fn stop_all(&mut self) {
|
||||
if !self.disabled {
|
||||
if self.state != AudioState::Disabled {
|
||||
mixer::Channel::all().halt();
|
||||
}
|
||||
}
|
||||
|
||||
/// Pauses all currently playing audio channels.
|
||||
pub fn pause_all(&mut self) {
|
||||
if !self.disabled {
|
||||
if self.state != AudioState::Disabled {
|
||||
mixer::Channel::all().pause();
|
||||
}
|
||||
}
|
||||
|
||||
/// Resumes all currently playing audio channels.
|
||||
pub fn resume_all(&mut self) {
|
||||
if !self.disabled {
|
||||
if self.state != AudioState::Disabled {
|
||||
mixer::Channel::all().resume();
|
||||
}
|
||||
}
|
||||
@@ -241,15 +213,23 @@ impl Audio {
|
||||
/// their default volume (32) when unmuting. The mute state is tracked internally
|
||||
/// regardless of whether audio is disabled, allowing the state to be preserved.
|
||||
pub fn set_mute(&mut self, mute: bool) {
|
||||
if !self.disabled {
|
||||
let channels = 4;
|
||||
let volume = if mute { 0 } else { 32 };
|
||||
for i in 0..channels {
|
||||
mixer::Channel(i).set_volume(volume);
|
||||
match (mute, self.state) {
|
||||
// Mute
|
||||
(true, AudioState::Enabled { volume }) => {
|
||||
self.state = AudioState::Muted { previous_volume: volume };
|
||||
for i in 0..AUDIO_CHANNELS {
|
||||
mixer::Channel(i).set_volume(0);
|
||||
}
|
||||
}
|
||||
// Unmute
|
||||
(false, AudioState::Muted { previous_volume }) => {
|
||||
self.state = AudioState::Enabled { volume: previous_volume };
|
||||
for i in 0..AUDIO_CHANNELS {
|
||||
mixer::Channel(i).set_volume(previous_volume as i32);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
self.muted = mute;
|
||||
}
|
||||
|
||||
/// Returns the current mute state regardless of whether audio is functional.
|
||||
@@ -257,7 +237,7 @@ impl Audio {
|
||||
/// This tracks the user's mute preference and will return `true` if muted
|
||||
/// even when the audio system is disabled due to initialization failures.
|
||||
pub fn is_muted(&self) -> bool {
|
||||
self.muted
|
||||
matches!(self.state, AudioState::Muted { .. })
|
||||
}
|
||||
|
||||
/// Returns whether the audio system failed to initialize and is non-functional.
|
||||
@@ -266,6 +246,6 @@ impl Audio {
|
||||
/// audio device, or failure to load any sound assets. When disabled, all
|
||||
/// audio operations become no-ops.
|
||||
pub fn is_disabled(&self) -> bool {
|
||||
self.disabled
|
||||
matches!(self.state, AudioState::Disabled)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,9 +53,9 @@ pub mod animation {
|
||||
/// Frightened ghost animation speed (ticks per frame at 60 ticks/sec)
|
||||
pub const GHOST_FRIGHTENED_SPEED: u16 = 12;
|
||||
/// Time in ticks for frightened ghosts to return to normal
|
||||
pub const GHOST_FRIGHTENED_TICKS: u32 = 300;
|
||||
pub const GHOST_FRIGHTENED_TICKS: u32 = 5 * 60;
|
||||
/// Time in ticks when frightened ghosts start flashing
|
||||
pub const GHOST_FRIGHTENED_FLASH_START_TICKS: u32 = GHOST_FRIGHTENED_TICKS - 120;
|
||||
pub const GHOST_FRIGHTENED_FLASH_START_TICKS: u32 = GHOST_FRIGHTENED_TICKS - 2 * 60;
|
||||
}
|
||||
|
||||
/// The size of the canvas, in pixels.
|
||||
@@ -75,13 +75,15 @@ pub const LARGE_CANVAS_SIZE: UVec2 = UVec2::new(
|
||||
pub mod collider {
|
||||
use super::CELL_SIZE;
|
||||
|
||||
/// Collider size for player and ghosts (1.375x cell size)
|
||||
pub const PLAYER_GHOST_SIZE: f32 = CELL_SIZE as f32 * 1.375;
|
||||
/// Collider size for pellets (0.4x cell size)
|
||||
/// Collider size for player and ghosts
|
||||
pub const PLAYER_SIZE: f32 = CELL_SIZE as f32 * 1.385;
|
||||
/// Collider size for ghosts
|
||||
pub const GHOST_SIZE: f32 = CELL_SIZE as f32 * 1.55;
|
||||
/// Collider size for pellets
|
||||
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
|
||||
pub const POWER_PELLET_SIZE: f32 = CELL_SIZE as f32 * 0.95;
|
||||
/// Collider size for fruits (0.8x cell size)
|
||||
/// Collider size for fruits
|
||||
pub const FRUIT_SIZE: f32 = CELL_SIZE as f32 * 1.375;
|
||||
}
|
||||
|
||||
@@ -148,7 +150,7 @@ pub const RAW_BOARD: [&str; BOARD_CELL_SIZE.y as usize] = [
|
||||
/// Game initialization constants
|
||||
pub mod startup {
|
||||
/// Number of frames for the startup sequence (3 seconds at 60 FPS)
|
||||
pub const STARTUP_FRAMES: u32 = 60 * 3;
|
||||
pub const STARTUP_FRAMES: u32 = 60 * 4;
|
||||
}
|
||||
|
||||
/// Game mechanics constants
|
||||
|
||||
@@ -54,7 +54,6 @@ pub enum AssetError {
|
||||
#[derive(thiserror::Error, Debug)]
|
||||
pub enum PlatformError {
|
||||
#[error("Console initialization failed: {0}")]
|
||||
#[cfg(any(windows, target_os = "emscripten"))]
|
||||
ConsoleInit(String),
|
||||
}
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ pub enum GameCommand {
|
||||
/// TODO: Display pause state, fix debug rendering pause distress
|
||||
TogglePause,
|
||||
/// Toggle fullscreen mode (desktop only)
|
||||
#[cfg(not(target_os = "emscripten"))]
|
||||
ToggleFullscreen,
|
||||
}
|
||||
|
||||
|
||||
@@ -381,7 +381,7 @@ impl Game {
|
||||
directional_animation: player_animation,
|
||||
entity_type: EntityType::Player,
|
||||
collider: Collider {
|
||||
size: constants::collider::PLAYER_GHOST_SIZE,
|
||||
size: constants::collider::PLAYER_SIZE,
|
||||
},
|
||||
pacman_collider: PacmanCollider,
|
||||
}
|
||||
@@ -629,7 +629,7 @@ impl Game {
|
||||
directional_animation: animations,
|
||||
entity_type: EntityType::Ghost,
|
||||
collider: Collider {
|
||||
size: constants::collider::PLAYER_GHOST_SIZE,
|
||||
size: constants::collider::GHOST_SIZE,
|
||||
},
|
||||
ghost_collider: GhostCollider,
|
||||
ghost_state: GhostState::Normal,
|
||||
|
||||
@@ -20,6 +20,7 @@ pub fn sleep(duration: Duration, focused: bool) {
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(unused_variables)]
|
||||
pub fn init_console(force_console: bool) -> Result<(), PlatformError> {
|
||||
use crate::formatter::CustomFormatter;
|
||||
use tracing::Level;
|
||||
|
||||
@@ -27,7 +27,7 @@ fn calculate_fruit_sprite_position(index: u32) -> Vec2 {
|
||||
let sprite_spacing = CELL_SIZE + CELL_SIZE / 2; // 1.5 cells between sprites
|
||||
|
||||
let x = start_x - ((index as f32) * (sprite_spacing as f32 * 1.5)).round() as u32;
|
||||
let y = start_y - CELL_SIZE / 2;
|
||||
let y = start_y - (1 + CELL_SIZE / 2);
|
||||
|
||||
Vec2::new((x - CELL_SIZE) as f32, (y + CELL_SIZE) as f32)
|
||||
}
|
||||
|
||||
@@ -3,12 +3,14 @@ use bevy_ecs::{
|
||||
observer::Trigger,
|
||||
system::{Commands, NonSendMut, Res},
|
||||
};
|
||||
use rand::Rng;
|
||||
use strum_macros::IntoStaticStr;
|
||||
use tracing::debug;
|
||||
|
||||
use crate::{
|
||||
constants,
|
||||
map::builder::Map,
|
||||
platform::rng,
|
||||
systems::{common::bundles::ItemBundle, Collider, Position, Renderable, TimeToLive},
|
||||
texture::{
|
||||
sprite::SpriteAtlas,
|
||||
@@ -112,7 +114,9 @@ pub fn spawn_fruit_observer(
|
||||
item_collider: ItemCollider,
|
||||
};
|
||||
|
||||
commands.spawn(bundle)
|
||||
let lifetime_ticks = (rng().random_range(9f32..10f32) * 60f32).round() as u32;
|
||||
|
||||
commands.spawn((bundle, TimeToLive::new(lifetime_ticks)))
|
||||
}
|
||||
SpawnTrigger::Bonus { position, value, ttl } => {
|
||||
let sprite = &atlas
|
||||
|
||||
Reference in New Issue
Block a user