Add total plie count validation

This commit is contained in:
Bruno BELANYI 2024-04-01 22:59:06 +01:00
parent f4764f2174
commit 08f010ed32
2 changed files with 24 additions and 0 deletions

View file

@ -23,6 +23,8 @@ pub enum InvalidError {
ErroneousCombinedOccupancy, ErroneousCombinedOccupancy,
/// Half-move clock is higher than total number of plies. /// Half-move clock is higher than total number of plies.
HalfMoveClockTooHigh, HalfMoveClockTooHigh,
/// The total plie count does not match the current player.
IncoherentPlieCount,
} }
impl std::fmt::Display for InvalidError { 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." "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::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) write!(f, "{}", error_msg)
} }

View file

@ -208,6 +208,11 @@ impl ChessBoard {
/// Validate the state of the board. Return Err([InvalidError]) if an issue is found. /// Validate the state of the board. Return Err([InvalidError]) if an issue is found.
pub fn validate(&self) -> Result<(), InvalidError> { 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. // Make sure the clocks are in agreement.
if u32::from(self.half_move_clock()) > self.total_plies() { if u32::from(self.half_move_clock()) > self.total_plies() {
return Err(InvalidError::HalfMoveClockTooHigh); return Err(InvalidError::HalfMoveClockTooHigh);
@ -428,6 +433,22 @@ mod test {
assert!(default_position.is_valid()); 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::<ChessBoard>::try_into(builder).unwrap();
board.total_plies = 1;
board
};
assert_eq!(
position.validate().err().unwrap(),
InvalidError::IncoherentPlieCount,
);
}
#[test] #[test]
fn invalid_half_moves_clock() { fn invalid_half_moves_clock() {
let res = { let res = {