fours 0.1.0

Four in a row in your terminal, with three levels of opponent.
Documentation
use crate::app::Action;
use crate::app::Notice;
use crate::bot::Bot;
use crate::bot::Difficulty;
use crate::bot::Opponent;
use crate::game::BoardDimensions;
use crate::game::Game;
use crate::game::GameError;
use crate::game::GameState;
use crate::game::Player;
use crate::game::Status;

/// The front end state of a game against an opponent.
///
/// The application owns the game and the opponent, and is driven entirely by [`Action`]s, so it
/// can be used by any front end that can turn user input into actions. It never touches a
/// terminal.
///
/// A game is under way from the moment an application is made. The level can be changed at any
/// point, which swaps the opponent and leaves the board as it stands.
///
/// # Examples
///
/// ```
/// use fours::app::Action;
/// use fours::app::App;
/// use fours::bot::Difficulty;
/// use fours::game::BoardDimensions;
///
/// let mut app = App::seeded(BoardDimensions::STANDARD, 7);
/// app.handle(Action::Confirm);
///
/// // The player placed a disc and the opponent answered.
/// assert_eq!(app.state().disc_count(), 2);
///
/// app.handle(Action::CycleDifficulty);
///
/// // A new opponent took over the game that was already going.
/// assert_eq!(app.difficulty(), Difficulty::Hard);
/// assert_eq!(app.state().disc_count(), 2);
/// ```
#[derive(Debug)]
pub struct App {
    dimensions: BoardDimensions,
    seed: Option<u64>,
    difficulty: Difficulty,
    game: Game,
    opponent: Opponent,
    human_player: Player,
    selected_column: usize,
    notice: Option<Notice>,
    running: bool,
}

impl App {
    /// An application playing a game against an opponent that plays differently every run.
    pub fn new(dimensions: BoardDimensions) -> Self {
        Self::with_seed(dimensions, None)
    }

    /// An application whose opponents play the same way every run.
    pub fn seeded(dimensions: BoardDimensions, seed: u64) -> Self {
        Self::with_seed(dimensions, Some(seed))
    }

    /// An application that is playing the given game against the given opponent.
    ///
    /// Changing the level, or starting a new game with [`Action::Restart`], replaces the opponent
    /// with the standard one for its level.
    pub fn playing(game: Game, opponent: Opponent) -> Self {
        let dimensions = game.state().dimensions();

        Self {
            selected_column: dimensions.column_count() / 2,
            difficulty: opponent.difficulty(),
            dimensions,
            seed: None,
            game,
            opponent,
            human_player: Player::FIRST,
            notice: None,
            running: true,
        }
    }

    fn with_seed(dimensions: BoardDimensions, seed: Option<u64>) -> Self {
        let difficulty = Difficulty::default();
        let mut app = Self::playing(
            Game::with_dimensions(dimensions),
            opponent_for(difficulty, seed),
        );
        app.seed = seed;

        app
    }

    /// The level being played.
    pub const fn difficulty(&self) -> Difficulty {
        self.difficulty
    }

    /// The opponent.
    pub const fn opponent(&self) -> &Opponent {
        &self.opponent
    }

    /// The game being played.
    pub const fn game(&self) -> &Game {
        &self.game
    }

    /// The position of the game being played.
    pub const fn state(&self) -> &GameState {
        self.game.state()
    }

    /// The player who is controlled by whoever is at the keyboard.
    pub const fn human_player(&self) -> Player {
        self.human_player
    }

    /// The column a disc would be placed in.
    pub const fn selected_column(&self) -> usize {
        self.selected_column
    }

    /// The remark about the last action, if there is one.
    pub const fn notice(&self) -> Option<Notice> {
        self.notice
    }

    /// Whether the front end should keep running.
    pub const fn is_running(&self) -> bool {
        self.running
    }

    /// Whether the player may place a disc right now.
    pub fn is_waiting_for_player(&self) -> bool {
        !self.state().is_over() && self.state().current_player() == self.human_player
    }

