Refactor make_move, internal functions, move parsing and add more tests

This commit is contained in:
stefiosif
2024-09-14 20:55:00 +03:00
parent b26357a205
commit 49b413d24f
5 changed files with 490 additions and 301 deletions

View File

@@ -58,6 +58,7 @@ impl fmt::Display for Response {
}
}
#[derive(Debug)]
struct UciParameters {
movetime: Option<usize>,
depth: Option<u8>,
@@ -109,19 +110,23 @@ pub fn uci_position(position: &mut SplitWhitespace) -> Result<Game, String> {
}
for mv_str in position {
let mv = Move::parse_from_str(mv_str)?;
let mv = Move::parse_from_str(&game.board, mv_str)?;
game.board.make_move(&mv);
}
Ok(game)
}
const MAX_DEPTH: u8 = 5;
const MAX_DEPTH: u8 = 3;
pub fn uci_go(go: &mut SplitWhitespace, game: &mut Game) -> Result<Move, String> {
let mut params = UciParameters::new();
while let Some(subcommand) = go.next() {
match subcommand {
// TODO: Add new commands
"wtime" => (),
"btime" => (),
"movestogo" => (),
"depth" => {
let depth_str = go.next().ok_or("Expected depth value")?;
let depth = depth_str.parse::<u8>().map_err(|_| "Invalid depth value")?;
@@ -161,6 +166,7 @@ pub fn uci_loop<R: BufRead, W: Write>(input: R, mut output: W) -> Result<(), Str
Command::UciNewGame => Response::Info("Clear cache".to_string()),
Command::Position => {
params.add_game(uci_position(&mut parts)?);
// dbg!(&params);
Response::Info("Initialized position".to_string())
}
Command::Go => {
@@ -237,7 +243,7 @@ mod tests {
#[test]
fn test_uci_loop() -> Result<(), String> {
init_attacks();
let commands = b"uci\n\
let commands = "uci\n\
ucinewgame\n\
position fen 8/8/8/8/8/4q1k1/8/5K2 b - - 0 1\n\
go\n\
@@ -259,4 +265,30 @@ mod tests {
Ok(())
}
#[test]
fn test_cute_chess_bug() -> Result<(), String> {
init_attacks();
let commands = "uci\n\
ucinewgame\n\
position startpos moves b1c3 g7g6 d2d4 f8g7 e2e4 f7f5 e4f5 e7e6 f5g6 h7g6 g1f3 b8c6 f1c4 d7d6 c1e3 e6e5 d4d5 c6e7 c3b5 c7c6 d5c6 b7c6 b5d6 d8d6 d1d6 c8d7 f3e5 d7e6 d6e6 g8f6 e5g6 f6g8 e6f7 e8d7 f7g7 g8f6 g7e7 d7c8 g6h8 c8b8 e7d8 b8b7 d8f6 b7c7 e3a7 a8a7 h8g6 c7b6 g6e5 a7c7 f6c6 b6a7
go\n\
quit";
let input = Cursor::new(commands);
let mut output: Vec<_> = vec![];
uci_loop(input, &mut output)?;
let expected_response = "id name ippos\n\
id author stefiosif\n\
uciok\n\
Clear cache\n\
Initialized position\n\
bestmove c6c7\n";
let actual_response = String::from_utf8(output).expect("Invalid UTF-8 in output");
assert_eq!(expected_response, actual_response);
Ok(())
}
}