Compare commits

...

2 Commits

Author SHA1 Message Date
Mark e8614dd29f
Cleanup 2024-03-05 14:35:26 -08:00
Mark b344ae359b
Documentation & Tweaks 2024-03-05 14:22:30 -08:00
11 changed files with 124 additions and 73 deletions

14
Cargo.lock generated
View File

@ -170,13 +170,7 @@ dependencies = [
] ]
[[package]] [[package]]
name = "numtoa" name = "minimax"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8f8bdf33df195859076e54ab11ee78a1b208382d3a26ec40d142ffc1ecc49ef"
[[package]]
name = "ops"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
@ -186,6 +180,12 @@ dependencies = [
"termion", "termion",
] ]
[[package]]
name = "numtoa"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8f8bdf33df195859076e54ab11ee78a1b208382d3a26ec40d142ffc1ecc49ef"
[[package]] [[package]]
name = "ppv-lite86" name = "ppv-lite86"
version = "0.2.17" version = "0.2.17"

View File

@ -1,5 +1,5 @@
[package] [package]
name = "ops" name = "minimax"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"

28
README.md Normal file
View File

@ -0,0 +1,28 @@
# Minimax
## Rules
This game is played in two rounds, starting with an empty eleven-space board. Red always goes first.
On Red's board (i.e, duing the first round), Red's job is to maximize the value of the expression; Blue's job is to minimize it.
Players take turns placing the fourteen symbols `0123456789+-×÷` on the board, with the maximizing player taking the first move.
A board's syntax must always be valid. Namely, the following rules are enforced:
- Each symbol may only be used once
- The binary operators `+-×÷` may not be next to one another, and may not be at the end slots.
- The unary operator `-` (negative) must have a number as an argument. Therefore, it cannot be left of an operator (like `-×`), and it may not be in the rightmost slot.
- `0` may not follow `÷`. This prevents most cases of zero-division, but isn't perfect. `÷-0` will break the game, and `÷0_+` is forbidden despite being valid syntax once the empty slot is filled (for example, with `÷03+`). This is done to simplyify game logic, and might be improved later.
## Building & Running
As always, run this project with `cargo run`. The app takes one argument by default: the name of the blue player. This can be any of the following:
- `human`: Play against a human
- `random`: Play against a random agent (very easy)
- `chase`: Play against a simple extremum-chasing agent (easy)
- `diffuse`: Play against a slightly more intellegent extremum chaser (medium)
For example, `cargo run -- random` will play a game against a random player.
Additional options are available, see `cargo run -- --help`.

View File

