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;
pub const NAME: &str = env!("CARGO_PKG_NAME");
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
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";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Command {
Play(Options),
Help,
Version,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Options {
pub dimensions: BoardDimensions,
pub difficulty: Difficulty,
pub seed: Option<u64>,
}
#[derive(Debug, Clone, PartialEq, Eq, Error, Diagnostic)]
#[non_exhaustive]
pub enum CliError {
#[error("unknown argument {argument:?}")]
#[diagnostic(
code(fours::unknown_argument),
help("Run with --help to see the arguments.")
)]
UnknownArgument { argument: String },
#[error("{option} needs a value")]
#[diagnostic(code(fours::missing_value), help("Write it as {option} <number>."))]
MissingValue { option: String },
#[error("{value:?} is not a number for {option}")]
#[diagnostic(code(fours::invalid_number))]
InvalidNumber { option: String, value: String },
#[error("{value:?} is not a difficulty: {reason}")]
#[diagnostic(code(fours::invalid_difficulty))]
InvalidDifficulty { value: String, reason: String },
#[error(transparent)]
#[diagnostic(
code(fours::invalid_board),
help("Boards run from {MINIMUM_SIDE} to {MAXIMUM_SIDE} columns and rows.")
)]
InvalidBoard(#[from] GameError),
}
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(),
})
}