use alloc::vec::Vec;
use core::mem;
use crate::table::{Memory, Transpositions};
use crate::{Game, Hashed, NoTable, ScoredMove, Stats, Table};
#[derive(Debug)]
pub struct Searcher<G: Game, T = NoTable> {
moves: Vec<Vec<G::Move>>,
lines: Vec<Vec<ScoredMove<G::Move, G::Score>>>,
pub(crate) hint: Vec<G::Move>,
pub(crate) aborted: bool,
pub(crate) stats: Stats,
pub(crate) table: T,
pub(crate) algorithm: Algorithm,
pub(crate) guess: Option<G::Score>,
pub(crate) root_moves: Vec<ScoredMove<G::Move, G::Score>>,
pub(crate) lead: u32,
pub(crate) budget_first: bool,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Algorithm {
#[default]
AlphaBeta,
Pvs,
Mtdf,
}
impl<G: Game> Searcher<G> {
#[must_use]
pub const fn new() -> Self {
Self::with_memory(NoTable)
}
}
impl<G: Hashed, T: Table<G::Key, G::Move, G::Score>> Searcher<G, Transpositions<T>> {
#[must_use]
pub const fn with_table(table: T) -> Self {
Self::with_memory(Transpositions(table))
}
#[must_use]
pub const fn table(&self) -> &T {
&self.table.0
}
pub const fn table_mut(&mut self) -> &mut T {
&mut self.table.0
}
}
impl<G: Game, T: Memory<G>> Searcher<G, T> {
const fn with_memory(table: T) -> Self {
Self {
moves: Vec::new(),
lines: Vec::new(),
hint: Vec::new(),
aborted: false,
stats: Stats::ZERO,
table,
algorithm: Algorithm::AlphaBeta,
guess: None,
root_moves: Vec::new(),
lead: 0,
budget_first: false,
}
}
#[must_use]
pub const fn with_algorithm(mut self, algorithm: Algorithm) -> Self {
self.algorithm = algorithm;
self
}
#[must_use]
pub const fn algorithm(&self) -> Algorithm {
self.algorithm
}
pub(crate) fn enter(&mut self, ply: usize) -> Vec<G::Move> {
while self.lines.len() <= ply {
self.lines.push(Vec::new());
self.moves.push(Vec::new());
}
self.lines[ply].clear();
mem::take(&mut self.moves[ply])
}
pub(crate) fn leave(&mut self, ply: usize, mut moves: Vec<G::Move>) {
moves.clear();
self.moves[ply] = moves;
}
pub(crate) fn adopt(&mut self, ply: usize, step: ScoredMove<G::Move, G::Score>) {
let (above, below) = self.lines.split_at_mut(ply + 1);
let line = &mut above[ply];
line.clear();
line.push(step);
line.extend_from_slice(&below[0]);
}
pub(crate) fn line(&self, ply: usize) -> &[ScoredMove<G::Move, G::Score>] {
self.lines.get(ply).map_or(&[], Vec::as_slice)
}
}
impl<G: Game> Default for Searcher<G> {
fn default() -> Self {
Self::new()
}
}