refactor: resolve clippy warnings, resolve shared reference with once_cell

This commit is contained in:
2025-07-23 17:38:24 -05:00
parent 4365639a1d
commit 06841fd0d7
9 changed files with 44 additions and 71 deletions

5
Cargo.lock generated
View File

@@ -150,9 +150,9 @@ dependencies = [
[[package]] [[package]]
name = "once_cell" name = "once_cell"
version = "1.18.0" version = "1.21.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d" checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
[[package]] [[package]]
name = "overload" name = "overload"
@@ -166,6 +166,7 @@ version = "0.1.0"
dependencies = [ dependencies = [
"lazy_static", "lazy_static",
"libc", "libc",
"once_cell",
"pathfinding", "pathfinding",
"rand", "rand",
"sdl2", "sdl2",

View File

@@ -14,6 +14,7 @@ sdl2 = { version = "0.38.0", features = ["image", "ttf"] }
spin_sleep = "1.3.2" spin_sleep = "1.3.2"
rand = "0.9.2" rand = "0.9.2"
pathfinding = "4.14" pathfinding = "4.14"
once_cell = "1.21.3"
[target.'cfg(target_os = "windows")'.dependencies.winapi] [target.'cfg(target_os = "windows")'.dependencies.winapi]
version = "0.3" version = "0.3"

View File

@@ -34,7 +34,7 @@ impl Audio {
// set channel volume // set channel volume
for i in 0..channels { for i in 0..channels {
mixer::Channel(i as i32).set_volume(32); mixer::Channel(i).set_volume(32);
} }
let mixer_context = mixer::init(InitFlag::OGG).expect("Failed to initialize SDL2_mixer"); let mixer_context = mixer::init(InitFlag::OGG).expect("Failed to initialize SDL2_mixer");
@@ -44,11 +44,8 @@ impl Audio {
.enumerate() .enumerate()
.map(|(i, data)| { .map(|(i, data)| {
let rwops = RWops::from_bytes(data) let rwops = RWops::from_bytes(data)
.expect(&format!("Failed to create RWops for sound {}", i + 1)); .unwrap_or_else(|_| panic!("Failed to create RWops for sound {}", i + 1));
rwops.load_wav().expect(&format!( rwops.load_wav().unwrap_or_else(|_| panic!("Failed to load sound {} from embedded data", i + 1))
"Failed to load sound {} from embedded data",
i + 1
))
}) })
.collect(); .collect();

View File

@@ -17,16 +17,11 @@ pub enum DebugMode {
pub struct DebugRenderer; pub struct DebugRenderer;
impl DebugRenderer { impl DebugRenderer {
pub fn draw_cell(canvas: &mut Canvas<Window>, map: &Map, cell: (u32, u32), color: Color) { pub fn draw_cell(canvas: &mut Canvas<Window>, _map: &Map, cell: (u32, u32), color: Color) {
let position = Map::cell_to_pixel(cell); let position = Map::cell_to_pixel(cell);
canvas.set_draw_color(color); canvas.set_draw_color(color);
canvas canvas
.draw_rect(sdl2::rect::Rect::new( .draw_rect(sdl2::rect::Rect::new(position.0, position.1, 24, 24))
position.0 as i32,
position.1 as i32,
24,
24,
))
.expect("Could not draw rectangle"); .expect("Could not draw rectangle");
} }

View File

@@ -55,7 +55,7 @@ pub fn reconstruct_edibles<'a>(
map: Rc<RefCell<Map>>, map: Rc<RefCell<Map>>,
pellet_sprite: Rc<AtlasTexture<'a>>, pellet_sprite: Rc<AtlasTexture<'a>>,
power_pellet_sprite: Rc<AtlasTexture<'a>>, power_pellet_sprite: Rc<AtlasTexture<'a>>,
fruit_sprite: Rc<AtlasTexture<'a>>, _fruit_sprite: Rc<AtlasTexture<'a>>,
) -> Vec<Edible<'a>> { ) -> Vec<Edible<'a>> {
let mut edibles = Vec::new(); let mut edibles = Vec::new();
for x in 0..BOARD_WIDTH { for x in 0..BOARD_WIDTH {

View File

@@ -180,7 +180,6 @@ impl<'a> Game<'a> {
// Reset game // Reset game
if keycode == Keycode::R { if keycode == Keycode::R {
self.reset(); self.reset();
return;
} }
} }
@@ -343,7 +342,7 @@ impl<'a> Game<'a> {
// Render the score and high score // Render the score and high score
self.render_text( self.render_text(
&format!("{}UP HIGH SCORE ", lives), &format!("{lives}UP HIGH SCORE "),
(24 * lives_offset + x_offset, y_offset), (24 * lives_offset + x_offset, y_offset),
Color::WHITE, Color::WHITE,
); );

View File

@@ -13,16 +13,11 @@
pub fn is_adjacent(a: (u32, u32), b: (u32, u32), diagonal: bool) -> bool { pub fn is_adjacent(a: (u32, u32), b: (u32, u32), diagonal: bool) -> bool {
let (ax, ay) = a; let (ax, ay) = a;
let (bx, by) = b; let (bx, by) = b;
let dx = ax.abs_diff(bx);
// Calculate absolute differences between coordinates let dy = ay.abs_diff(by);
let dx = if ax > bx { ax - bx } else { bx - ax };
let dy = if ay > by { ay - by } else { by - ay };
if diagonal { if diagonal {
// For diagonal adjacency: both differences must be ≤ 1 and at least one > 0 dx <= 1 && dy <= 1 && (dx != 0 || dy != 0)
dx <= 1 && dy <= 1 && (dx + dy) > 0
} else { } else {
// For orthogonal adjacency: exactly one difference must be 1, the other 0
(dx == 1 && dy == 0) || (dx == 0 && dy == 1) (dx == 1 && dy == 0) || (dx == 0 && dy == 1)
} }
} }

View File

@@ -11,7 +11,7 @@ use tracing_subscriber::layer::SubscriberExt;
#[cfg(windows)] #[cfg(windows)]
use winapi::{ use winapi::{
shared::{ntdef::NULL, windef::HWND}, shared::ntdef::NULL,
um::{ um::{
fileapi::{CreateFileA, OPEN_EXISTING}, fileapi::{CreateFileA, OPEN_EXISTING},
handleapi::INVALID_HANDLE_VALUE, handleapi::INVALID_HANDLE_VALUE,
@@ -29,13 +29,13 @@ use winapi::{
/// terminal, this function does nothing. /// terminal, this function does nothing.
#[cfg(windows)] #[cfg(windows)]
unsafe fn attach_console() { unsafe fn attach_console() {
if GetConsoleWindow() != std::ptr::null_mut() as HWND { if !std::ptr::eq(GetConsoleWindow(), std::ptr::null_mut()) {
return; return;
} }
if AttachConsole(winapi::um::wincon::ATTACH_PARENT_PROCESS) != 0 { if AttachConsole(winapi::um::wincon::ATTACH_PARENT_PROCESS) != 0 {
let handle = CreateFileA( let handle = CreateFileA(
"CONOUT$\0".as_ptr() as *const i8, c"CONOUT$".as_ptr(),
GENERIC_READ | GENERIC_WRITE, GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
std::ptr::null_mut(), std::ptr::null_mut(),

View File

@@ -3,6 +3,7 @@ use rand::seq::IteratorRandom;
use crate::constants::{MapTile, BOARD_OFFSET, CELL_SIZE}; use crate::constants::{MapTile, BOARD_OFFSET, CELL_SIZE};
use crate::constants::{BOARD_HEIGHT, BOARD_WIDTH}; use crate::constants::{BOARD_HEIGHT, BOARD_WIDTH};
use once_cell::sync::OnceCell;
use std::collections::{HashSet, VecDeque}; use std::collections::{HashSet, VecDeque};
use std::ops::Add; use std::ops::Add;
@@ -66,20 +67,8 @@ impl Map {
pub fn new(raw_board: [&str; BOARD_HEIGHT as usize]) -> Map { pub fn new(raw_board: [&str; BOARD_HEIGHT as usize]) -> Map {
let mut map = [[MapTile::Empty; BOARD_HEIGHT as usize]; BOARD_WIDTH as usize]; let mut map = [[MapTile::Empty; BOARD_HEIGHT as usize]; BOARD_WIDTH as usize];
for y in 0..BOARD_HEIGHT as usize { for (y, line) in raw_board.iter().enumerate().take(BOARD_HEIGHT as usize) {
let line = raw_board[y]; for (x, character) in line.chars().enumerate().take(BOARD_WIDTH as usize) {
for x in 0..BOARD_WIDTH as usize {
if x >= line.len() {
break;
}
let i = (y * (BOARD_WIDTH as usize) + x) as usize;
let character = line
.chars()
.nth(x as usize)
.unwrap_or_else(|| panic!("Could not get character at {} = ({}, {})", i, x, y));
let tile = match character { let tile = match character {
'#' => MapTile::Wall, '#' => MapTile::Wall,
'.' => MapTile::Pellet, '.' => MapTile::Pellet,
@@ -90,25 +79,29 @@ impl Map {
MapTile::StartingPosition(c.to_digit(10).unwrap() as u8) MapTile::StartingPosition(c.to_digit(10).unwrap() as u8)
} }
'=' => MapTile::Empty, '=' => MapTile::Empty,
_ => panic!("Unknown character in board: {}", character), _ => panic!("Unknown character in board: {character}"),
}; };
map[x][y] = tile;
map[x as usize][y as usize] = tile;
} }
} }
Map { Map {
current: map, current: map,
default: map.clone(), default: map,
} }
} }
/// Resets the map to its original state. /// Resets the map to its original state.
pub fn reset(&mut self) { pub fn reset(&mut self) {
// Restore the map to its original state // Restore the map to its original state
for x in 0..BOARD_WIDTH as usize { for (x, col) in self
for y in 0..BOARD_HEIGHT as usize { .current
self.current[x][y] = self.default[x][y]; .iter_mut()
.enumerate()
.take(BOARD_WIDTH as usize)
{
for (y, cell) in col.iter_mut().enumerate().take(BOARD_HEIGHT as usize) {
*cell = self.default[x][y];
} }
} }
} }
@@ -163,19 +156,19 @@ impl Map {
/// This is computed once using a flood fill from a random pellet, and then cached. /// This is computed once using a flood fill from a random pellet, and then cached.
pub fn get_valid_playable_positions(&mut self) -> &Vec<Position> { pub fn get_valid_playable_positions(&mut self) -> &Vec<Position> {
use MapTile::*; use MapTile::*;
static mut CACHE: Option<Vec<Position>> = None; static CACHE: OnceCell<Vec<Position>> = OnceCell::new();
// SAFETY: This is only mutated once, and only in this function. if let Some(cached) = CACHE.get() {
unsafe { return cached;
if let Some(ref cached) = CACHE {
return cached;
}
} }
// Find a random starting pellet // Find a random starting pellet
let mut pellet_positions = vec![]; let mut pellet_positions = vec![];
for x in 0..BOARD_WIDTH as u32 { for (x, col) in self.current.iter().enumerate().take(BOARD_WIDTH as usize) {
for y in 0..BOARD_HEIGHT as u32 { for (y, &cell) in col.iter().enumerate().take(BOARD_HEIGHT as usize) {
match self.current[x as usize][y as usize] { match cell {
Pellet | PowerPellet => pellet_positions.push(Position { x, y }), Pellet | PowerPellet => pellet_positions.push(Position {
x: x as u32,
y: y as u32,
}),
_ => {} _ => {}
} }
} }
@@ -191,15 +184,12 @@ impl Map {
queue.push_back(start); queue.push_back(start);
while let Some(pos) = queue.pop_front() { while let Some(pos) = queue.pop_front() {
// Mark visited, skip if already visited
if !visited.insert(pos) { if !visited.insert(pos) {
continue; continue;
} }
// Check if the current tile is valid
match self.current[pos.x as usize][pos.y as usize] { match self.current[pos.x as usize][pos.y as usize] {
Empty | Pellet | PowerPellet => { Empty | Pellet | PowerPellet => {
// Valid, continue flood
for offset in [ for offset in [
SignedPosition { x: -1, y: 0 }, SignedPosition { x: -1, y: 0 },
SignedPosition { x: 1, y: 0 }, SignedPosition { x: 1, y: 0 },
@@ -207,7 +197,7 @@ impl Map {
SignedPosition { x: 0, y: 1 }, SignedPosition { x: 0, y: 1 },
] { ] {
let neighbor = pos + offset; let neighbor = pos + offset;
if neighbor.x < BOARD_WIDTH as u32 && neighbor.y < BOARD_HEIGHT as u32 { if neighbor.x < BOARD_WIDTH && neighbor.y < BOARD_HEIGHT {
let neighbor_tile = let neighbor_tile =
self.current[neighbor.x as usize][neighbor.y as usize]; self.current[neighbor.x as usize][neighbor.y as usize];
if matches!(neighbor_tile, Empty | Pellet | PowerPellet) { if matches!(neighbor_tile, Empty | Pellet | PowerPellet) {
@@ -216,16 +206,11 @@ impl Map {
} }
} }
} }
StartingPosition(_) | Wall | Tunnel => { StartingPosition(_) | Wall | Tunnel => {}
// Not valid, do not continue
}
} }
} }
let mut result: Vec<Position> = visited.into_iter().collect(); let mut result: Vec<Position> = visited.into_iter().collect();
result.sort_unstable(); result.sort_unstable();
unsafe { CACHE.get_or_init(|| result)
CACHE = Some(result);
CACHE.as_ref().unwrap()
}
} }
} }