81 lines
2.2 KiB
Rust
81 lines
2.2 KiB
Rust
use crate::{board::zobrist::ZobristHash, movegen::r#move::Move};
|
|
|
|
#[derive(Clone, Debug, Eq, PartialEq)]
|
|
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.0 % self.size) as usize)
|
|
.and_then(|entry| entry.as_ref());
|
|
|
|
entry
|
|
}
|
|
|
|
pub fn insert(&mut self, tt_entry: TTEntry) {
|
|
let idx = (tt_entry.hash.0 % self.size) as usize;
|
|
self.positions[idx] = Some(tt_entry);
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Debug, Eq, PartialEq)]
|
|
pub struct TTEntry {
|
|
pub hash: ZobristHash,
|
|
pub mv: Option<Move>,
|
|
}
|
|
|
|
impl TTEntry {
|
|
pub const fn new(hash: ZobristHash, mv: Option<Move>) -> Self {
|
|
Self { hash, mv }
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use crate::{
|
|
board::fen::from_fen,
|
|
evaluation::{MAX_SCORE, MIN_SCORE},
|
|
movegen::attack_generator::init_attacks,
|
|
search::{negamax::negamax, time::TimeInfo},
|
|
};
|
|
|
|
const FEN: &str = "1r2k2r/2P1pq1p/2npb3/1p3ppP/p3P3/P2B1Q2/1P1PNPP1/R3K2R w KQk g6 0 1";
|
|
const FEN_POSSIBLE: &str = "1r2k2r/2P1pq1p/2npb3/1B3ppP/p3P3/P4Q2/1P1PNPP1/R3K2R b KQk - 0 1";
|
|
const FEN_IMPOSSIBLE: &str = "1Q2k2r/2P1pq1p/2npb3/1p3ppP/p3P3/P2B4/1P1PNPP1/R3K2R b KQk - 0 1";
|
|
|
|
#[test]
|
|
fn test_transposition_table() -> anyhow::Result<()> {
|
|
init_attacks();
|
|
let mut game = from_fen(FEN).unwrap();
|
|
let time_info = TimeInfo::new(std::time::Instant::now(), 30000, 100);
|
|
|
|
negamax(&mut game, MIN_SCORE, MAX_SCORE, 2, 0, &time_info, &mut 0)
|
|
.expect("Expected a search result");
|
|
|
|
dbg!(time_info.instant.elapsed());
|
|
|
|
let will_be_hash = from_fen(FEN_POSSIBLE).unwrap().hash;
|
|
let tt_entry = game.tt.lookup(will_be_hash);
|
|
|
|
assert!(tt_entry.is_some());
|
|
|
|
let wont_be_hash = from_fen(FEN_IMPOSSIBLE).unwrap().hash;
|
|
let tt_entry = game.tt.lookup(wont_be_hash);
|
|
|
|
assert!(tt_entry.is_none());
|
|
|
|
Ok(())
|
|
}
|
|
}
|