move some methods to BoardConsts

This commit is contained in:
mehbark 2025-07-07 11:46:10 -04:00
parent 9919ac8ab5
commit 767f3bc3b6

View file

@ -2,7 +2,6 @@ use std::{
error::Error,
fmt::{self, Display},
io::{self, prelude::*},
str::FromStr,
};
use bitvec::vec::BitVec;
@ -16,6 +15,41 @@ struct BoardConsts {
goals: BitVec,
}
#[allow(
clippy::cast_possible_truncation,
clippy::cast_possible_wrap,
clippy::cast_sign_loss
)]
impl BoardConsts {
pub fn height(&self) -> i16 {
self.walls.len() as i16 / self.width
}
fn index_of(&self, (x, y): Pos) -> usize {
(x + y * self.width) as usize
}
pub fn in_bounds(&self, (x, y): Pos) -> bool {
(0..self.width).contains(&x) && (0..self.height()).contains(&y)
}
pub fn wall_at(&self, pos: Pos) -> bool {
if !self.in_bounds(pos) {
return true;
}
*self.walls.get(self.index_of(pos)).unwrap()
}
pub fn goal_at(&self, pos: Pos) -> bool {
if !self.in_bounds(pos) {
return false;
}
*self.goals.get(self.index_of(pos)).unwrap()
}
}
#[derive(Debug)]
struct Board {
pub player: Pos,
@ -47,40 +81,12 @@ impl Error for BoardParseError {}
clippy::cast_sign_loss
)]
impl Board {
pub fn height(&self, consts: &BoardConsts) -> i16 {
self.boxes.len() as i16 / consts.width
}
pub fn in_bounds(&self, consts: &BoardConsts, (x, y): Pos) -> bool {
(0..consts.width).contains(&x) && (0..self.height(consts)).contains(&y)
}
fn index_of(&self, consts: &BoardConsts, (x, y): Pos) -> usize {
(x + y * consts.width) as usize
}
pub fn wall_at(&self, consts: &BoardConsts, pos: Pos) -> bool {
if !self.in_bounds(consts, pos) {
return true;
}
*consts.walls.get(self.index_of(consts, pos)).unwrap()
}
pub fn goal_at(&self, consts: &BoardConsts, pos: Pos) -> bool {
if !self.in_bounds(consts, pos) {
return false;
}
*consts.goals.get(self.index_of(consts, pos)).unwrap()
}
pub fn box_at(&self, consts: &BoardConsts, pos: Pos) -> bool {
if !self.in_bounds(consts, pos) {
if !consts.in_bounds(pos) {
return false;
}
*self.boxes.get(self.index_of(consts, pos)).unwrap()
*self.boxes.get(consts.index_of(pos)).unwrap()
}
pub fn parse(src: &str) -> Result<(BoardConsts, Board), BoardParseError> {
@ -129,10 +135,10 @@ impl Board {
}
fn write(&self, consts: &BoardConsts, f: &mut impl Write) -> Result<(), Box<dyn Error>> {
for y in 0..self.height(consts) {
for y in 0..consts.height() {
for x in 0..consts.width {
if self.player == (x, y) {
if self.goal_at(consts, (x, y)) {
if consts.goal_at((x, y)) {
write!(f, "+")?;
} else {
write!(f, "@")?;
@ -143,8 +149,8 @@ impl Board {
f,
"{}",
match (
self.wall_at(consts, (x, y)),
self.goal_at(consts, (x, y)),
consts.wall_at((x, y)),
consts.goal_at((x, y)),
self.box_at(consts, (x, y))
) {
(true, false, false) => '#',