fours 0.1.0

Four in a row in your terminal, with three levels of opponent.
Documentation
//! The command line of the game.

use crate::bot::Difficulty;
use crate::bot::UnknownDifficulty;
use crate::game::BoardDimensions;
use crate::game::GameError;
use crate::game::MAXIMUM_SIDE;
use crate::game::MINIMUM_SIDE;
use miette::Diagnostic;
use thiserror::Error;

/// The name of the program.
pub const NAME: &str = env!("CARGO_PKG_NAME");

/// The version of the program.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

/// The text shown for `--help`.
pub const HELP: &str = "\
Four in a row in your terminal.

Usage: fours [options]

Options:
      --difficulty <name>  Play against easy, medium or hard [default: medium]
      --columns <number>   Columns of the board [default: 7]
      --rows <number>      Rows of the board [default: 6]
      --seed <number>      Seed of the opponent, for a reproducible game
  -h, --help               Show this text
  -V, --version            Show the version

Controls:
  Arrow keys, or h and l, move between columns
  Enter or space places a disc, d moves on to the next level, r starts a new
  game and q leaves";

/// What the program was asked to do.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Command {
    /// Play a game with these settings.
    Play(Options),
    /// Show the help text.
    Help,
    /// Show the version.
    Version,
}

/// The settings of a game.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Options {
    /// The size of the board.
    pub dimensions: BoardDimensions,
    /// The level to play at.
    pub difficulty: Difficulty,
    /// The seed of the opponent, if the game should be reproducible.
    pub seed: Option<u64>,
}

/// The reason a command line could not be understood.
#[derive(Debug, Clone, PartialEq, Eq, Error, Diagnostic)]
#[non_exhaustive]
pub enum CliError {
    /// An argument that the program does not know about.
    #[error("unknown argument {argument:?}")]
    #[diagnostic(
        code(fours::unknown_argument),
        help("Run with --help to see the arguments.")
    )]
    UnknownArgument { argument: String },

    /// An option that was given without its value.
    #[error("{option} needs a value")]
    #[diagnostic(code(fours::missing_value), help("Write it as {option} <number>."))]
    MissingValue { option: String },

    /// A value that should have been a number.
    #[error("{value:?} is not a number for {option}")]
    #[diagnostic(code(fours::invalid_number))]
    InvalidNumber { option: String, value: String },

    /// A level the game does not have.
    #[error("{value:?} is not a difficulty: {reason}")]
    #[diagnostic(code(fours::invalid_difficulty))]
    InvalidDifficulty { value: String, reason: String },

    /// A board size that cannot be played on.
    #[error(transparent)]
    #[diagnostic(
        code(fours::invalid_board),
        help("Boards run from {MINIMUM_SIDE} to {MAXIMUM_SIDE} columns and rows.")
    )]
    InvalidBoard(#[from] GameError),
}

/// Read a command line.
///
/// # Errors
///
/// Returns a [`CliError`] when an argument is unknown, misses its value or does not describe a
/// board that can be played on.
///
/// # Examples
///
/// ```
/// use fours::cli;
///
/// let command = cli::parse(["--seed".to_owned(), "7".to_owned()]).unwrap();
/// assert!(matches!(command, cli::Command::Play(_)));
/// ```
pub fn parse<I>(arguments: I) -> Result<Command, CliError>
where
    I: IntoIterator<Item = String>,
{
    let mut arguments = arguments.into_iter();
    let mut columns = BoardDimensions::STANDARD.column_count();
    let mut rows = BoardDimensions::STANDARD.row_count();
    let mut difficulty = Difficulty::default();
    let mut seed = None;

    while let Some(argument) = arguments.next() {
        match argument.as_str() {
            "-h" | "--help" => return Ok(Command::Help),
            "-V" | "--version" => return Ok(Command::Version),
            "--columns" => columns = number(&argument, arguments.next())?,
            "--rows" => rows = number(&argument, arguments.next())?,
            "--seed" => seed = Some(number(&argument, arguments.next())?),
            "--difficulty" => difficulty = level(&argument, arguments.next())?,
            _ => return Err(CliError::UnknownArgument { argument }),
        }
    }

    Ok(Command::Play(Options {
        dimensions: BoardDimensions::new(columns, rows)?,
        difficulty,
        seed,
    }))
}

fn level(option: &str, value: Option<String>) -> Result<Difficulty, CliError> {
    let value = expect_value(option, value)?;

    value
        .parse()
        .map_err(|reason: UnknownDifficulty| CliError::InvalidDifficulty {
            value,
            reason: reason.to_string(),
        })
}

fn number<T>(option: &str, value: Option<String>) -> Result<T, CliError>
where
    T: std::str::FromStr,
{
    let value = expect_value(option, value)?;

    value.parse().map_err(|_| CliError::InvalidNumber {
        option: option.to_owned(),
        value,
    })
}

fn expect_value(option: &str, value: Option<String>) -> Result<String, CliError> {
    value.ok_or_else(|| CliError::MissingValue {
        option: option.to_owned(),
    })
}