@ -8,11 +8,11 @@ use crate::{
util::{Player, Symb}, util::{Player, Symb},
}; };
pub struct SimpleMinimax { pub struct Chase {
player: Player, player: Player,
} }
impl SimpleMinimax { impl Chase {
pub fn new(player: Player) -> Self { pub fn new(player: Player) -> Self {
Self { player } Self { player }
} }
@ -33,13 +33,13 @@ impl SimpleMinimax {
return Random::new(self.player).step_min(board); return Random::new(self.player).step_min(board);
} }
let t = free_slots_by_influence(&board); let t = free_slots_by_influence(board);
if t.is_none() { if t.is_none() {
bail!("could not compute next move!") bail!("could not compute next move!")
} }
let t = t.unwrap(); let t = t.unwrap();
if t.len() == 0 { if t.is_empty() {
return Random::new(self.player).step_min(board); return Random::new(self.player).step_min(board);
} }
@ -63,12 +63,10 @@ impl SimpleMinimax {
} else { } else {
available_numbers[available_numbers.len() - 1 - offset] available_numbers[available_numbers.len() - 1 - offset]
} }
} else if val <= 0.0 {
available_numbers[offset]
} else { } else {
if val <= 0.0 { available_numbers[available_numbers.len() - 1 - offset]
available_numbers[offset]
} else {
available_numbers[available_numbers.len() - 1 - offset]
}
} }
}); });
offset += 1; offset += 1;
@ -81,9 +79,9 @@ impl SimpleMinimax {
} }
} }
impl Agent for SimpleMinimax { impl Agent for Chase {
fn name(&self) -> &'static str { fn name(&self) -> &'static str {
"Minimax" "Chase"
} }
fn player(&self) -> Player { fn player(&self) -> Player {
@ -91,13 +89,13 @@ impl Agent for SimpleMinimax {
} }
} }
impl MinimizerAgent for SimpleMinimax { impl MinimizerAgent for Chase {
fn step_min(&mut self, board: &Board) -> Result<PlayerAction> { fn step_min(&mut self, board: &Board) -> Result<PlayerAction> {
self.step(board, true) self.step(board, true)
} }
} }
impl MaximizerAgent for SimpleMinimax { impl MaximizerAgent for Chase {
fn step_max(&mut self, board: &Board) -> Result<PlayerAction> { fn step_max(&mut self, board: &Board) -> Result<PlayerAction> {
self.step(board, false) self.step(board, false)
} }

View File

@ -1,6 +1,6 @@
use anyhow::Result; use anyhow::Result;
use super::{Agent, MaximizerAgent, MinimizerAgent, Random, SimpleMinimax}; use super::{Agent, Chase, MaximizerAgent, MinimizerAgent, Random};
use crate::{ use crate::{
board::{Board, PlayerAction}, board::{Board, PlayerAction},
util::{Player, Symb}, util::{Player, Symb},
@ -94,7 +94,7 @@ impl MinimizerAgent for Diffuse {
Ok(self.step_symb(board, *symb)) Ok(self.step_symb(board, *symb))
} else { } else {
// No symbols available, play a random number // No symbols available, play a random number
SimpleMinimax::new(self.player).step_min(board) Chase::new(self.player).step_min(board)
} }
} }
} }
@ -109,7 +109,7 @@ impl MaximizerAgent for Diffuse {
Ok(self.step_symb(board, *symb)) Ok(self.step_symb(board, *symb))
} else { } else {
// No symbols available, play a random number // No symbols available, play a random number
SimpleMinimax::new(self.player).step_max(board) Chase::new(self.player).step_max(board)
} }
} }
} }

View File

