Refactor Position delta

Now it's a bit easier to work with
This commit is contained in:
2025-02-22 15:38:43 +01:00
parent 15202df4f4
commit 7cc7fa3e70

View File

@@ -33,6 +33,13 @@ pub struct Position {
pub rank: Rank,
}
enum Dir {
Left,
Right,
Up,
Down,
}
impl Position {
pub fn new(file: File, rank: Rank) -> Position {
Position {
@@ -40,14 +47,19 @@ impl Position {
rank,
}
}
fn delta(
&self,
file_direction: &Direction,
rank_direction: &Direction,
) -> Option<Position> {
fn chain(&self, dirs: &[&Dir]) -> Option<Position> {
dirs.iter().try_fold(self.clone(), |pos, dir| pos.delta(dir))
}
fn delta(&self, direction: &Dir) -> Option<Position> {
let (file, rank) = match direction {
Dir::Left => (self.file.decr()?, self.rank),
Dir::Right => (self.file.incr()?, self.rank),
Dir::Up => (self.file, self.rank.incr()?),
Dir::Down => (self.file, self.rank.decr()?),
};
Some(Position {
rank: self.rank.delta(rank_direction)?,
file: self.file.delta(file_direction)?,
file,
rank,
})
}
}
@@ -76,12 +88,6 @@ pub enum File {
H,
}
enum Direction {
Incr,
Decr,
Stay,
}
pub trait GridAxis
where
Self: Sized,
@@ -89,13 +95,6 @@ where
{
fn incr(&self) -> Option<Self>;
fn decr(&self) -> Option<Self>;
fn delta(&self, direction: &Direction) -> Option<Self> {
match direction {
Direction::Incr => self.incr(),
Direction::Decr => self.decr(),
Direction::Stay => Some(self.clone()),
}
}
}
impl GridAxis for Rank {
@@ -170,10 +169,10 @@ impl PieceType {
}
fn pawn_move_rays(position: &Position, color: &Color) -> Vec<Ray> {
let direction = match color {
Color::Black => Direction::Decr,
Color::White => Direction::Incr,
Color::Black => Dir::Down,
Color::White => Dir::Up,
};
let go = |p: &Position| p.delta(&Direction::Stay, &direction);
let go = |p: &Position| p.delta(&direction);
if position.rank == color.get_pawn_rank() {
let one = go(position).unwrap();
let two = go(&one).unwrap();
@@ -190,19 +189,18 @@ impl PieceType {
}
}
}
fn pawn_capture_rays(position: &Position, color: &Color) -> Vec<Ray> {
let direction = match color {
Color::Black => Direction::Decr,
Color::White => Direction::Incr,
Color::Black => Dir::Down,
Color::White => Dir::Up,
};
let mut capture_rays = vec![];
if let Some(p) = position.delta(&Direction::Incr, &direction) {
if let Some(p) = position.chain(&[&direction, &Dir::Left]) {
capture_rays.push(Ray {
positions: vec![p],
});
}
if let Some(p) = position.delta(&Direction::Decr, &direction) {
if let Some(p) = position.chain(&[&direction, &Dir::Right]) {
capture_rays.push(Ray {
positions: vec![p],
});