Refactor based on clippy, move tt to search module and call iterative deepening from uci_go

This commit is contained in:
stefiosif
2024-11-03 01:19:12 +02:00
parent 802bdcdb37
commit 1b28de5064
11 changed files with 67 additions and 92 deletions

View File

@@ -1,40 +1,30 @@
use crate::{
board::{game::Game, transposition_table::TranspositionTable},
board::game::Game,
evaluation::{MAX_SCORE, MIN_SCORE},
movegen::r#move::Move,
};
use super::negamax;
use super::{negamax, transposition_table::TranspositionTable, MAX_TT_SIZE};
pub fn iterative_deepening(
game: &mut Game,
max_depth: u8,
move_time: u128,
mut tt: TranspositionTable,
) -> Result<Move, String> {
let mut nodes = 0;
let (mut mv, _): (Option<Move>, i32) = (None, 0);
pub fn iterative_deepening(game: &mut Game, max_depth: u8, move_time: u128) -> Option<Move> {
let mut tt = TranspositionTable::new(MAX_TT_SIZE);
let mut mv: Option<Move> = None;
let time_now = std::time::Instant::now();
for depth in 0..max_depth {
if move_time < time_now.elapsed().as_millis() {
return Ok(mv.expect("No move selected"));
for depth in 1..=max_depth {
if time_now.elapsed().as_millis() >= move_time {
return mv;
}
(mv, _) = negamax::negamax(game, MIN_SCORE, MAX_SCORE, depth, 0, &mut tt, &mut nodes);
dbg!(depth, nodes);
(mv, _) = negamax::negamax(game, MIN_SCORE, MAX_SCORE, depth, 0, &mut tt);
}
Ok(mv.expect("No move selected"))
mv
}
#[cfg(test)]
mod tests {
use crate::{
board::{fen::from_fen, transposition_table::TranspositionTable},
movegen::attack_generator::init_attacks,
search,
};
use crate::{board::fen::from_fen, movegen::attack_generator::init_attacks, search};
const FEN: &str = "1r2k2r/2P1pq1p/2npb3/1p3ppP/p3P3/P2B1Q2/1P1PNPP1/R3K2R w KQk g6 0 1";
@@ -42,10 +32,9 @@ mod tests {
fn test_iterative_deepening() -> Result<(), String> {
init_attacks();
let mut game = from_fen(FEN)?;
let tt = TranspositionTable::new(1000000);
let time_now = std::time::Instant::now();
let _ = search::iterative_deepening::iterative_deepening(&mut game, 6, 100000, tt);
let _ = search::iterative_deepening::iterative_deepening(&mut game, 6, 1000);
dbg!(time_now.elapsed());
Ok(())

View File

@@ -3,3 +3,9 @@ pub mod move_ordering;
pub mod negamax;
pub mod perft;
pub mod quiescence;
pub mod transposition_table;
pub const MAX_DEPTH: u8 = 4;
pub const QUIESCENCE_DEPTH: u8 = 3;
pub const MOVE_TIME: u128 = 1000;
pub const MAX_TT_SIZE: u64 = 1000000;

View File

@@ -1,15 +1,10 @@
use crate::{
board::{
game::Game,
transposition_table::{Bound, TTEntry, TranspositionTable},
},
board::game::Game,
evaluation::{MATE_SCORE, MIN_SCORE},
movegen::r#move::Move,
};
use super::{move_ordering::score_by_mvv_lva, quiescence::quiescence};
const QUIESCENCE_DEPTH: u8 = 3;
use super::{move_ordering::score_by_mvv_lva, quiescence::quiescence, transposition_table::{Bound, TTEntry, TranspositionTable}, QUIESCENCE_DEPTH};
pub fn negamax(
game: &mut Game,
@@ -18,15 +13,14 @@ pub fn negamax(
depth: u8,
plies: u8,
tt: &mut TranspositionTable,
nodes: &mut u64,
) -> (Option<Move>, i32) {
*nodes += 1;
if depth == 0 {
let q = quiescence(game, alpha, beta, nodes, QUIESCENCE_DEPTH).1;
let q = quiescence(game, alpha, beta, QUIESCENCE_DEPTH).1;
return (None, q);
}
let mut tt_move = None;
if let Some(entry) = tt.lookup(game.hash) {
if entry.depth >= depth
&& (matches!(entry.bound, Bound::Exact)
@@ -35,6 +29,7 @@ pub fn negamax(
{
return (entry.mv, entry.score);
}
tt_move = entry.mv;
}
let color = game.current_player();
@@ -43,6 +38,13 @@ pub fn negamax(
let mut pseudo_legal_moves = game.board.pseudo_moves_all();
pseudo_legal_moves.sort_unstable_by_key(|mv| score_by_mvv_lva(&game.mailbox, *mv));
if let Some(tt_move) = tt_move {
if let Some(tt_move_index) = pseudo_legal_moves.iter().position(|&mv| mv == tt_move) {
pseudo_legal_moves.remove(tt_move_index);
pseudo_legal_moves.insert(0, tt_move);
}
}
for mv in pseudo_legal_moves {
game.make_move(&mv);
@@ -52,7 +54,7 @@ pub fn negamax(
}
legal_moves += 1;
let move_score = -negamax(game, -beta, -alpha, depth - 1, plies + 1, tt, nodes).1;
let move_score = -negamax(game, -beta, -alpha, depth - 1, plies + 1, tt).1;
game.unmake_move();
if move_score > best_score {
@@ -65,7 +67,7 @@ pub fn negamax(
game.hash,
depth,
best_score,
None,
best_move,
Bound::Lower,
));
return (best_move, beta);
@@ -80,12 +82,12 @@ pub fn negamax(
game.hash,
depth,
mate_score,
None,
best_move,
Bound::Exact,
));
return (None, mate_score);
}
tt.insert(TTEntry::new(game.hash, depth, 0, None, Bound::Exact));
tt.insert(TTEntry::new(game.hash, depth, 0, best_move, Bound::Exact));
return (None, 0);
}
@@ -104,12 +106,13 @@ pub fn negamax(
#[cfg(test)]
mod tests {
use crate::board::transposition_table::TranspositionTable;
use crate::board::{fen::from_fen, square::Square};
use crate::evaluation::{MAX_SCORE, MIN_SCORE};
use crate::movegen::attack_generator::init_attacks;
use crate::movegen::r#move::Move;
use crate::search::negamax::negamax;
use crate::search::transposition_table::TranspositionTable;
use crate::search::MAX_TT_SIZE;
const FEN_MATE_IN_1: [&str; 2] = [
"8/8/8/8/8/4q1k1/8/5K2 b - - 0 1",
@@ -121,13 +124,11 @@ mod tests {
init_attacks();
let mut game = from_fen(FEN_MATE_IN_1[0])?;
let mut tt = TranspositionTable::new(1000000);
let mut tt = TranspositionTable::new(MAX_TT_SIZE);
let e3f2 = Move::new(Square::E3, Square::F2);
let mut nodes = 0;
let anointed_move = negamax(&mut game, MIN_SCORE, MAX_SCORE, 2, 0, &mut tt, &mut nodes)
let anointed_move = negamax(&mut game, MIN_SCORE, MAX_SCORE, 2, 0, &mut tt)
.0
.unwrap();
dbg!(nodes);
assert_eq!(e3f2, anointed_move);

View File

@@ -80,23 +80,22 @@ mod tests {
let mut nodes = 0;
driver(&mut game, &mut nodes, depth);
dbg!(time_now.elapsed());
dbg!(nodes, time_now.elapsed());
Ok(nodes)
}
const FEN: &str = "1r2k2r/2P1pq1p/2npb3/1p3ppP/p3P3/P2B1Q2/1P1PNPP1/R3K2R w KQk g6 0 1";
#[ignore]
// #[ignore]
#[test]
fn test_nodes() -> Result<(), String> {
init_attacks();
assert_eq!(perft(FEN, 6)?, 0);
perft(FEN, 4)?;
Ok(())
}
#[test]
fn test_perft_1() -> Result<(), String> {
init_attacks();

View File

@@ -2,15 +2,7 @@ use crate::{board::game::Game, evaluation::evaluation::evaluate_position, movege
use super::move_ordering::score_by_mvv_lva;
pub fn quiescence(
game: &mut Game,
mut alpha: i32,
beta: i32,
nodes: &mut u64,
depth: u8,
) -> (Option<Move>, i32) {
*nodes += 1;
pub fn quiescence(game: &mut Game, mut alpha: i32, beta: i32, depth: u8) -> (Option<Move>, i32) {
if depth == 0 {
return (None, evaluate_position(&game.board));
}
@@ -37,7 +29,7 @@ pub fn quiescence(
continue;
}
let move_score = -quiescence(game, -beta, -alpha, nodes, depth - 1).1;
let move_score = -quiescence(game, -beta, -alpha, depth - 1).1;
game.unmake_move();
if move_score >= beta {

View File

@@ -0,0 +1,109 @@
use crate::{board::zobrist::ZobristHash, movegen::r#move::Move};
pub struct TranspositionTable {
positions: Vec<Option<TTEntry>>,
size: u64,
}
impl TranspositionTable {
pub fn new(size: u64) -> Self {
Self {
positions: vec![None; size as usize],
size,
}
}
pub fn lookup(&self, zobrist_hash: ZobristHash) -> Option<&TTEntry> {
let entry = self
.positions
.get((zobrist_hash.hash % self.size) as usize)
.and_then(|entry| entry.as_ref());
entry
}
pub fn insert(&mut self, tt_entry: TTEntry) {
let index = (tt_entry.hash.hash % self.size) as usize;
if let Some(stored) = &self.positions[index] {
if tt_entry.depth > stored.depth || matches!(tt_entry.bound, Bound::Exact) {
self.positions[index] = Some(tt_entry);
}
} else {
self.positions[index] = Some(tt_entry);
}
}
}
#[derive(Clone)]
pub struct TTEntry {
pub hash: ZobristHash,
pub depth: u8,
pub score: i32,
pub mv: Option<Move>,
pub bound: Bound,
}
impl TTEntry {
pub const fn new(
hash: ZobristHash,
depth: u8,
score: i32,
mv: Option<Move>,
bound: Bound,
) -> Self {
Self {
hash,
depth,
score,
mv,
bound,
}
}
}
#[derive(Clone)]
pub enum Bound {
Exact,
Lower,
Upper,
}
#[cfg(test)]
mod tests {
use crate::{
board::fen::from_fen,
evaluation::{MAX_SCORE, MIN_SCORE},
movegen::attack_generator::init_attacks,
search::{self, transposition_table::TranspositionTable, MAX_TT_SIZE},
};
const FEN: &str = "1r2k2r/2P1pq1p/2npb3/1p3ppP/p3P3/P2B1Q2/1P1PNPP1/R3K2R w KQk g6 0 1";
const FEN_WILL_BE: &str = "1r2k2r/2P1pq1p/2npb3/1B3ppP/p3P3/P4Q2/1P1PNPP1/R3K2R b KQk - 0 1";
const FEN_WONT_BE: &str = "1Q2k2r/2P1pq1p/2npb3/1p3ppP/p3P3/P2B4/1P1PNPP1/R3K2R b KQk - 0 1";
#[test]
fn test_transposition_table() -> Result<(), String> {
init_attacks();
let mut game = from_fen(FEN)?;
let mut tt = TranspositionTable::new(MAX_TT_SIZE);
let time_now = std::time::Instant::now();
// fill Transposition Table
search::negamax::negamax(&mut game, MIN_SCORE, MAX_SCORE, 4, 0, &mut tt);
dbg!(time_now.elapsed());
let will_be_hash = from_fen(FEN_WILL_BE)?.hash;
let tt_entry = tt.lookup(will_be_hash);
assert!(tt_entry.is_some());
// needs a bigger tt size because it could be a collision entry
let wont_be_hash = from_fen(FEN_WONT_BE)?.hash;
let tt_entry = tt.lookup(wont_be_hash);
assert!(tt_entry.is_none());
Ok(())
}
}