From 08f010ed32c2f2d25802bf11d836d5ea08252068 Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Mon, 1 Apr 2024 22:59:06 +0100 Subject: [PATCH] Add total plie count validation --- src/board/chess_board/error.rs | 3 +++ src/board/chess_board/mod.rs | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/src/board/chess_board/error.rs b/src/board/chess_board/error.rs index 4265de0..7b570a4 100644 --- a/src/board/chess_board/error.rs +++ b/src/board/chess_board/error.rs @@ -23,6 +23,8 @@ pub enum InvalidError { ErroneousCombinedOccupancy, /// Half-move clock is higher than total number of plies. HalfMoveClockTooHigh, + /// The total plie count does not match the current player. + IncoherentPlieCount, } impl std::fmt::Display for InvalidError { @@ -45,6 +47,7 @@ impl std::fmt::Display for InvalidError { "The pre-computed combined occupancy boards does not match the other boards." } Self::HalfMoveClockTooHigh => "Half-move clock is higher than total number of plies.", + Self::IncoherentPlieCount => "The total plie count does not match the current player.", }; write!(f, "{}", error_msg) } diff --git a/src/board/chess_board/mod.rs b/src/board/chess_board/mod.rs index 879aba6..d28d69c 100644 --- a/src/board/chess_board/mod.rs +++ b/src/board/chess_board/mod.rs @@ -208,6 +208,11 @@ impl ChessBoard { /// Validate the state of the board. Return Err([InvalidError]) if an issue is found. pub fn validate(&self) -> Result<(), InvalidError> { + // The current plie count should be odd on white's turn, and vice-versa. + if self.total_plies() % 2 != self.current_player().index() as u32 { + return Err(InvalidError::IncoherentPlieCount); + } + // Make sure the clocks are in agreement. if u32::from(self.half_move_clock()) > self.total_plies() { return Err(InvalidError::HalfMoveClockTooHigh); @@ -428,6 +433,22 @@ mod test { assert!(default_position.is_valid()); } + #[test] + fn invalid_incoherent_plie_count() { + let position = { + let mut builder = ChessBoardBuilder::new(); + builder[Square::E1] = Some((Piece::King, Color::White)); + builder[Square::E8] = Some((Piece::King, Color::Black)); + let mut board = TryInto::::try_into(builder).unwrap(); + board.total_plies = 1; + board + }; + assert_eq!( + position.validate().err().unwrap(), + InvalidError::IncoherentPlieCount, + ); + } + #[test] fn invalid_half_moves_clock() { let res = {