refactor: huge refactor into node/graph-based movement system

This commit is contained in:
2025-07-28 12:23:57 -05:00
parent 413f9f156f
commit 464d6f9ca6
24 changed files with 868 additions and 2067 deletions

View File

@@ -1,10 +1,6 @@
//! This module defines the `Direction` enum, which is used to represent the
//! direction of an entity.
use glam::IVec2;
use sdl2::keyboard::Keycode;
/// An enum representing the direction of an entity.
#[derive(Debug, Copy, Clone, PartialEq)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum Direction {
Up,
Down,
@@ -13,48 +9,29 @@ pub enum Direction {
}
impl Direction {
/// Returns the angle of the direction in degrees.
pub fn angle(&self) -> f64 {
match self {
Direction::Right => 0f64,
Direction::Down => 90f64,
Direction::Left => 180f64,
Direction::Up => 270f64,
}
}
/// Returns the offset of the direction as a tuple of (x, y).
pub fn offset(&self) -> IVec2 {
match self {
Direction::Right => IVec2::new(1, 0),
Direction::Down => IVec2::new(0, 1),
Direction::Left => IVec2::new(-1, 0),
Direction::Up => IVec2::new(0, -1),
}
}
/// Returns the opposite direction.
pub fn opposite(&self) -> Direction {
match self {
Direction::Right => Direction::Left,
Direction::Up => Direction::Down,
Direction::Down => Direction::Up,
Direction::Left => Direction::Right,
Direction::Up => Direction::Down,
Direction::Right => Direction::Left,
}
}
/// Creates a `Direction` from a `Keycode`.
///
/// # Arguments
///
/// * `keycode` - The keycode to convert.
pub fn from_keycode(keycode: Keycode) -> Option<Direction> {
match keycode {
Keycode::D | Keycode::Right => Some(Direction::Right),
Keycode::A | Keycode::Left => Some(Direction::Left),
Keycode::W | Keycode::Up => Some(Direction::Up),
Keycode::S | Keycode::Down => Some(Direction::Down),
_ => None,
pub fn to_ivec2(&self) -> IVec2 {
(*self).into()
}
}
impl From<Direction> for IVec2 {
fn from(dir: Direction) -> Self {
match dir {
Direction::Up => -IVec2::Y,
Direction::Down => IVec2::Y,
Direction::Left => -IVec2::X,
Direction::Right => IVec2::X,
}
}
}
pub const DIRECTIONS: [Direction; 4] = [Direction::Up, Direction::Down, Direction::Left, Direction::Right];

View File

@@ -1,110 +0,0 @@
//! Edible entity for Pac-Man: pellets, power pellets, and fruits.
use crate::constants::{FruitType, MapTile, BOARD_CELL_SIZE};
use crate::entity::{Entity, Renderable, StaticEntity};
use crate::map::Map;
use crate::texture::animated::AnimatedTexture;
use crate::texture::blinking::BlinkingTexture;
use anyhow::Result;
use glam::{IVec2, UVec2};
use sdl2::render::WindowCanvas;
use std::cell::RefCell;
use std::rc::Rc;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EdibleKind {
Pellet,
PowerPellet,
Fruit(FruitType),
}
pub enum EdibleSprite {
Pellet(AnimatedTexture),
PowerPellet(BlinkingTexture),
}
pub struct Edible {
pub base: StaticEntity,
pub kind: EdibleKind,
pub sprite: EdibleSprite,
}
impl Edible {
pub fn new_pellet(cell_position: UVec2, sprite: AnimatedTexture) -> Self {
let pixel_position = Map::cell_to_pixel(cell_position);
Edible {
base: StaticEntity::new(pixel_position, cell_position),
kind: EdibleKind::Pellet,
sprite: EdibleSprite::Pellet(sprite),
}
}
pub fn new_power_pellet(cell_position: UVec2, sprite: BlinkingTexture) -> Self {
let pixel_position = Map::cell_to_pixel(cell_position);
Edible {
base: StaticEntity::new(pixel_position, cell_position),
kind: EdibleKind::PowerPellet,
sprite: EdibleSprite::PowerPellet(sprite),
}
}
/// Checks collision with Pac-Man (or any entity)
pub fn collide(&self, pacman: &dyn Entity) -> bool {
self.base.cell_position == pacman.base().cell_position
}
}
impl Entity for Edible {
fn base(&self) -> &StaticEntity {
&self.base
}
}
impl Renderable for Edible {
fn render(&mut self, canvas: &mut WindowCanvas) -> Result<()> {
let pos = self.base.pixel_position;
let dest = match &mut self.sprite {
EdibleSprite::Pellet(sprite) => {
let tile = sprite.current_tile();
let x = pos.x + ((crate::constants::CELL_SIZE as i32 - tile.size.x as i32) / 2);
let y = pos.y + ((crate::constants::CELL_SIZE as i32 - tile.size.y as i32) / 2);
sdl2::rect::Rect::new(x, y, tile.size.x as u32, tile.size.y as u32)
}
EdibleSprite::PowerPellet(sprite) => {
let tile = sprite.animation.current_tile();
let x = pos.x + ((crate::constants::CELL_SIZE as i32 - tile.size.x as i32) / 2);
let y = pos.y + ((crate::constants::CELL_SIZE as i32 - tile.size.y as i32) / 2);
sdl2::rect::Rect::new(x, y, tile.size.x as u32, tile.size.y as u32)
}
};
match &mut self.sprite {
EdibleSprite::Pellet(sprite) => sprite.render(canvas, dest),
EdibleSprite::PowerPellet(sprite) => sprite.render(canvas, dest),
}
}
}
/// Reconstruct all edibles from the original map layout
pub fn reconstruct_edibles(
map: Rc<RefCell<Map>>,
pellet_sprite: AnimatedTexture,
power_pellet_sprite: BlinkingTexture,
_fruit_sprite: AnimatedTexture,
) -> Vec<Edible> {
let mut edibles = Vec::new();
for x in 0..BOARD_CELL_SIZE.x {
for y in 0..BOARD_CELL_SIZE.y {
let tile = map.borrow().get_tile(IVec2::new(x as i32, y as i32));
match tile {
Some(MapTile::Pellet) => {
edibles.push(Edible::new_pellet(UVec2::new(x, y), pellet_sprite.clone()));
}
Some(MapTile::PowerPellet) => {
edibles.push(Edible::new_power_pellet(UVec2::new(x, y), power_pellet_sprite.clone()));
}
// Fruits can be added here if you have fruit positions
_ => {}
}
}
}
edibles
}

View File

@@ -1,510 +0,0 @@
use rand::rngs::SmallRng;
use rand::Rng;
use rand::SeedableRng;
use crate::constants::MapTile;
use crate::constants::BOARD_CELL_SIZE;
use crate::entity::direction::Direction;
use crate::entity::pacman::Pacman;
use crate::entity::speed::SimpleTickModulator;
use crate::entity::{Entity, MovableEntity, Moving, Renderable};
use crate::map::Map;
use crate::texture::{
animated::AnimatedTexture, blinking::BlinkingTexture, directional::DirectionalAnimatedTexture, get_atlas_tile,
sprite::SpriteAtlas,
};
use anyhow::Result;
use glam::{IVec2, UVec2};
use sdl2::pixels::Color;
use sdl2::render::WindowCanvas;
use std::cell::RefCell;
use std::rc::Rc;
/// The different modes a ghost can be in
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum GhostMode {
/// Chase mode - ghost actively pursues Pac-Man using its unique strategy
Chase,
/// Scatter mode - ghost heads to its home corner
Scatter,
/// Frightened mode - ghost moves randomly and can be eaten
Frightened,
/// Eyes mode - ghost returns to the ghost house after being eaten
Eyes,
/// House mode - ghost is in the ghost house, waiting to exit
House(HouseMode),
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum HouseMode {
Entering,
Exiting,
Waiting,
}
/// The different ghost personalities
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum GhostType {
Blinky, // Red - Shadow
Pinky, // Pink - Speedy
Inky, // Cyan - Bashful
Clyde, // Orange - Pokey
}
impl GhostType {
/// Returns the color of the ghost.
pub fn color(&self) -> Color {
match self {
GhostType::Blinky => Color::RGB(255, 0, 0),
GhostType::Pinky => Color::RGB(255, 184, 255),
GhostType::Inky => Color::RGB(0, 255, 255),
GhostType::Clyde => Color::RGB(255, 184, 82),
}
}
}
/// Base ghost struct that contains common functionality
pub struct Ghost {
/// Shared movement and position fields.
pub base: MovableEntity,
/// The current mode of the ghost
pub mode: GhostMode,
/// The type/personality of this ghost
pub ghost_type: GhostType,
/// Reference to Pac-Man for targeting
pub pacman: Rc<RefCell<Pacman>>,
pub texture: DirectionalAnimatedTexture,
pub frightened_texture: BlinkingTexture,
pub eyes_texture: DirectionalAnimatedTexture,
pub house_offset: i32,
pub current_house_offset: i32,
}
impl Ghost {
/// Creates a new ghost instance
pub fn new(
ghost_type: GhostType,
starting_position: UVec2,
atlas: Rc<RefCell<SpriteAtlas>>,
map: Rc<RefCell<Map>>,
pacman: Rc<RefCell<Pacman>>,
house_offset: i32,
) -> Ghost {
let pixel_position = Map::cell_to_pixel(starting_position);
let name = match ghost_type {
GhostType::Blinky => "blinky",
GhostType::Pinky => "pinky",
GhostType::Inky => "inky",
GhostType::Clyde => "clyde",
};
let get = |dir: &str, suffix: &str| get_atlas_tile(&atlas, &format!("ghost/{name}/{dir}_{suffix}.png"));
let texture = DirectionalAnimatedTexture::new(
vec![get("up", "a"), get("up", "b")],
vec![get("down", "a"), get("down", "b")],
vec![get("left", "a"), get("left", "b")],
vec![get("right", "a"), get("right", "b")],
25,
);
let frightened_texture = BlinkingTexture::new(
AnimatedTexture::new(
vec![
get_atlas_tile(&atlas, "ghost/frightened/blue_a.png"),
get_atlas_tile(&atlas, "ghost/frightened/blue_b.png"),
],
10,
),
45,
15,
);
let eyes_get = |dir: &str| get_atlas_tile(&atlas, &format!("ghost/eyes/{dir}.png"));
let eyes_texture = DirectionalAnimatedTexture::new(
vec![eyes_get("up")],
vec![eyes_get("down")],
vec![eyes_get("left")],
vec![eyes_get("right")],
0,
);
Ghost {
base: MovableEntity::new(
pixel_position,
starting_position,
Direction::Left,
SimpleTickModulator::new(0.9375),
map,
),
mode: GhostMode::House(HouseMode::Waiting),
ghost_type,
pacman,
texture,
frightened_texture,
eyes_texture,
house_offset,
current_house_offset: house_offset,
}
}
/// Gets the target tile for this ghost based on its current mode
pub fn get_target_tile(&self) -> Option<IVec2> {
match self.mode {
GhostMode::Scatter => Some(self.get_scatter_target()),
GhostMode::Chase => Some(self.get_chase_target()),
GhostMode::Frightened => Some(self.get_random_target()),
GhostMode::Eyes => Some(self.get_house_target()),
GhostMode::House(_) => None,
}
}
/// Gets this ghost's home corner target for scatter mode
fn get_scatter_target(&self) -> IVec2 {
match self.ghost_type {
GhostType::Blinky => IVec2::new(25, 0), // Top right
GhostType::Pinky => IVec2::new(2, 0), // Top left
GhostType::Inky => IVec2::new(27, 35), // Bottom right
GhostType::Clyde => IVec2::new(0, 35), // Bottom left
}
}
/// Gets a random adjacent tile for frightened mode
fn get_random_target(&self) -> IVec2 {
let mut rng = SmallRng::from_os_rng();
let mut possible_moves = Vec::new();
// Check all four directions
for dir in &[Direction::Up, Direction::Down, Direction::Left, Direction::Right] {
// Don't allow reversing direction
if *dir == self.base.direction.opposite() {
continue;
}
let next_cell = self.base.next_cell(Some(*dir));
if !matches!(self.base.map.borrow().get_tile(next_cell), Some(MapTile::Wall)) {
possible_moves.push(next_cell);
}
}
if possible_moves.is_empty() {
// No valid moves, must reverse
self.base.next_cell(Some(self.base.direction.opposite()))
} else {
// Choose a random valid move
possible_moves[rng.random_range(0..possible_moves.len())]
}
}
/// Gets the ghost house target for returning eyes
fn get_house_target(&self) -> IVec2 {
IVec2::new(13, 14) // Center of ghost house
}
/// Gets this ghost's chase mode target based on its personality
fn get_chase_target(&self) -> IVec2 {
let pacman = self.pacman.borrow();
let pacman_cell = pacman.base().cell_position;
let pacman_direction = pacman.base.direction;
match self.ghost_type {
GhostType::Blinky => {
// Blinky (Red) - Directly targets Pac-Man's current position
IVec2::new(pacman_cell.x as i32, pacman_cell.y as i32)
}
GhostType::Pinky => {
// Pinky (Pink) - Targets 4 cells ahead of Pac-Man in his direction
let offset = pacman_direction.offset();
let target_x = (pacman_cell.x as i32) + (offset.x * 4);
let target_y = (pacman_cell.y as i32) + (offset.y * 4);
IVec2::new(target_x, target_y)
}
GhostType::Inky => {
// Inky (Cyan) - Uses Blinky's position and Pac-Man's position to calculate target
// For now, just target Pac-Man with some randomness
let mut rng = SmallRng::from_os_rng();
let random_offset_x = rng.random_range(-2..=2);
let random_offset_y = rng.random_range(-2..=2);
IVec2::new(
(pacman_cell.x as i32) + random_offset_x,
(pacman_cell.y as i32) + random_offset_y,
)
}
GhostType::Clyde => {
// Clyde (Orange) - Targets Pac-Man when far, runs to scatter corner when close
let distance = ((self.base.base.cell_position.x as i32 - pacman_cell.x as i32).pow(2)
+ (self.base.base.cell_position.y as i32 - pacman_cell.y as i32).pow(2))
as f32;
let distance = distance.sqrt();
if distance > 8.0 {
// Far from Pac-Man - chase
IVec2::new(pacman_cell.x as i32, pacman_cell.y as i32)
} else {
// Close to Pac-Man - scatter to bottom left
IVec2::new(0, 35)
}
}
}
}
/// Calculates the path to the target tile using the A* algorithm.
pub fn get_path_to_target(&self, target: UVec2) -> Option<(Vec<UVec2>, u32)> {
let start = self.base.base.cell_position;
let map = self.base.map.borrow();
use pathfinding::prelude::dijkstra;
dijkstra(
&start,
|&p| {
let mut successors = vec![];
let tile = map.get_tile(IVec2::new(p.x as i32, p.y as i32));
// Tunnel wrap: if currently in a tunnel, add the opposite exit as a neighbor
if let Some(MapTile::Tunnel) = tile {
if p.x == 0 {
successors.push((UVec2::new(BOARD_CELL_SIZE.x - 2, p.y), 1));
} else if p.x == BOARD_CELL_SIZE.x - 1 {
successors.push((UVec2::new(1, p.y), 1));
}
}
for dir in &[Direction::Up, Direction::Down, Direction::Left, Direction::Right] {
let offset = dir.offset();
let next_p = IVec2::new(p.x as i32 + offset.x, p.y as i32 + offset.y);
if let Some(tile) = map.get_tile(next_p) {
if tile == MapTile::Wall {
continue;
}
let next_u = UVec2::new(next_p.x as u32, next_p.y as u32);
successors.push((next_u, 1));
}
}
successors
},
|&p| p == target,
)
}
/// Changes the ghost's mode and handles direction reversal
pub fn set_mode(&mut self, new_mode: GhostMode) {
// Don't reverse if going to/from frightened or if in house
let should_reverse = !matches!(self.mode, GhostMode::House(_))
&& !matches!(new_mode, GhostMode::House(_))
&& !matches!(self.mode, GhostMode::Frightened)
&& !matches!(new_mode, GhostMode::Frightened);
self.mode = new_mode;
self.base.speed.set_speed(match new_mode {
GhostMode::Chase => 0.9375,
GhostMode::Scatter => 0.85,
GhostMode::Frightened => 0.7,
GhostMode::Eyes => 1.5,
GhostMode::House(_) => 0.7,
});
if should_reverse {
self.base.set_direction_if_valid(self.base.direction.opposite());
}
}
pub fn tick(&mut self) {
if let GhostMode::House(house_mode) = self.mode {
match house_mode {
HouseMode::Waiting => {
// Ghosts in waiting mode move up and down
if self.base.is_grid_aligned() {
self.base.update_cell_position();
// Simple up and down movement
let current_pos = self.base.base.cell_position;
let start_pos = UVec2::new(13, 14); // Center of ghost house
if current_pos.y > start_pos.y + 1 {
// Too far down, move up
self.base.set_direction_if_valid(Direction::Up);
} else if current_pos.y < start_pos.y - 1 {
// Too far up, move down
self.base.set_direction_if_valid(Direction::Down);
} else if self.base.direction == Direction::Up {
// At top, switch to down
self.base.set_direction_if_valid(Direction::Down);
} else if self.base.direction == Direction::Down {
// At bottom, switch to up
self.base.set_direction_if_valid(Direction::Up);
}
}
}
HouseMode::Exiting => {
// Ghosts exiting move towards the exit
if self.base.is_grid_aligned() {
self.base.update_cell_position();
let exit_pos = UVec2::new(13, 11);
let current_pos = self.base.base.cell_position;
// Determine direction to exit
if current_pos.y > exit_pos.y {
// Need to move up
self.base.set_direction_if_valid(Direction::Up);
} else if current_pos.y == exit_pos.y && current_pos.x != exit_pos.x {
// At exit level, move horizontally to center
if current_pos.x < exit_pos.x {
self.base.set_direction_if_valid(Direction::Right);
} else {
self.base.set_direction_if_valid(Direction::Left);
}
} else if current_pos == exit_pos {
// Reached exit, transition to chase mode
self.mode = GhostMode::Chase;
self.current_house_offset = 0; // Reset offset
}
}
}
HouseMode::Entering => {
// Ghosts entering move towards their starting position
if self.base.is_grid_aligned() {
self.base.update_cell_position();
let start_pos = UVec2::new(13, 14); // Center of ghost house
let current_pos = self.base.base.cell_position;
// Determine direction to starting position
if current_pos.y < start_pos.y {
// Need to move down
self.base.set_direction_if_valid(Direction::Down);
} else if current_pos.y == start_pos.y && current_pos.x != start_pos.x {
// At house level, move horizontally to center
if current_pos.x < start_pos.x {
self.base.set_direction_if_valid(Direction::Right);
} else {
self.base.set_direction_if_valid(Direction::Left);
}
} else if current_pos == start_pos {
// Reached starting position, switch to waiting
self.mode = GhostMode::House(HouseMode::Waiting);
}
}
}
}
// Update house offset for smooth transitions
if self.current_house_offset != 0 {
// Gradually reduce offset when turning
if self.base.direction == Direction::Left || self.base.direction == Direction::Right {
if self.current_house_offset > 0 {
self.current_house_offset -= 1;
} else if self.current_house_offset < 0 {
self.current_house_offset += 1;
}
}
}
self.base.tick();
self.texture.tick();
self.frightened_texture.tick();
self.eyes_texture.tick();
return;
}
// Normal ghost behavior
if self.base.is_grid_aligned() {
self.base.update_cell_position();
if !self.base.handle_tunnel() {
// Pathfinding logic (only if not in tunnel)
if let Some(target_tile) = self.get_target_tile() {
if let Some((path, _)) = self.get_path_to_target(target_tile.as_uvec2()) {
if path.len() > 1 {
let next_move = path[1];
let x = self.base.base.cell_position.x;
let y = self.base.base.cell_position.y;
let dx = next_move.x as i32 - x as i32;
let dy = next_move.y as i32 - y as i32;
let new_direction = if dx > 0 {
Direction::Right
} else if dx < 0 {
Direction::Left
} else if dy > 0 {
Direction::Down
} else {
Direction::Up
};
self.base.set_direction_if_valid(new_direction);
}
}
}
}
}
// Handle house offset transition when turning
if self.current_house_offset != 0 {
if self.base.direction == Direction::Left || self.base.direction == Direction::Right {
if self.current_house_offset > 0 {
self.current_house_offset -= 1;
} else if self.current_house_offset < 0 {
self.current_house_offset += 1;
}
}
}
self.base.tick(); // Handles wall collision and movement
self.texture.tick();
self.frightened_texture.tick();
self.eyes_texture.tick();
}
}
impl Moving for Ghost {
fn tick_movement(&mut self) {
self.base.tick_movement();
}
fn tick(&mut self) {
self.base.tick();
}
fn update_cell_position(&mut self) {
self.base.update_cell_position();
}
fn next_cell(&self, direction: Option<Direction>) -> IVec2 {
self.base.next_cell(direction)
}
fn is_wall_ahead(&self, direction: Option<Direction>) -> bool {
self.base.is_wall_ahead(direction)
}
fn handle_tunnel(&mut self) -> bool {
self.base.handle_tunnel()
}
fn is_grid_aligned(&self) -> bool {
self.base.is_grid_aligned()
}
fn set_direction_if_valid(&mut self, new_direction: Direction) -> bool {
self.base.set_direction_if_valid(new_direction)
}
}
impl Renderable for Ghost {
fn render(&mut self, canvas: &mut WindowCanvas) -> Result<()> {
let mut pos = self.base.base.pixel_position;
let dir = self.base.direction;
// Apply house offset if in house mode or transitioning
if matches!(self.mode, GhostMode::House(_)) || self.current_house_offset != 0 {
pos.x += self.current_house_offset;
}
match self.mode {
GhostMode::Frightened => {
let tile = self.frightened_texture.animation.current_tile();
let dest = sdl2::rect::Rect::new(pos.x - 4, pos.y - 4, tile.size.x as u32, tile.size.y as u32);
self.frightened_texture.render(canvas, dest)
}
GhostMode::Eyes => {
let tile = self.eyes_texture.up.first().unwrap();
let dest = sdl2::rect::Rect::new(pos.x - 4, pos.y - 4, tile.size.x as u32, tile.size.y as u32);
self.eyes_texture.render(canvas, dest, dir)
}
_ => {
let tile = self.texture.up.first().unwrap();
let dest = sdl2::rect::Rect::new(pos.x - 4, pos.y - 4, tile.size.x as u32, tile.size.y as u32);
self.texture.render(canvas, dest, dir)
}
}
}
}

274
src/entity/graph.rs Normal file
View File

@@ -0,0 +1,274 @@
use glam::Vec2;
use smallvec::SmallVec;
use super::direction::Direction;
/// A unique identifier for a node, represented by its index in the graph's storage.
pub type NodeId = usize;
/// Represents a directed edge from one node to another with a given weight (e.g., distance).
#[derive(Debug, Clone, Copy)]
pub struct Edge {
pub target: NodeId,
pub distance: f32,
pub direction: Direction,
}
#[derive(Debug)]
pub struct Node {
pub position: Vec2,
}
/// A generic, arena-based graph.
/// The graph owns all node data and connection information.
pub struct Graph {
nodes: Vec<Node>,
adjacency_list: Vec<SmallVec<[Edge; 4]>>,
}
impl Graph {
/// Creates a new, empty graph.
pub fn new() -> Self {
Graph {
nodes: Vec::new(),
adjacency_list: Vec::new(),
}
}
/// Adds a new node with the given data to the graph and returns its ID.
pub fn add_node(&mut self, data: Node) -> NodeId {
let id = self.nodes.len();
self.nodes.push(data);
self.adjacency_list.push(SmallVec::new());
id
}
/// Adds a directed edge between two nodes.
pub fn add_edge(
&mut self,
from: NodeId,
to: NodeId,
distance: Option<f32>,
direction: Direction,
) -> Result<(), &'static str> {
let edge = Edge {
target: to,
distance: match distance {
Some(distance) => {
if distance <= 0.0 {
return Err("Edge distance must be positive.");
}
distance
}
None => {
// If no distance is provided, calculate it based on the positions of the nodes
let from_pos = self.nodes[from].position;
let to_pos = self.nodes[to].position;
from_pos.distance(to_pos)
}
},
direction,
};
if from >= self.adjacency_list.len() {
return Err("From node does not exist.");
}
let adjacency_list = &mut self.adjacency_list[from];
// Check if the edge already exists in this direction or to the same target
if let Some(err) = adjacency_list.iter().find_map(|e| {
if e.direction == direction {
Some(Err("Edge already exists in this direction."))
} else if e.target == to {
Some(Err("Edge already exists."))
} else {
None
}
}) {
return err;
}
adjacency_list.push(edge);
Ok(())
}
/// Retrieves an immutable reference to a node's data.
pub fn get_node(&self, id: NodeId) -> Option<&Node> {
self.nodes.get(id)
}
pub fn node_count(&self) -> usize {
self.nodes.len()
}
/// Finds a specific edge from a source node to a target node.
pub fn find_edge(&self, from: NodeId, to: NodeId) -> Option<&Edge> {
self.adjacency_list.get(from)?.iter().find(|edge| edge.target == to)
}
pub fn find_edge_in_direction(&self, from: NodeId, direction: Direction) -> Option<&Edge> {
self.adjacency_list.get(from)?.iter().find(|edge| edge.direction == direction)
}
}
// Default implementation for creating an empty graph.
impl Default for Graph {
fn default() -> Self {
Self::new()
}
}
// --- Traversal State and Logic ---
/// Represents the traverser's current position within the graph.
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum Position {
/// The traverser is located exactly at a node.
AtNode(NodeId),
/// The traverser is on an edge between two nodes.
BetweenNodes {
from: NodeId,
to: NodeId,
/// The floating-point distance traversed along the edge from the `from` node.
traversed: f32,
},
}
impl Position {
pub fn is_at_node(&self) -> bool {
matches!(self, Position::AtNode(_))
}
pub fn from_node_id(&self) -> NodeId {
match self {
Position::AtNode(id) => *id,
Position::BetweenNodes { from, .. } => *from,
}
}
pub fn to_node_id(&self) -> Option<NodeId> {
match self {
Position::AtNode(_) => None,
Position::BetweenNodes { to, .. } => Some(*to),
}
}
pub fn is_stopped(&self) -> bool {
matches!(self, Position::AtNode(_))
}
}
/// Manages a traversal session over a graph.
/// It holds a reference to the graph and the current position state.
pub struct Traverser {
pub position: Position,
pub direction: Direction,
pub next_direction: Option<(Direction, u8)>,
}
impl Traverser {
/// Creates a new traverser starting at the given node ID.
pub fn new(graph: &Graph, start_node: NodeId, initial_direction: Direction) -> Self {
let mut traverser = Traverser {
position: Position::AtNode(start_node),
direction: initial_direction,
next_direction: Some((initial_direction, 1)),
};
// This will kickstart the traverser into motion
traverser.advance(graph, 0.0);
traverser
}
pub fn set_next_direction(&mut self, new_direction: Direction) {
if self.direction != new_direction {
self.next_direction = Some((new_direction, 30));
}
}
pub fn advance(&mut self, graph: &Graph, distance: f32) {
// Decrement the remaining frames for the next direction
if let Some((direction, remaining)) = self.next_direction {
if remaining > 0 {
self.next_direction = Some((direction, remaining - 1));
} else {
self.next_direction = None;
}
}
match self.position {
Position::AtNode(node_id) => {
// We're not moving, but a buffered direction is available.
if let Some((next_direction, _)) = self.next_direction {
if let Some(edge) = graph.find_edge_in_direction(node_id, next_direction) {
// Start moving in that direction
self.position = Position::BetweenNodes {
from: node_id,
to: edge.target,
traversed: distance.max(0.0),
};
self.direction = next_direction;
}
self.next_direction = None; // Consume the buffered direction regardless of whether we started moving with it
}
}
Position::BetweenNodes { from, to, traversed } => {
// There is no point in any of the next logic if we don't travel at all
if distance <= 0.0 {
return;
}
let edge = graph
.find_edge(from, to)
.expect("Inconsistent state: Traverser is on a non-existent edge.");
let new_traversed = traversed + distance;
if new_traversed < edge.distance {
// Still on the same edge, just update the distance.
self.position = Position::BetweenNodes {
from,
to,
traversed: new_traversed,
};
} else {
let overflow = new_traversed - edge.distance;
let mut moved = false;
// If we buffered a direction, try to find an edge in that direction
if let Some((next_dir, _)) = self.next_direction {
if let Some(edge) = graph.find_edge_in_direction(to, next_dir) {
self.position = Position::BetweenNodes {
from: to,
to: edge.target,
traversed: overflow,
};
self.direction = next_dir; // Remember our new direction
self.next_direction = None; // Consume the buffered direction
moved = true;
}
}
// If we didn't move, try to continue in the current direction
if !moved {
if let Some(edge) = graph.find_edge_in_direction(to, self.direction) {
self.position = Position::BetweenNodes {
from: to,
to: edge.target,
traversed: overflow,
};
} else {
self.position = Position::AtNode(to);
self.next_direction = None;
}
}
}
}
}
}
}

View File

@@ -1,205 +1,3 @@
pub mod direction;
pub mod edible;
pub mod ghost;
pub mod graph;
pub mod pacman;
pub mod speed;
use crate::{
constants::{MapTile, BOARD_CELL_OFFSET, BOARD_CELL_SIZE, CELL_SIZE},
entity::{direction::Direction, speed::SimpleTickModulator},
map::Map,
};
use anyhow::Result;
use glam::{IVec2, UVec2};
use sdl2::render::WindowCanvas;
use std::cell::RefCell;
use std::rc::Rc;
/// A trait for game objects that can be moved and rendered.
pub trait Entity {
/// Returns a reference to the base entity (position, etc).
fn base(&self) -> &StaticEntity;
/// Returns true if the entity is colliding with the other entity.
fn is_colliding(&self, other: &dyn Entity) -> bool {
let a = self.base().cell_position;
let b = other.base().cell_position;
a == b
}
}
/// A trait for entities that can move and interact with the map.
pub trait Moving {
fn tick(&mut self) {
self.base_tick();
}
fn base_tick(&mut self) {
if self.is_grid_aligned() {
self.on_grid_aligned();
}
self.tick_movement();
}
/// Called when the entity is grid-aligned. Default does nothing.
fn on_grid_aligned(&mut self) {}
/// Handles movement and wall collision. Default uses tick logic from MovableEntity.
fn tick_movement(&mut self);
fn update_cell_position(&mut self);
fn next_cell(&self, direction: Option<Direction>) -> IVec2;
fn is_wall_ahead(&self, direction: Option<Direction>) -> bool;
fn handle_tunnel(&mut self) -> bool;
fn is_grid_aligned(&self) -> bool;
fn set_direction_if_valid(&mut self, new_direction: Direction) -> bool;
}
/// Trait for entities that support queued direction changes.
pub trait QueuedDirection: Moving {
fn next_direction(&self) -> Option<Direction>;
fn set_next_direction(&mut self, dir: Option<Direction>);
/// Handles a requested direction change if possible.
fn handle_direction_change(&mut self) -> bool {
if let Some(next_direction) = self.next_direction() {
if self.set_direction_if_valid(next_direction) {
self.set_next_direction(None);
return true;
}
}
false
}
}
/// A struct for static (non-moving) entities with position only.
pub struct StaticEntity {
pub pixel_position: IVec2,
pub cell_position: UVec2,
}
impl StaticEntity {
pub fn new(pixel_position: IVec2, cell_position: UVec2) -> Self {
Self {
pixel_position,
cell_position,
}
}
}
/// A struct for movable game entities with position, direction, speed, and modulation.
pub struct MovableEntity {
pub base: StaticEntity,
pub direction: Direction,
pub speed: SimpleTickModulator,
pub in_tunnel: bool,
pub map: Rc<RefCell<Map>>,
}
impl MovableEntity {
pub fn new(
pixel_position: IVec2,
cell_position: UVec2,
direction: Direction,
speed: SimpleTickModulator,
map: Rc<RefCell<Map>>,
) -> Self {
Self {
base: StaticEntity::new(pixel_position, cell_position),
direction,
speed,
in_tunnel: false,
map,
}
}
/// Returns the position within the current cell, in pixels.
pub fn internal_position(&self) -> UVec2 {
UVec2::new(
(self.base.pixel_position.x as u32) % CELL_SIZE,
(self.base.pixel_position.y as u32) % CELL_SIZE,
)
}
}
impl Entity for MovableEntity {
fn base(&self) -> &StaticEntity {
&self.base
}
}
impl Moving for MovableEntity {
fn tick_movement(&mut self) {
if self.speed.next() && !self.is_wall_ahead(None) {
match self.direction {
Direction::Right => self.base.pixel_position.x += 1,
Direction::Left => self.base.pixel_position.x -= 1,
Direction::Up => self.base.pixel_position.y -= 1,
Direction::Down => self.base.pixel_position.y += 1,
}
if self.is_grid_aligned() {
self.update_cell_position();
}
}
if self.is_grid_aligned() {
self.update_cell_position();
}
}
fn update_cell_position(&mut self) {
self.base.cell_position = UVec2::new(
(self.base.pixel_position.x as u32 / CELL_SIZE) - BOARD_CELL_OFFSET.x,
(self.base.pixel_position.y as u32 / CELL_SIZE) - BOARD_CELL_OFFSET.y,
);
}
fn next_cell(&self, direction: Option<Direction>) -> IVec2 {
let IVec2 { x, y } = direction.unwrap_or(self.direction).offset();
IVec2::new(self.base.cell_position.x as i32 + x, self.base.cell_position.y as i32 + y)
}
fn is_wall_ahead(&self, direction: Option<Direction>) -> bool {
let next_cell = self.next_cell(direction);
matches!(self.map.borrow().get_tile(next_cell), Some(MapTile::Wall))
}
fn handle_tunnel(&mut self) -> bool {
let x = self.base.cell_position.x;
let at_left_tunnel = x == 0;
let at_right_tunnel = x == BOARD_CELL_SIZE.x - 1;
// Reset tunnel state if we're not at a tunnel position
if !at_left_tunnel && !at_right_tunnel {
self.in_tunnel = false;
return false;
}
// If we're already in a tunnel, stay in tunnel state
if self.in_tunnel {
return true;
}
// Enter the tunnel and teleport to the other side
let new_x = if at_left_tunnel { BOARD_CELL_SIZE.x - 2 } else { 1 };
self.base.cell_position.x = new_x;
self.base.pixel_position = Map::cell_to_pixel(self.base.cell_position);
self.in_tunnel = true;
true
}
fn is_grid_aligned(&self) -> bool {
self.internal_position() == UVec2::ZERO
}
fn set_direction_if_valid(&mut self, new_direction: Direction) -> bool {
if new_direction == self.direction {
return false;
}
if self.is_wall_ahead(Some(new_direction)) {
return false;
}
self.direction = new_direction;
true
}
}
impl Entity for StaticEntity {
fn base(&self) -> &StaticEntity {
self
}
}
/// A trait for entities that can be rendered to the screen.
pub trait Renderable {
fn render(&mut self, canvas: &mut WindowCanvas) -> Result<()>;
}

View File

@@ -1,143 +1,93 @@
//! This module defines the Pac-Man entity, including its behavior and rendering.
use anyhow::Result;
use glam::{IVec2, UVec2};
use sdl2::render::WindowCanvas;
use std::cell::RefCell;
use std::rc::Rc;
use glam::Vec2;
use crate::{
entity::speed::SimpleTickModulator,
entity::{direction::Direction, Entity, MovableEntity, Moving, QueuedDirection, Renderable, StaticEntity},
map::Map,
texture::{animated::AnimatedTexture, directional::DirectionalAnimatedTexture, get_atlas_tile, sprite::SpriteAtlas},
};
use crate::constants::BOARD_PIXEL_OFFSET;
use crate::entity::direction::Direction;
use crate::entity::graph::{Graph, NodeId, Position, Traverser};
use crate::texture::animated::AnimatedTexture;
use crate::texture::directional::DirectionalAnimatedTexture;
use crate::texture::sprite::SpriteAtlas;
use sdl2::keyboard::Keycode;
use sdl2::rect::Rect;
use sdl2::render::{Canvas, RenderTarget};
use std::collections::HashMap;
/// The Pac-Man entity.
pub struct Pacman {
/// Shared movement and position fields.
pub base: MovableEntity,
/// The next direction of Pac-Man, which will be applied when Pac-Man is next aligned with the grid.
pub next_direction: Option<Direction>,
/// Whether Pac-Man is currently stopped.
pub stopped: bool,
pub skip_move_tick: bool,
pub texture: DirectionalAnimatedTexture,
pub death_animation: AnimatedTexture,
}
impl Entity for Pacman {
fn base(&self) -> &StaticEntity {
&self.base.base
}
}
impl Moving for Pacman {
fn tick_movement(&mut self) {
if self.skip_move_tick {
self.skip_move_tick = false;
return;
}
self.base.tick_movement();
}
fn update_cell_position(&mut self) {
self.base.update_cell_position();
}
fn next_cell(&self, direction: Option<Direction>) -> IVec2 {
self.base.next_cell(direction)
}
fn is_wall_ahead(&self, direction: Option<Direction>) -> bool {
self.base.is_wall_ahead(direction)
}
fn handle_tunnel(&mut self) -> bool {
self.base.handle_tunnel()
}
fn is_grid_aligned(&self) -> bool {
self.base.is_grid_aligned()
}
fn set_direction_if_valid(&mut self, new_direction: Direction) -> bool {
self.base.set_direction_if_valid(new_direction)
}
fn on_grid_aligned(&mut self) {
Pacman::update_cell_position(self);
if !<Pacman as Moving>::handle_tunnel(self) {
<Pacman as QueuedDirection>::handle_direction_change(self);
if !self.stopped && <Pacman as Moving>::is_wall_ahead(self, None) {
self.stopped = true;
} else if self.stopped && !<Pacman as Moving>::is_wall_ahead(self, None) {
self.stopped = false;
}
}
}
}
impl QueuedDirection for Pacman {
fn next_direction(&self) -> Option<Direction> {
self.next_direction
}
fn set_next_direction(&mut self, dir: Option<Direction>) {
self.next_direction = dir;
}
pub traverser: Traverser,
texture: DirectionalAnimatedTexture,
}
impl Pacman {
/// Creates a new `Pacman` instance.
pub fn new(starting_position: UVec2, atlas: Rc<RefCell<SpriteAtlas>>, map: Rc<RefCell<Map>>) -> Pacman {
let pixel_position = Map::cell_to_pixel(starting_position);
let get = |name: &str| get_atlas_tile(&atlas, name);
pub fn new(graph: &Graph, start_node: NodeId, atlas: &SpriteAtlas) -> Self {
let mut textures = HashMap::new();
let mut stopped_textures = HashMap::new();
Pacman {
base: MovableEntity::new(
pixel_position,
starting_position,
Direction::Right,
SimpleTickModulator::new(1f32),
map,
),
next_direction: None,
stopped: false,
skip_move_tick: false,
texture: DirectionalAnimatedTexture::new(
vec![get("pacman/up_a.png"), get("pacman/up_b.png"), get("pacman/full.png")],
vec![get("pacman/down_a.png"), get("pacman/down_b.png"), get("pacman/full.png")],
vec![get("pacman/left_a.png"), get("pacman/left_b.png"), get("pacman/full.png")],
vec![get("pacman/right_a.png"), get("pacman/right_b.png"), get("pacman/full.png")],
8,
),
death_animation: AnimatedTexture::new(
(0..=10)
.map(|i| get_atlas_tile(&atlas, &format!("pacman/death/{i}.png")))
.collect(),
5,
),
for &direction in &[Direction::Up, Direction::Down, Direction::Left, Direction::Right] {
let moving_prefix = match direction {
Direction::Up => "pacman/up",
Direction::Down => "pacman/down",
Direction::Left => "pacman/left",
Direction::Right => "pacman/right",
};
let moving_tiles = vec![
SpriteAtlas::get_tile(&atlas, &format!("{}_a.png", moving_prefix)).unwrap(),
SpriteAtlas::get_tile(&atlas, &format!("{}_b.png", moving_prefix)).unwrap(),
SpriteAtlas::get_tile(&atlas, "pacman/full.png").unwrap(),
];
let stopped_tiles = vec![SpriteAtlas::get_tile(&atlas, &format!("{}_b.png", moving_prefix)).unwrap()];
textures.insert(direction, AnimatedTexture::new(moving_tiles, 0.08));
stopped_textures.insert(direction, AnimatedTexture::new(stopped_tiles, 0.1));
}
Self {
traverser: Traverser::new(graph, start_node, Direction::Left),
texture: DirectionalAnimatedTexture::new(textures, stopped_textures),
}
}
/// Returns the internal position of Pac-Man, rounded down to the nearest even number.
fn internal_position_even(&self) -> UVec2 {
let pos = self.base.internal_position();
UVec2::new((pos.x / 2) * 2, (pos.y / 2) * 2)
pub fn tick(&mut self, dt: f32, graph: &Graph) {
self.traverser.advance(graph, dt * 60.0 * 1.125);
self.texture.tick(dt);
}
pub fn tick(&mut self) {
<Pacman as Moving>::tick(self);
self.texture.tick();
pub fn handle_key(&mut self, keycode: Keycode) {
let direction = match keycode {
Keycode::Up => Some(Direction::Up),
Keycode::Down => Some(Direction::Down),
Keycode::Left => Some(Direction::Left),
Keycode::Right => Some(Direction::Right),
_ => None,
};
if let Some(direction) = direction {
self.traverser.set_next_direction(direction);
}
}
}
impl Renderable for Pacman {
fn render(&mut self, canvas: &mut WindowCanvas) -> Result<()> {
let pos = self.base.base.pixel_position;
let dir = self.base.direction;
fn get_pixel_pos(&self, graph: &Graph) -> Vec2 {
match self.traverser.position {
Position::AtNode(node_id) => graph.get_node(node_id).unwrap().position,
Position::BetweenNodes { from, to, traversed } => {
let from_pos = graph.get_node(from).unwrap().position;
let to_pos = graph.get_node(to).unwrap().position;
let weight = from_pos.distance(to_pos);
from_pos.lerp(to_pos, traversed / weight)
}
}
}
// Center the 16x16 sprite on the 8x8 cell by offsetting by -4
let dest = sdl2::rect::Rect::new(pos.x - 4, pos.y - 4, 16, 16);
pub fn render<T: RenderTarget>(&self, canvas: &mut Canvas<T>, atlas: &mut SpriteAtlas, graph: &Graph) {
let pixel_pos = self.get_pixel_pos(graph).round().as_ivec2() + BOARD_PIXEL_OFFSET.as_ivec2();
let dest = Rect::new(pixel_pos.x - 8, pixel_pos.y - 8, 16, 16);
let is_stopped = self.traverser.position.is_stopped();
if self.stopped {
// When stopped, show the full sprite (mouth open)
self.texture.render_stopped(canvas, dest, dir)?;
if is_stopped {
self.texture
.render_stopped(canvas, atlas, dest, self.traverser.direction)
.unwrap();
} else {
self.texture.render(canvas, dest, dir)?;
self.texture.render(canvas, atlas, dest, self.traverser.direction).unwrap();
}
Ok(())
}
}

View File

@@ -1,56 +0,0 @@
//! This module provides a tick modulator, which can be used to slow down
//! operations by a percentage.
/// A tick modulator allows you to slow down operations by a percentage.
///
/// Unfortunately, switching to floating point numbers for entities can induce floating point errors, slow down calculations
/// and make the game less deterministic. This is why we use a speed modulator instead.
/// Additionally, with small integers, lowering the speed by a percentage is not possible. For example, if we have a speed of 2,
/// and we want to slow it down by 10%, we would need to slow it down by 0.2. However, since we are using integers, we can't.
/// The only amount you can slow it down by is 1, which is 50% of the speed.
///
/// The basic principle of the Speed Modulator is to instead 'skip' movement ticks every now and then.
/// At 60 ticks per second, skips could happen several times per second, or once every few seconds.
/// Whatever it be, as long as the tick rate is high enough, the human eye will not be able to tell the difference.
///
/// For example, if we want to slow down the speed by 10%, we would need to skip every 10th tick.
pub trait TickModulator {
/// Creates a new tick modulator.
///
/// # Arguments
///
/// * `percent` - The percentage to slow down by, from 0.0 to 1.0.
fn new(percent: f32) -> Self;
/// Returns whether or not the operation should be performed on this tick.
fn next(&mut self) -> bool;
fn set_speed(&mut self, speed: f32);
}
/// A simple tick modulator that skips every Nth tick.
pub struct SimpleTickModulator {
accumulator: f32,
pixels_per_tick: f32,
}
// TODO: Add tests for the tick modulator to ensure that it is working correctly.
// TODO: Look into average precision and binary code modulation strategies to see
// if they would be a better fit for this use case.
impl SimpleTickModulator {
pub fn new(pixels_per_tick: f32) -> Self {
Self {
accumulator: 0f32,
pixels_per_tick: pixels_per_tick * 0.47,
}
}
pub fn set_speed(&mut self, pixels_per_tick: f32) {
self.pixels_per_tick = pixels_per_tick;
}
pub fn next(&mut self) -> bool {
self.accumulator += self.pixels_per_tick;
if self.accumulator >= 1f32 {
self.accumulator -= 1f32;
true
} else {
false
}
}
}