    /// What the game is waiting for, or how it ended.
    pub fn headline(&self) -> Headline {
        match self.state().status() {
            Status::InProgress => Headline::Turn(self.state().current_player()),
            Status::Won(victory) => Headline::Won(victory.winner()),
            Status::Draw => Headline::Draw,
        }
    }

    /// The text a front end shows for the current [`Headline`].
    pub fn headline_text(&self) -> String {
        match self.headline() {
            Headline::Turn(player) if player == self.human_player => "Your turn".to_owned(),
            Headline::Turn(_) => format!("{} is thinking", self.opponent.name()),
            Headline::Won(player) if player == self.human_player => "You win!".to_owned(),
            Headline::Won(_) => format!("{} wins", self.opponent.name()),
            Headline::Draw => "A draw, the board is full".to_owned(),
        }
    }

    /// Face the opponent of a level, keeping the game as it stands.
    ///
    /// The board is left alone, so a game can be finished against a different opponent than it was
    /// started against.
    pub fn set_difficulty(&mut self, difficulty: Difficulty) {
        self.difficulty = difficulty;
        self.opponent = opponent_for(difficulty, self.seed);
    }

    /// Start a new game against the level being played.
    pub fn restart(&mut self) {
        self.game = Game::with_dimensions(self.dimensions);
        self.opponent = opponent_for(self.difficulty, self.seed);
        self.selected_column = self.dimensions.column_count() / 2;
        self.notice = None;
    }

    /// Apply an action.
    pub fn handle(&mut self, action: Action) {
        self.notice = None;

        match action {
            Action::Previous => self.select(self.selected_column.saturating_sub(1)),
            Action::Next => self.select(self.selected_column.saturating_add(1)),
            Action::Choose(column) => self.select(column),
            Action::Confirm => self.place_disc(),
            Action::CycleDifficulty => self.set_difficulty(self.difficulty.next()),
            Action::SetDifficulty(difficulty) => self.set_difficulty(difficulty),
            Action::Restart => self.restart(),
            Action::Quit => self.running = false,
        }
    }

    /// Point at a column, ignoring columns outside the board.
    fn select(&mut self, column: usize) {
        if column < self.state().column_count() {
            self.selected_column = column;
        }
    }

    /// Place a disc in the selected column and let the opponent answer.
    fn place_disc(&mut self) {
        if self.state().is_over() {
            self.notice = Some(Notice::GameFinished);
            return;
        }

        if !self.is_waiting_for_player() {
            return;
        }

        match self.game.play(self.selected_column) {
            Ok(_) => self.play_opponent_turns(),
            Err(GameError::ColumnFull { .. }) => self.notice = Some(Notice::ColumnFull),
            Err(_) => self.notice = Some(Notice::MoveRejected),
        }
    }

    /// Let the opponent play until it is the player's turn again.
    fn play_opponent_turns(&mut self) {
        while !self.state().is_over() && self.state().current_player() != self.human_player {
            let Some(column) = self.opponent.choose_move(self.game.state()) else {
                return;
            };

            if self.game.play(column).is_err() {
                self.notice = Some(Notice::MoveRejected);
                return;
            }
        }
    }
}

impl Default for App {
    fn default() -> Self {
        Self::new(BoardDimensions::STANDARD)
    }
}

/// The opponent of a level, seeded when the application was.
fn opponent_for(difficulty: Difficulty, seed: Option<u64>) -> Opponent {
    seed.map_or_else(
        || Opponent::new(difficulty),
        |seed| Opponent::seeded(difficulty, seed),
    )
}

/// What a game is waiting for, or how it ended.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Headline {
    /// It is this player's turn.
    Turn(Player),
    /// This player won.
    Won(Player),
    /// The board filled up without a winner.
    Draw,
}

impl Headline {
    /// The player the headline is about, if it is about one.
    pub const fn player(self) -> Option<Player> {
        match self {
            Self::Turn(player) | Self::Won(player) => Some(player),
            Self::Draw => None,
        }
    }
}