Add TT cutoffs

This commit is contained in:
stefiosif
2025-01-26 23:58:44 +02:00
parent 53beda7fe3
commit a01310c7b7
5 changed files with 71 additions and 32 deletions

View File

@@ -9,7 +9,7 @@ use super::{
move_ordering::score_move,
quiescence::quiescence,
time::TimeInfo,
transposition_table::TTEntry,
transposition_table::{NodeType, TTEntry},
};
pub fn negamax(
@@ -30,8 +30,7 @@ pub fn negamax(
}
if depth == 0 {
let q_score =
quiescence(game, alpha, beta, time, nodes).map_err(|e| anyhow!("{e}"))?;
let q_score = quiescence(game, alpha, beta, time, nodes).map_err(|e| anyhow!("{e}"))?;
return Ok(q_score);
}
@@ -40,9 +39,22 @@ pub fn negamax(
let mut best_score = MIN_SCORE;
let mut best_move = None;
let mut moves = game.board.pseudo_moves_all();
let tt_move = game.tt.lookup(game.hash).and_then(|entry| entry.mv);
let tt_entry = game.tt.lookup(game.hash);
moves.sort_unstable_by_key(|mv| score_move(&game.mailbox, *mv, tt_move));
if let Some(tt_entry) = tt_entry {
if plies > 0 && tt_entry.hash == game.hash && tt_entry.depth >= depth {
match tt_entry.node_type {
NodeType::Exact => return Ok(tt_entry.score),
NodeType::LowerBound if tt_entry.score >= beta => return Ok(tt_entry.score),
NodeType::UpperBound if tt_entry.score <= alpha => return Ok(tt_entry.score),
_ => (),
}
}
}
moves.sort_unstable_by_key(|mv| {
score_move(&game.mailbox, *mv, tt_entry.and_then(|entry| entry.mv))
});
for mv in moves {
game.make_move(&mv);
@@ -57,15 +69,7 @@ pub fn negamax(
let score = if legal_moves == 1 {
-negamax(game, -beta, -alpha, depth - 1, plies + 1, time, nodes)?
} else {
let mut score = -negamax(
game,
-alpha - 1,
-alpha,
depth - 1,
plies + 1,
time,
nodes,
)?;
let mut score = -negamax(game, -alpha - 1, -alpha, depth - 1, plies + 1, time, nodes)?;
if score > alpha && score < beta {
score = -negamax(game, -beta, -alpha, depth - 1, plies + 1, time, nodes)?;
}
@@ -95,7 +99,15 @@ pub fn negamax(
return Ok(0);
}
game.tt.insert(TTEntry::new(game.hash, best_move));
let node_type = match best_score {
s if s >= beta => NodeType::LowerBound,
s if s <= alpha => NodeType::UpperBound,
_ => NodeType::Exact,
};
game.tt.insert(TTEntry::new(
game.hash, best_move, depth, best_score, node_type,
));
Ok(best_score)
}