From 7cc7fa3e7001b77c76067324c45e093eb0bc6217 Mon Sep 17 00:00:00 2001 From: Pavel Lutskov Date: Sat, 22 Feb 2025 15:38:43 +0100 Subject: [PATCH] Refactor Position delta Now it's a bit easier to work with --- rs/src/board.rs | 54 ++++++++++++++++++++++++------------------------- 1 file changed, 26 insertions(+), 28 deletions(-) diff --git a/rs/src/board.rs b/rs/src/board.rs index 2cd0165..81bfc88 100644 --- a/rs/src/board.rs +++ b/rs/src/board.rs @@ -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 { + fn chain(&self, dirs: &[&Dir]) -> Option { + dirs.iter().try_fold(self.clone(), |pos, dir| pos.delta(dir)) + } + fn delta(&self, direction: &Dir) -> Option { + 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; fn decr(&self) -> Option; - fn delta(&self, direction: &Direction) -> Option { - 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 { 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 { 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], });