From 0bc7e8d542d2bf00fd7265a4545c987163fa3470 Mon Sep 17 00:00:00 2001 From: Eryn Wells Date: Wed, 10 Jan 2024 13:37:18 -0800 Subject: [PATCH] [board] Implement some castling checks on Move Define some constants in Square that refer to the starting positions of the two kings, and the target castling squares. Then implement the following methods that use those constants to determine if a move is a castle. - Move::is_kingside_castle() - Move::is_queenside_castle() - Move::is_castle() These checks only apply to King moves, and if the king is moving from and to specific squares. --- board/src/moves/move.rs | 30 ++++++++++++++++++++++++++++-- board/src/square.rs | 4 ++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/board/src/moves/move.rs b/board/src/moves/move.rs index 53f6ecc..ece8f18 100644 --- a/board/src/moves/move.rs +++ b/board/src/moves/move.rs @@ -1,7 +1,10 @@ // Eryn Wells -use crate::piece::{Piece, PlacedPiece, Shape}; -use crate::Square; +use crate::{ + piece::{Piece, PlacedPiece, Shape}, + position::BoardSide, + Square, +}; #[derive(Debug, Clone, Eq, Hash, PartialEq)] pub struct Move { @@ -32,4 +35,27 @@ impl Move { self.promoting_to = Some(shape); self } + + pub fn is_castle(&self) -> bool { + let color = self.piece.color(); + self.piece.shape() == Shape::King + && self.from == Square::KING_STARTING_SQUARES[color as usize] + && Square::KING_CASTLE_TARGET_SQUARES[color as usize].contains(&self.to) + } + + pub fn is_kingside_castle(&self) -> bool { + let color = self.piece.color(); + self.piece.shape() == Shape::King + && self.from == Square::KING_STARTING_SQUARES[color as usize] + && self.to + == Square::KING_CASTLE_TARGET_SQUARES[color as usize][BoardSide::King as usize] + } + + pub fn is_queenside_castle(&self) -> bool { + let color = self.piece.color(); + self.piece.shape() == Shape::King + && self.from == Square::KING_STARTING_SQUARES[color as usize] + && self.to + == Square::KING_CASTLE_TARGET_SQUARES[color as usize][BoardSide::Queen as usize] + } } diff --git a/board/src/square.rs b/board/src/square.rs index 7a0d6d8..d380b29 100644 --- a/board/src/square.rs +++ b/board/src/square.rs @@ -155,6 +155,10 @@ impl Square { } impl Square { + pub(crate) const KING_STARTING_SQUARES: [Square; 2] = [Square::E1, Square::E8]; + pub(crate) const KING_CASTLE_TARGET_SQUARES: [[Square; 2]; 2] = + [[Square::C1, Square::G1], [Square::C8, Square::G8]]; + pub fn from_algebraic_str(s: &str) -> Result { s.parse() }