fours 0.1.0

Four in a row in your terminal, with three levels of opponent.
Documentation
use crate::bot::Bot;
use crate::bot::random_numbers;
use crate::game::GameState;
use crate::game::Player;
use rand::rngs::StdRng;
use rand::seq::IndexedRandom;

/// A bot that plays the move in front of its nose.
///
/// It takes a win when it has one, avoids handing one to its opponent, and otherwise plays towards
/// the middle of the board, where lines are easiest to build. Blocking comes out of avoiding
/// handed out wins: the only move that stops a threat is usually the only safe one.
///
/// # Examples
///
/// ```
/// use fours::bot::Bot;
/// use fours::bot::TacticalBot;
/// use fours::game::Game;
///
/// // Red threatens a line along the bottom row and it is the bot's turn as yellow.
/// let game = Game::from_moves([0, 5, 1, 6, 2]).unwrap();
/// let mut bot = TacticalBot::seeded(1);
///
/// assert_eq!(bot.choose_move(game.state()), Some(3));
/// ```
#[derive(Debug, Clone)]
pub struct TacticalBot {
    random_numbers: StdRng,
}

impl TacticalBot {
    /// A bot seeded from the operating system, which plays differently every run.
    pub fn from_entropy() -> Self {
        Self::with_seed(None)
    }

    /// A bot seeded with a fixed value, which plays the same way every run.
    pub fn seeded(seed: u64) -> Self {
        Self::with_seed(Some(seed))
    }

    pub(crate) fn with_seed(seed: Option<u64>) -> Self {
        Self {
            random_numbers: random_numbers(seed),
        }
    }

    /// A move that does not let the opponent win straight away, preferring the middle.
    fn safe_move(&mut self, state: &GameState, moves: &[usize]) -> Option<usize> {
        let safe: Vec<usize> = moves
            .iter()
            .copied()
            .filter(|column| !hands_over_a_win(state, *column))
            .collect();
        let candidates = if safe.is_empty() { moves } else { &safe };

        candidates
            .choose_weighted(&mut self.random_numbers, |column| {
                centrality(*column, state.column_count())
            })
            .ok()
            .copied()
    }
}

impl Default for TacticalBot {
    fn default() -> Self {
        Self::from_entropy()
    }
}

impl Bot for TacticalBot {
    fn choose_move(&mut self, state: &GameState) -> Option<usize> {
        let moves = state.legal_moves();
        if moves.is_empty() {
            return None;
        }

        let winning = moves
            .iter()
            .copied()
            .find(|column| wins_now(state, *column, state.current_player()));

        winning.or_else(|| self.safe_move(state, &moves))
    }

    fn name(&self) -> &'static str {
        "Tactical bot"
    }
}

/// The position after a move, if the move can be played.
fn after(state: &GameState, column: usize) -> Option<GameState> {
    let mut next = state.clone();
    next.apply_move(column).ok()?;

    Some(next)
}

/// Whether a player wins the game by playing a column right now.
fn wins_now(state: &GameState, column: usize, player: Player) -> bool {
    after(state, column).and_then(|next| next.winner()) == Some(player)
}

/// Whether a move lets the opponent win with their answer to it.
fn hands_over_a_win(state: &GameState, column: usize) -> bool {
    let Some(next) = after(state, column) else {
        return false;
    };
    let opponent = next.current_player();

    next.legal_moves()
        .into_iter()
        .any(|answer| wins_now(&next, answer, opponent))
}

/// How close a column is to the middle of the board, as a weight of at least one.
fn centrality(column: usize, column_count: usize) -> u32 {
    let middle = column_count / 2;
    let distance = column.abs_diff(middle);
    let weight = column_count.saturating_sub(distance);

    u32::try_from(weight).unwrap_or(u32::MAX).max(1)
}