game-tree-search 0.2.4

Adversarial game-tree search for computer opponents in board, card and turn-based games: minimax, negamax, alpha-beta, principal variation search, MTD(f), iterative deepening with transposition tables, expectimax and Monte Carlo tree search
Documentation
//! Plain minimax: the reference every faster search must agree with.

use alloc::vec::Vec;

use crate::game::expanded_moves;
use crate::result::{Line, RootMoves};
use crate::{Bound, Game, Score, ScoredMove, SearchResult, Side, Stats};

/// Searches every line from `position` up to `depth` plies and returns the minimax score.
///
/// [`Side::Max`] picks the highest child score, [`Side::Min`] the lowest; the side to move
/// comes from [`Game::side_to_move`], so one side may move several times in a row. Visits
/// every position of the tree, which grows exponentially with `depth`; it serves as the
/// reference the faster searches are tested against. Ties go to the earliest move.
///
/// # Examples
///
/// See [`Game`] for a complete game.
#[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,
    }
}

/// The minimax score of `position`, `ply` moves below the root with `depth` plies left, and
/// its principal variation in reverse (last move first), so each level appends its move in
/// constant time.
///
/// Records every child of the root in `root_moves`, given only at the root.
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),
    )
}

/// The value of `position`, where its side to move chooses the best child, each valued by
/// `value` from the child's position, its `(ply, depth)` and the counters: the minimax step
/// shared by the reference searches.
///
/// Searches the [`Game::noisy_moves`] past the horizon, where the side may also stand pat,
/// records every child in `root_moves` (given only at the root) and returns the line in
/// reverse (last move first). Ties go to the earliest move.
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")
}

/// The score a quiescence position keeps if its side declines every noisy move, with an
/// empty line; `None` above the horizon, where every move must be searched.
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()))
}

/// Whether `score` is strictly better for `side` than `best`.
pub(crate) fn improves<S: Score>(side: Side, score: S, best: S) -> bool {
    match side {
        Side::Max => score > best,
        Side::Min => score < best,
    }
}