Probe TT at each negamax recursion and store entries based on bounds

This commit is contained in:
stefiosif
2024-10-14 23:57:54 +03:00
parent 33617df497
commit b2df931d48
5 changed files with 135 additions and 68 deletions

View File

@@ -1,5 +1,8 @@
use crate::{
board::game::Game,
board::{
game::Game,
transposition_table::{Bound, TTEntry, TranspositionTable},
},
evaluation::{MATE_SCORE, MIN_SCORE},
movegen::r#move::Move,
};
@@ -12,16 +15,25 @@ pub fn negamax(
beta: i32,
depth: u8,
plies: u8,
tt: &mut TranspositionTable,
) -> (Option<Move>, i32) {
let color = game.current_player();
if depth == 0 {
return (None, quiescence(game, alpha, beta).1);
}
if let Some(entry) = tt.lookup(game.hash) {
if entry.depth >= depth
&& (matches!(entry.bound, Bound::Exact)
|| (matches!(entry.bound, Bound::Lower) && entry.score >= beta)
|| (matches!(entry.bound, Bound::Upper) && entry.score <= alpha))
{
return (entry.mv, entry.score);
}
}
let color = game.current_player();
let (mut best_move, mut best_score, mate_score) = (None, MIN_SCORE, -MATE_SCORE + plies as i32);
let mut legal_moves = 0;
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));
@@ -32,9 +44,9 @@ pub fn negamax(
game.unmake_move();
continue;
}
legal_moves += 1;
let move_score = -negamax(game, -beta, -alpha, depth - 1, plies + 1).1;
let move_score = -negamax(game, -beta, -alpha, depth - 1, plies + 1, tt).1;
game.unmake_move();
if move_score > best_score {
@@ -43,6 +55,13 @@ pub fn negamax(
}
if move_score >= beta {
tt.insert(TTEntry::new(
game.hash,
depth,
best_score,
None,
Bound::Lower,
));
return (best_move, beta);
}
@@ -51,15 +70,35 @@ pub fn negamax(
if legal_moves == 0 {
if game.board.king_under_check(color) {
tt.insert(TTEntry::new(
game.hash,
depth,
mate_score,
None,
Bound::Exact,
));
return (None, mate_score);
}
tt.insert(TTEntry::new(game.hash, depth, 0, None, Bound::Exact));
return (None, 0);
}
if best_score < alpha {
tt.insert(TTEntry::new(
game.hash,
depth,
best_score,
best_move,
Bound::Upper,
));
}
(best_move, best_score)
}
#[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;
@@ -76,8 +115,11 @@ mod tests {
init_attacks();
let mut game = from_fen(FEN_MATE_IN_1[0])?;
let mut tt = TranspositionTable::new(1000000);
let e3f2 = Move::new(Square::E3, Square::F2);
let anointed_move = negamax(&mut game, MIN_SCORE, MAX_SCORE, 2, 0).0.unwrap();
let anointed_move = negamax(&mut game, MIN_SCORE, MAX_SCORE, 2, 0, &mut tt)
.0
.unwrap();
assert_eq!(e3f2, anointed_move);