@ -1,12 +1,12 @@
mod chase;
mod diffuse; mod diffuse;
mod human; mod human;
mod minimax;
mod random; mod random;
pub mod util; pub mod util;
pub use chase::Chase;
pub use diffuse::Diffuse; pub use diffuse::Diffuse;
pub use human::Human; pub use human::Human;
pub use minimax::SimpleMinimax;
pub use random::Random; pub use random::Random;
use crate::{ use crate::{

View File

@ -69,7 +69,7 @@ pub fn maximize_value(board: &Board) -> Option<Board> {
.filter(|x| !board.contains(*x)) .filter(|x| !board.contains(*x))
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let slots = free_slots_by_influence(&board)?; let slots = free_slots_by_influence(board)?;
let all_symbols = { let all_symbols = {
// We need this many from the bottom, and this many from the top. // We need this many from the bottom, and this many from the top.
@ -92,7 +92,7 @@ pub fn maximize_value(board: &Board) -> Option<Board> {
// equal-weight slots // equal-weight slots
.map(|s| { .map(|s| {
(0..s) (0..s)
.map(|_| a_iter.next().unwrap().clone()) .map(|_| *a_iter.next().unwrap())
.permutations(s) .permutations(s)
.unique() .unique()
.collect_vec() .collect_vec()

View File

@ -1,6 +1,6 @@
use anyhow::Result; use anyhow::Result;
use itertools::Itertools; use itertools::Itertools;
use std::fmt::Write; use std::fmt::{Display, Write};
use termion::color::{self, Color}; use termion::color::{self, Color};
use super::{PlayerAction, TreeElement}; use super::{PlayerAction, TreeElement};
@ -65,14 +65,12 @@ pub struct Board {
last_placed: Option<usize>, last_placed: Option<usize>,
} }
impl ToString for Board { impl Display for Board {
fn to_string(&self) -> String { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut s = String::new(); for c in self.board {
s.extend( write!(f, "{}", c.map(|s| s.get_char().unwrap()).unwrap_or('_'))?
self.board }
.map(|x| x.map(|s| s.to_char().unwrap()).unwrap_or('_')), Ok(())
);
s
} }
} }
@ -369,7 +367,7 @@ impl Board {
if c == '_' { if c == '_' {
Some(None) Some(None)
} else { } else {
Symb::from_char(c).map(|s| Some(s)) Symb::from_char(c).map(Some)
} }
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();

View File

@ -1,59 +1,79 @@
use std::fmt::Display;
use clap::{Parser, ValueEnum}; use clap::{Parser, ValueEnum};
use crate::{ use crate::{
agents::{Diffuse, Human, MaximizerAgent, MinimizerAgent, Random, SimpleMinimax}, agents::{Chase, Diffuse, Human, MaximizerAgent, MinimizerAgent, Random},
util::Player, util::Player,
}; };
#[derive(Parser, Debug)] #[derive(Parser, Debug)]
#[command(version, about)] #[command(about)]
pub struct Cli { pub struct Cli {
pub red: AgentSelector, /// The agent that controls the Blue (opponent) player
pub blue: AgentSelector, pub blue: AgentSelector,
/// The agent that controls the Red (home) player
#[arg(long, default_value = "human")]
pub red: AgentSelector,
/// If this is greater than one, repeat the game this many times and print a summary.
/// Best used with --silent.
#[arg(long, short, default_value = "0")] #[arg(long, short, default_value = "0")]
pub repeat: usize, pub repeat: usize,
/// If this is given, do not print boards.
/// Good for bulk runs with --repeat, bad for human players.
#[arg(long, short, default_value = "false")] #[arg(long, short, default_value = "false")]
pub silent: bool, pub silent: bool,
} }
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)] #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)]
pub enum AgentSelector { pub enum AgentSelector {
Random, /// A human agent. Asks for input.
Diffuse,
Minimax,
Human, Human,
/// A random agent (very easy)
Random,
/// A simple extremum-chaser (easy)
Chase,
/// A smarter extremum-chaser (medium)
Diffuse,
} }
impl AgentSelector { impl AgentSelector {
pub fn to_maxi(&self, player: Player) -> Box<dyn MaximizerAgent> { pub fn get_maximizer(&self, player: Player) -> Box<dyn MaximizerAgent> {
match self { match self {
Self::Random => Box::new(Random::new(player)), Self::Random => Box::new(Random::new(player)),
Self::Minimax => Box::new(SimpleMinimax::new(player)), Self::Chase => Box::new(Chase::new(player)),
Self::Diffuse => Box::new(Diffuse::new(player)), Self::Diffuse => Box::new(Diffuse::new(player)),
Self::Human => Box::new(Human::new(player)), Self::Human => Box::new(Human::new(player)),
} }
} }
pub fn to_mini(&self, player: Player) -> Box<dyn MinimizerAgent> { pub fn get_minimizer(&self, player: Player) -> Box<dyn MinimizerAgent> {
match self { match self {
Self::Random => Box::new(Random::new(player)), Self::Random => Box::new(Random::new(player)),
Self::Minimax => Box::new(SimpleMinimax::new(player)), Self::Chase => Box::new(Chase::new(player)),
Self::Diffuse => Box::new(Diffuse::new(player)), Self::Diffuse => Box::new(Diffuse::new(player)),
Self::Human => Box::new(Human::new(player)), Self::Human => Box::new(Human::new(player)),
} }
} }
} }
impl ToString for AgentSelector { impl Display for AgentSelector {
fn to_string(&self) -> String { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self { write!(
Self::Random => "random", f,
Self::Diffuse => "diffuse", "{}",
Self::Minimax => "minimax", match self {
Self::Human => "human", Self::Random => "random",
} Self::Diffuse => "diffuse",
.to_string() Self::Chase => "chase",
Self::Human => "human",
}
)
} }
} }

View File

@ -59,11 +59,18 @@ fn play(
let mut is_first_turn = true; let mut is_first_turn = true;
let mut is_maxi_turn = true; let mut is_maxi_turn = true;
let board_label = format!(
"{}{:6}{}",
color::Fg(color::LightBlack),
maxi.player(),
color::Fg(color::Reset)
);
while !board.is_done() { while !board.is_done() {
// Print board // Print board
println!( println!(
"\r{}{}{}{}", "\r{}{}{}{}",
" ".repeat(6), board_label,
if is_first_turn { '╓' } else { '║' }, if is_first_turn { '╓' } else { '║' },
board.prettyprint()?, board.prettyprint()?,
if is_first_turn { '╖' } else { '║' }, if is_first_turn { '╖' } else { '║' },
@ -99,8 +106,8 @@ fn play(
is_maxi_turn = !is_maxi_turn; is_maxi_turn = !is_maxi_turn;
} }
println!("\r{}{}", " ".repeat(6), board.prettyprint()?); println!("\r{}{}", board_label, board.prettyprint()?);
println!("\r{}{}", " ".repeat(6), " ".repeat(board.size())); println!("\r{}{}", board_label, " ".repeat(board.size()));
Ok(board) Ok(board)
} }
@ -112,8 +119,8 @@ fn main() -> Result<()> {
let mut blue_wins = 0f32; let mut blue_wins = 0f32;
for _ in 0..cli.repeat { for _ in 0..cli.repeat {
let mut maxi = cli.red.to_maxi(Player::Red); let mut maxi = cli.red.get_maximizer(Player::Red);
let mut mini = cli.blue.to_mini(Player::Blue); let mut mini = cli.blue.get_minimizer(Player::Blue);
let red_board = match if cli.silent { let red_board = match if cli.silent {
play_silent(&mut *maxi, &mut *mini) play_silent(&mut *maxi, &mut *mini)
} else { } else {
@ -126,8 +133,8 @@ fn main() -> Result<()> {
} }
}; };
let mut maxi = cli.blue.to_maxi(Player::Blue); let mut maxi = cli.blue.get_maximizer(Player::Blue);
let mut mini = cli.red.to_mini(Player::Red); let mut mini = cli.red.get_minimizer(Player::Red);
let blue_board = match if cli.silent { let blue_board = match if cli.silent {
play_silent(&mut *maxi, &mut *mini) play_silent(&mut *maxi, &mut *mini)
} else { } else {
@ -154,16 +161,16 @@ fn main() -> Result<()> {
println!( println!(
"Red win rate: {:.2} ({})", "Red win rate: {:.2} ({})",
red_wins / cli.repeat as f32, red_wins / cli.repeat as f32,
cli.red.to_string(), cli.red,
); );
println!( println!(
"Blue win rate: {:.2} ({}) ", "Blue win rate: {:.2} ({}) ",
blue_wins / cli.repeat as f32, blue_wins / cli.repeat as f32,
cli.blue.to_string(), cli.blue,
); );
} else { } else {
let mut maxi = cli.red.to_maxi(Player::Red); let mut maxi = cli.red.get_maximizer(Player::Red);
let mut mini = cli.blue.to_mini(Player::Blue); let mut mini = cli.blue.get_minimizer(Player::Blue);
let red_board = if cli.silent { let red_board = if cli.silent {
play_silent(&mut *maxi, &mut *mini) play_silent(&mut *maxi, &mut *mini)
} else { } else {
@ -187,8 +194,8 @@ fn main() -> Result<()> {
return Ok(()); return Ok(());
} }
let mut maxi = cli.blue.to_maxi(Player::Blue); let mut maxi = cli.blue.get_maximizer(Player::Blue);
let mut mini = cli.red.to_mini(Player::Red); let mut mini = cli.red.get_minimizer(Player::Red);
let blue_board = if cli.silent { let blue_board = if cli.silent {
play_silent(&mut *maxi, &mut *mini) play_silent(&mut *maxi, &mut *mini)
} else { } else {
@ -220,7 +227,7 @@ fn main() -> Result<()> {
println!( println!(
"\r\n{}Red ({}){} wins!", "\r\n{}Red ({}){} wins!",
color::Fg(Player::Red.color()), color::Fg(Player::Red.color()),
cli.red.to_string(), cli.red,
color::Fg(color::Reset), color::Fg(color::Reset),
); );
} }
@ -228,7 +235,7 @@ fn main() -> Result<()> {
println!( println!(
"\r\n{}Blue ({}){} wins!", "\r\n{}Blue ({}){} wins!",
color::Fg(Player::Blue.color()), color::Fg(Player::Blue.color()),
cli.blue.to_string(), cli.blue,
color::Fg(color::Reset), color::Fg(color::Reset),
); );
} }

View File

@ -69,7 +69,7 @@ impl Symb {
self == &Self::Minus self == &Self::Minus
} }
pub const fn to_char(&self) -> Option<char> { pub const fn get_char(&self) -> Option<char> {
match self { match self {
Self::Plus => Some('+'), Self::Plus => Some('+'),
Self::Minus => Some('-'), Self::Minus => Some('-'),