Move castling move generation logic to movegen.rs and refactor related repeated code

This commit is contained in:
2024-06-14 21:46:37 +03:00
parent a0959bf6b9
commit 07af7294fa
4 changed files with 100 additions and 140 deletions

View File

@@ -1,5 +1,5 @@
use crate::board::{Board, Color, Kind, Piece};
use crate::game::{Game, State};
use crate::game::{Castle, Game, State};
use String as FenError;
pub fn from_fen(fen: &str) -> Result<Game, FenError> {
@@ -78,17 +78,15 @@ fn side_to_move(side: &str) -> Result<Color, FenError> {
}
}
/// Return castling ability as a bitflag. LSb K, 2nd LSb Q, 3rd LSb k, 4th LSb q. Ignore 4 MSb's
fn castling_ability(castling: &str) -> Result<u8, FenError> {
let mut rights = 0b0;
fn castling_ability(castling: &str) -> Result<[Castle; 2], FenError> {
let mut bitflag = 0b0;
for c in castling.chars() {
match c {
'K' => rights |= 0b1,
'Q' => rights |= 0b10,
'k' => rights |= 0b100,
'q' => rights |= 0b1000,
'-' => rights |= 0b0,
'K' => bitflag |= 0b1000,
'Q' => bitflag |= 0b100,
'k' => bitflag |= 0b10,
'q' => bitflag |= 0b1,
'-' => break,
_ => {
return Err(FenError::from(
"Found invalid character while parsing in castling_ability",
@@ -96,7 +94,30 @@ fn castling_ability(castling: &str) -> Result<u8, FenError> {
}
};
}
Ok(rights)
let mut castling_ability: [Castle; 2] = [Castle::None, Castle::None];
let white_king_and_queen = bitflag & 0b11 == 0b11;
let white_king = (bitflag >> 1) & 1 == 1;
let white_queen = bitflag & 1 == 1;
castling_ability[0] = match (white_king_and_queen, white_king, white_queen) {
(true, _, _) => Castle::Both,
(_, true, _) => Castle::Short,
(_, _, true) => Castle::Long,
_ => Castle::None,
};
let black_king_and_queen = (bitflag >> 2) & 0b11 == 0b11;
let black_king = (bitflag >> 3) & 1 == 1;
let black_queen = (bitflag >> 2) & 1 == 1;
castling_ability[1] = match (black_king_and_queen, black_king, black_queen) {
(true, _, _) => Castle::Both,
(_, true, _) => Castle::Short,
(_, _, true) => Castle::Long,
_ => Castle::None,
};
Ok(castling_ability)
}
use std::collections::HashMap;