use alloc::vec::Vec;
use crate::game::expanded_moves;
use crate::result::{Line, RootMoves};
use crate::{Bound, Game, Score, ScoredMove, SearchResult, Side, Stats};
#[must_use]
pub fn minimax<G: Game>(
game: &G,
position: &G::Position,
depth: u32,
) -> SearchResult<G::Move, G::Score> {
let mut stats = Stats::default();
let mut root_moves = Vec::new();
let (score, mut pv) = search(
game,
position,
(0, depth),
Some(&mut root_moves),
&mut stats,
);
pv.reverse();
SearchResult {
score,
bound: Bound::Exact,
pv,
root_moves,
unexamined: 0,
depth,
proven: stats.horizon == 0,
stats,
}
}
fn search<G: Game>(
game: &G,
position: &G::Position,
(ply, depth): (u32, u32),
root_moves: RootMoves<'_, G>,
stats: &mut Stats,
) -> (G::Score, Line<G>) {
choose(
game,
position,
(ply, depth),
root_moves,
stats,
&mut |child, next, stats| search(game, child, next, None, stats),
)
}
pub(crate) fn choose<G: Game>(
game: &G,
position: &G::Position,
(ply, depth): (u32, u32),
mut root_moves: RootMoves<'_, G>,
stats: &mut Stats,
value: &mut impl FnMut(&G::Position, (u32, u32), &mut Stats) -> (G::Score, Line<G>),
) -> (G::Score, Line<G>) {
stats.visit(ply);
let moves = expanded_moves(game, position, depth, stats);
if moves.is_empty() {
return (game.evaluate(position), Vec::new());
}
let side = game.side_to_move(position);
let mut best = stand_pat(game, position, depth);
for mv in moves {
let child = game.play(position, &mv);
let (score, mut line) = value(&child, (ply + 1, depth.saturating_sub(1)), stats);
if let Some(root_moves) = root_moves.as_deref_mut() {
root_moves.push(ScoredMove::exact(mv.clone(), score));
}
if best
.as_ref()
.is_none_or(|&(best, _)| improves(side, score, best))
{
line.push(ScoredMove::exact(mv, score));
best = Some((score, line));
}
}
best.expect("a position with moves has a best child")
}
pub(crate) fn stand_pat<G: Game>(
game: &G,
position: &G::Position,
depth: u32,
) -> Option<(G::Score, Line<G>)> {
(depth == 0).then(|| (game.evaluate(position), Vec::new()))
}
pub(crate) fn improves<S: Score>(side: Side, score: S, best: S) -> bool {
match side {
Side::Max => score > best,
Side::Min => score < best,
}
}