Compare commits
No commits in common. "786e70fe9adbe439be35356c919963df60e41b25" and "89aba4f9304fd9fbe6a87c64027f3729b34fc17c" have entirely different histories.
786e70fe9a
...
89aba4f930
|
@ -120,31 +120,6 @@ version = "1.0.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7"
|
checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "crossbeam-deque"
|
|
||||||
version = "0.8.5"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "613f8cc01fe9cf1a3eb3d7f488fd2fa8388403e97039e2f73692932e291a770d"
|
|
||||||
dependencies = [
|
|
||||||
"crossbeam-epoch",
|
|
||||||
"crossbeam-utils",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "crossbeam-epoch"
|
|
||||||
version = "0.9.18"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e"
|
|
||||||
dependencies = [
|
|
||||||
"crossbeam-utils",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "crossbeam-utils"
|
|
||||||
version = "0.8.19"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "248e3bacc7dc6baa3b21e405ee045c3047101a49145e7e9eca583ab4c2ca5345"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "either"
|
name = "either"
|
||||||
version = "1.10.0"
|
version = "1.10.0"
|
||||||
|
@ -202,7 +177,6 @@ dependencies = [
|
||||||
"clap",
|
"clap",
|
||||||
"itertools",
|
"itertools",
|
||||||
"rand",
|
"rand",
|
||||||
"rayon",
|
|
||||||
"termion",
|
"termion",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
@ -266,26 +240,6 @@ dependencies = [
|
||||||
"getrandom",
|
"getrandom",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "rayon"
|
|
||||||
version = "1.9.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "e4963ed1bc86e4f3ee217022bd855b297cef07fb9eac5dfa1f788b220b49b3bd"
|
|
||||||
dependencies = [
|
|
||||||
"either",
|
|
||||||
"rayon-core",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "rayon-core"
|
|
||||||
version = "1.12.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "1465873a3dfdaa8ae7cb14b4383657caab0b3e8a0aa9ae8e04b044854c8dfce2"
|
|
||||||
dependencies = [
|
|
||||||
"crossbeam-deque",
|
|
||||||
"crossbeam-utils",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "redox_syscall"
|
name = "redox_syscall"
|
||||||
version = "0.4.1"
|
version = "0.4.1"
|
||||||
|
|
|
@ -8,5 +8,4 @@ anyhow = "1.0.80"
|
||||||
clap = { version = "4.5.1", features = ["derive"] }
|
clap = { version = "4.5.1", features = ["derive"] }
|
||||||
itertools = "0.12.1"
|
itertools = "0.12.1"
|
||||||
rand = "0.8.5"
|
rand = "0.8.5"
|
||||||
rayon = "1.9.0"
|
|
||||||
termion = "3.0.0"
|
termion = "3.0.0"
|
||||||
|
|
12
README.md
12
README.md
|
@ -22,15 +22,7 @@ As always, run this project with `cargo run`. The app takes one argument by defa
|
||||||
- `random`: Play against a random agent (very easy)
|
- `random`: Play against a random agent (very easy)
|
||||||
- `chase`: Play against a simple extremum-chasing agent (easy)
|
- `chase`: Play against a simple extremum-chasing agent (easy)
|
||||||
- `diffuse`: Play against a slightly more intellegent extremum chaser (medium)
|
- `diffuse`: Play against a slightly more intellegent extremum chaser (medium)
|
||||||
- `brutus`: Play against a simple brute-force agent (hard)
|
|
||||||
|
|
||||||
For example, `cargo run -- random` will start a game against a random player. Use your arrow keys and space bar to play.
|
For example, `cargo run -- random` will play a game against a random player. Use your arrow keys and space bar to play the game.
|
||||||
|
|
||||||
Additional options are available, see `cargo run -- --help`.
|
Additional options are available, see `cargo run -- --help`.
|
||||||
|
|
||||||
Win rates against random are as follows:
|
|
||||||
- `human`: ~100%
|
|
||||||
- `random`: ~50%
|
|
||||||
- `chase`: ~70%
|
|
||||||
- `diffuse`: ~76%
|
|
||||||
- `brutus`: ~90%
|
|
|
@ -1,142 +0,0 @@
|
||||||
use std::{cmp::Ordering, iter};
|
|
||||||
|
|
||||||
use anyhow::Result;
|
|
||||||
use itertools::Itertools;
|
|
||||||
use rand::{seq::SliceRandom, thread_rng};
|
|
||||||
use rayon::iter::{ParallelBridge, ParallelIterator};
|
|
||||||
|
|
||||||
use super::{Agent, Chase, MaximizerAgent, MinimizerAgent};
|
|
||||||
use crate::{
|
|
||||||
agents::{util::best_board_noop, Diffuse},
|
|
||||||
board::{Board, PlayerAction},
|
|
||||||
util::{Player, Symb},
|
|
||||||
};
|
|
||||||
|
|
||||||
pub struct Brutus {
|
|
||||||
player: Player,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Brutus {
|
|
||||||
pub fn new(player: Player) -> Self {
|
|
||||||
Self { player }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn step(&mut self, board: &Board, minimize: bool) -> Result<PlayerAction> {
|
|
||||||
let symbols = [Symb::Minus, Symb::Times, Symb::Plus, Symb::Div]
|
|
||||||
.into_iter()
|
|
||||||
.filter(|x| !board.contains(*x))
|
|
||||||
.collect_vec();
|
|
||||||
|
|
||||||
if symbols.is_empty() {
|
|
||||||
return if minimize {
|
|
||||||
Chase::new(self.player).step_min(board)
|
|
||||||
} else {
|
|
||||||
Chase::new(self.player).step_max(board)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Number of free slots
|
|
||||||
let n_free = board.get_board().iter().filter(|x| x.is_none()).count();
|
|
||||||
|
|
||||||
// Number of slots we need to fill with numbers
|
|
||||||
// Add one if we have two or fewer symbols available, so that we can
|
|
||||||
// account for one unused symbol while keeping a reasonable runtime
|
|
||||||
let n_fill = n_free - symbols.len() + if symbols.len() <= 2 { 1 } else { 0 };
|
|
||||||
|
|
||||||
let mut items = iter::repeat(None)
|
|
||||||
.take(n_fill)
|
|
||||||
.chain(symbols.iter().map(|x| Some(x.clone())))
|
|
||||||
.permutations(n_free)
|
|
||||||
.unique()
|
|
||||||
.par_bridge()
|
|
||||||
.filter_map(move |x| {
|
|
||||||
let mut tmp_board = board.clone();
|
|
||||||
|
|
||||||
for (i, s) in x.iter().enumerate() {
|
|
||||||
if let Some(s) = s {
|
|
||||||
let pos = board.ith_empty_slot(i).unwrap();
|
|
||||||
if !tmp_board.can_play(&PlayerAction { symb: *s, pos }) {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
tmp_board.get_board_mut()[pos] = Some(*s);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let min = best_board_noop(&tmp_board, true);
|
|
||||||
let max = best_board_noop(&tmp_board, false);
|
|
||||||
if min.is_none() || max.is_none() {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
let v_min = min.unwrap().evaluate().unwrap();
|
|
||||||
let v_max = max.unwrap().evaluate().unwrap();
|
|
||||||
let v = v_min + v_max / 2.0;
|
|
||||||
|
|
||||||
Some((tmp_board, v))
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
|
|
||||||
if minimize {
|
|
||||||
// Sort from smallest to biggest midpoint
|
|
||||||
items.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(Ordering::Equal));
|
|
||||||
} else {
|
|
||||||
items.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(Ordering::Equal));
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: why can `items` be empty?
|
|
||||||
// We shouldn't need this escape hatch
|
|
||||||
if items.is_empty() {
|
|
||||||
return if minimize {
|
|
||||||
Diffuse::new(self.player).step_min(board)
|
|
||||||
} else {
|
|
||||||
Diffuse::new(self.player).step_max(board)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
let (t, _) = items.first().unwrap();
|
|
||||||
|
|
||||||
let mut symbols = symbols.clone();
|
|
||||||
symbols.shuffle(&mut thread_rng());
|
|
||||||
|
|
||||||
// Place a random unused symbol
|
|
||||||
for target_s in symbols {
|
|
||||||
for (i, s) in t.get_board().iter().enumerate() {
|
|
||||||
if let Some(s) = s {
|
|
||||||
if board.get_board()[i].is_none() && target_s == *s {
|
|
||||||
return Ok(PlayerAction { pos: i, symb: *s });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Final escape hatch, if we didn't decide to place any symbols
|
|
||||||
// (which is possible, since we add one to free_spots above!)
|
|
||||||
if minimize {
|
|
||||||
Chase::new(self.player).step_min(board)
|
|
||||||
} else {
|
|
||||||
Chase::new(self.player).step_max(board)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Agent for Brutus {
|
|
||||||
fn name(&self) -> &'static str {
|
|
||||||
"Brutus"
|
|
||||||
}
|
|
||||||
|
|
||||||
fn player(&self) -> Player {
|
|
||||||
self.player
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl MinimizerAgent for Brutus {
|
|
||||||
fn step_min(&mut self, board: &Board) -> Result<PlayerAction> {
|
|
||||||
self.step(board, true)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl MaximizerAgent for Brutus {
|
|
||||||
fn step_max(&mut self, board: &Board) -> Result<PlayerAction> {
|
|
||||||
self.step(board, false)
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,5 +1,4 @@
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use rand::{seq::SliceRandom, thread_rng};
|
|
||||||
|
|
||||||
use super::{Agent, Chase, MaximizerAgent, MinimizerAgent, Random};
|
use super::{Agent, Chase, MaximizerAgent, MinimizerAgent, Random};
|
||||||
use crate::{
|
use crate::{
|
||||||
|
@ -10,7 +9,6 @@ use crate::{
|
||||||
/// A simple "operator diffusion" MINIMIZER agent.
|
/// A simple "operator diffusion" MINIMIZER agent.
|
||||||
///
|
///
|
||||||
/// Tries to keep operators as far apart as possible, denying large numbers.
|
/// Tries to keep operators as far apart as possible, denying large numbers.
|
||||||
/// Places numbers using the same algorithm as chase.
|
|
||||||
pub struct Diffuse {
|
pub struct Diffuse {
|
||||||
player: Player,
|
player: Player,
|
||||||
}
|
}
|
||||||
|
@ -88,9 +86,9 @@ impl Agent for Diffuse {
|
||||||
|
|
||||||
impl MinimizerAgent for Diffuse {
|
impl MinimizerAgent for Diffuse {
|
||||||
fn step_min(&mut self, board: &Board) -> Result<PlayerAction> {
|
fn step_min(&mut self, board: &Board) -> Result<PlayerAction> {
|
||||||
let mut x = [Symb::Minus, Symb::Times, Symb::Plus, Symb::Div];
|
let symb = [Symb::Minus, Symb::Times, Symb::Plus, Symb::Div]
|
||||||
x.shuffle(&mut thread_rng());
|
.iter()
|
||||||
let symb = x.iter().find(|x| !board.contains(**x));
|
.find(|x| !board.contains(**x));
|
||||||
|
|
||||||
if let Some(symb) = symb {
|
if let Some(symb) = symb {
|
||||||
Ok(self.step_symb(board, *symb))
|
Ok(self.step_symb(board, *symb))
|
||||||
|
@ -103,9 +101,9 @@ impl MinimizerAgent for Diffuse {
|
||||||
|
|
||||||
impl MaximizerAgent for Diffuse {
|
impl MaximizerAgent for Diffuse {
|
||||||
fn step_max(&mut self, board: &Board) -> Result<PlayerAction> {
|
fn step_max(&mut self, board: &Board) -> Result<PlayerAction> {
|
||||||
let mut x = [Symb::Minus, Symb::Times, Symb::Plus, Symb::Div];
|
let symb = [Symb::Minus, Symb::Times, Symb::Plus, Symb::Div]
|
||||||
x.shuffle(&mut thread_rng());
|
.iter()
|
||||||
let symb = x.iter().find(|x| !board.contains(**x));
|
.find(|x| !board.contains(**x));
|
||||||
|
|
||||||
if let Some(symb) = symb {
|
if let Some(symb) = symb {
|
||||||
Ok(self.step_symb(board, *symb))
|
Ok(self.step_symb(board, *symb))
|
||||||
|
|
|
@ -195,7 +195,7 @@ impl Human {
|
||||||
|
|
||||||
impl Agent for Human {
|
impl Agent for Human {
|
||||||
fn name(&self) -> &'static str {
|
fn name(&self) -> &'static str {
|
||||||
"Human"
|
"Player"
|
||||||
}
|
}
|
||||||
|
|
||||||
fn player(&self) -> Player {
|
fn player(&self) -> Player {
|
||||||
|
|
|
@ -1,11 +1,9 @@
|
||||||
mod brutus;
|
|
||||||
mod chase;
|
mod chase;
|
||||||
mod diffuse;
|
mod diffuse;
|
||||||
mod human;
|
mod human;
|
||||||
mod random;
|
mod random;
|
||||||
pub mod util;
|
pub mod util;
|
||||||
|
|
||||||
pub use brutus::Brutus;
|
|
||||||
pub use chase::Chase;
|
pub use chase::Chase;
|
||||||
pub use diffuse::Diffuse;
|
pub use diffuse::Diffuse;
|
||||||
pub use human::Human;
|
pub use human::Human;
|
||||||
|
|
|
@ -1,10 +1,10 @@
|
||||||
use itertools::Itertools;
|
use itertools::Itertools;
|
||||||
use std::{mem::swap, num::NonZeroU8};
|
use std::num::NonZeroU8;
|
||||||
|
|
||||||
use crate::{board::Board, util::Symb};
|
use crate::{board::Board, util::Symb};
|
||||||
|
|
||||||
/// Returns an iterator of (idx, coords, char_idx, f32) for each empty slot in the listed partials.
|
/// Returns an iterator of (sort, coords, char_idx, f32) for each empty slot in the listed partials.
|
||||||
/// - idx is the index of this slot in the board string.
|
/// - sort is the index of this slot.
|
||||||
/// - coords are the coordinate of this slot's partial
|
/// - coords are the coordinate of this slot's partial
|
||||||
/// - char_idx is the index of this slot in its partial
|
/// - char_idx is the index of this slot in its partial
|
||||||
/// - f32 is the influence of this slot
|
/// - f32 is the influence of this slot
|
||||||
|
@ -51,12 +51,16 @@ pub fn free_slots_by_influence(board: &Board) -> Option<Vec<(usize, f32)>> {
|
||||||
Some(slots)
|
Some(slots)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Find the minimum or maximum possible value of the given board,
|
/// Find the maximum possible value of the given board
|
||||||
/// without adding any operations. Returns None if we couldn't find
|
#[allow(dead_code)]
|
||||||
/// a best board.
|
pub fn maximize_value(board: &Board) -> Option<Board> {
|
||||||
pub fn best_board_noop(board: &Board, minimize: bool) -> Option<Board> {
|
|
||||||
let n_free = board.get_board().iter().filter(|x| x.is_none()).count();
|
let n_free = board.get_board().iter().filter(|x| x.is_none()).count();
|
||||||
|
|
||||||
|
// Assume we have 10 or fewer available slots
|
||||||
|
if n_free >= 10 {
|
||||||
|
panic!()
|
||||||
|
}
|
||||||
|
|
||||||
let available_numbers = (0..=9)
|
let available_numbers = (0..=9)
|
||||||
.map(|x| match x {
|
.map(|x| match x {
|
||||||
0 => Symb::Zero,
|
0 => Symb::Zero,
|
||||||
|
@ -65,36 +69,19 @@ pub fn best_board_noop(board: &Board, minimize: bool) -> Option<Board> {
|
||||||
.filter(|x| !board.contains(*x))
|
.filter(|x| !board.contains(*x))
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
if n_free > available_numbers.len() {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
let slots = free_slots_by_influence(board)?;
|
let slots = free_slots_by_influence(board)?;
|
||||||
|
|
||||||
let all_symbols = {
|
let all_symbols = {
|
||||||
let mut a = {
|
// We need this many from the bottom, and this many from the top.
|
||||||
// Number of slots we want to minimize
|
let neg_count = slots.iter().filter(|(_, x)| *x <= 0.0).count();
|
||||||
let mut neg_count = slots.iter().filter(|(_, x)| *x <= 0.0).count();
|
let pos_count = slots.iter().filter(|(_, x)| *x > 0.0).count();
|
||||||
// Number of slots we want to maximize
|
|
||||||
let mut pos_count = slots.iter().filter(|(_, x)| *x > 0.0).count();
|
|
||||||
|
|
||||||
if minimize {
|
let mut a_iter = available_numbers
|
||||||
swap(&mut neg_count, &mut pos_count);
|
.iter()
|
||||||
}
|
.take(neg_count)
|
||||||
|
.chain(available_numbers.iter().rev().take(pos_count).rev());
|
||||||
|
|
||||||
available_numbers
|
let mut g = slots
|
||||||
.iter()
|
|
||||||
.take(neg_count)
|
|
||||||
.chain(available_numbers.iter().rev().take(pos_count).rev())
|
|
||||||
.collect_vec()
|
|
||||||
};
|
|
||||||
|
|
||||||
if !minimize {
|
|
||||||
a.reverse();
|
|
||||||
}
|
|
||||||
let mut a_iter = a.into_iter();
|
|
||||||
|
|
||||||
slots
|
|
||||||
// Group slots with equal weights
|
// Group slots with equal weights
|
||||||
// and count the number of elements in each group
|
// and count the number of elements in each group
|
||||||
.iter()
|
.iter()
|
||||||
|
@ -114,32 +101,37 @@ pub fn best_board_noop(board: &Board, minimize: bool) -> Option<Board> {
|
||||||
// of this set of sets
|
// of this set of sets
|
||||||
.multi_cartesian_product()
|
.multi_cartesian_product()
|
||||||
.map(|x| x.iter().flatten().cloned().collect_vec())
|
.map(|x| x.iter().flatten().cloned().collect_vec())
|
||||||
// Finally, attach the coordinate of each slot to each symbol
|
.map(|v| slots.iter().zip(v).collect_vec())
|
||||||
.map(|v| slots.iter().map(|x| x.0).zip(v).collect_vec())
|
.collect_vec();
|
||||||
.collect_vec()
|
|
||||||
|
// Sort these vectors so the order of values
|
||||||
|
// matches the order of empty slots
|
||||||
|
g.iter_mut()
|
||||||
|
.for_each(|v| v.sort_by(|(a, _), (b, _)| b.0.partial_cmp(&a.0).unwrap()));
|
||||||
|
g.into_iter()
|
||||||
|
.map(|v| v.into_iter().map(|(_, s)| s).collect_vec())
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut best_board = None;
|
let mut best_board = None;
|
||||||
let mut best_value = None;
|
let mut best_value = None;
|
||||||
for i_iter in all_symbols {
|
for i in all_symbols {
|
||||||
let mut tmp_board = board.clone();
|
let mut i_iter = i.iter();
|
||||||
for (i, s) in i_iter {
|
let filled = Board::from_board(board.get_board().map(|x| match x {
|
||||||
tmp_board.get_board_mut()[i] = Some(s);
|
None => i_iter.next().cloned(),
|
||||||
}
|
_ => x,
|
||||||
|
}));
|
||||||
|
|
||||||
let val = tmp_board.evaluate();
|
let val = filled.evaluate();
|
||||||
|
|
||||||
if let Some(val) = val {
|
if let Some(val) = val {
|
||||||
if minimize {
|
if let Some(best) = best_value {
|
||||||
if best_value.is_none() || val < best_value.unwrap() {
|
if val > best {
|
||||||
best_value = Some(val);
|
best_value = Some(val);
|
||||||
best_board = Some(tmp_board)
|
best_board = Some(filled)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if best_value.is_none() || val > best_value.unwrap() {
|
best_value = Some(val);
|
||||||
best_value = Some(val);
|
best_board = Some(filled)
|
||||||
best_board = Some(tmp_board)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use itertools::Itertools;
|
use itertools::Itertools;
|
||||||
use std::fmt::{Debug, Display, Write};
|
use std::fmt::{Display, Write};
|
||||||
use termion::color::{self, Color};
|
use termion::color::{self, Color};
|
||||||
|
|
||||||
use super::{PlayerAction, TreeElement};
|
use super::{PlayerAction, TreeElement};
|
||||||
|
@ -74,12 +74,6 @@ impl Display for Board {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Debug for Board {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
Display::fmt(&self, f)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
impl Board {
|
impl Board {
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
|
@ -99,24 +93,6 @@ impl Board {
|
||||||
&mut self.board
|
&mut self.board
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the index of the ith empty slot
|
|
||||||
pub fn ith_empty_slot(&self, mut idx: usize) -> Option<usize> {
|
|
||||||
for (i, c) in self.board.iter().enumerate() {
|
|
||||||
if c.is_none() {
|
|
||||||
if idx == 0 {
|
|
||||||
return Some(i);
|
|
||||||
}
|
|
||||||
idx -= 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if idx == 0 {
|
|
||||||
Some(self.board.len() - 1)
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn is_done(&self) -> bool {
|
pub fn is_done(&self) -> bool {
|
||||||
self.free_spots == 0
|
self.free_spots == 0
|
||||||
}
|
}
|
||||||
|
|
14
src/cli.rs
14
src/cli.rs
|
@ -3,7 +3,7 @@ use std::fmt::Display;
|
||||||
use clap::{Parser, ValueEnum};
|
use clap::{Parser, ValueEnum};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
agents::{Brutus, Chase, Diffuse, Human, MaximizerAgent, MinimizerAgent, Random},
|
agents::{Chase, Diffuse, Human, MaximizerAgent, MinimizerAgent, Random},
|
||||||
util::Player,
|
util::Player,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -18,8 +18,14 @@ pub struct Cli {
|
||||||
pub red: AgentSelector,
|
pub red: AgentSelector,
|
||||||
|
|
||||||
/// If this is greater than one, repeat the game this many times and print a summary.
|
/// 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")]
|
||||||
|
pub silent: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)]
|
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)]
|
||||||
|
@ -35,9 +41,6 @@ pub enum AgentSelector {
|
||||||
|
|
||||||
/// A smarter extremum-chaser (medium)
|
/// A smarter extremum-chaser (medium)
|
||||||
Diffuse,
|
Diffuse,
|
||||||
|
|
||||||
/// A very smart brute-force agent (hard)
|
|
||||||
Brutus,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AgentSelector {
|
impl AgentSelector {
|
||||||
|
@ -46,7 +49,6 @@ impl AgentSelector {
|
||||||
Self::Random => Box::new(Random::new(player)),
|
Self::Random => Box::new(Random::new(player)),
|
||||||
Self::Chase => Box::new(Chase::new(player)),
|
Self::Chase => Box::new(Chase::new(player)),
|
||||||
Self::Diffuse => Box::new(Diffuse::new(player)),
|
Self::Diffuse => Box::new(Diffuse::new(player)),
|
||||||
Self::Brutus => Box::new(Brutus::new(player)),
|
|
||||||
Self::Human => Box::new(Human::new(player)),
|
Self::Human => Box::new(Human::new(player)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -56,7 +58,6 @@ impl AgentSelector {
|
||||||
Self::Random => Box::new(Random::new(player)),
|
Self::Random => Box::new(Random::new(player)),
|
||||||
Self::Chase => Box::new(Chase::new(player)),
|
Self::Chase => Box::new(Chase::new(player)),
|
||||||
Self::Diffuse => Box::new(Diffuse::new(player)),
|
Self::Diffuse => Box::new(Diffuse::new(player)),
|
||||||
Self::Brutus => Box::new(Brutus::new(player)),
|
|
||||||
Self::Human => Box::new(Human::new(player)),
|
Self::Human => Box::new(Human::new(player)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -70,7 +71,6 @@ impl Display for AgentSelector {
|
||||||
match self {
|
match self {
|
||||||
Self::Random => "random",
|
Self::Random => "random",
|
||||||
Self::Diffuse => "diffuse",
|
Self::Diffuse => "diffuse",
|
||||||
Self::Brutus => "brutus",
|
|
||||||
Self::Chase => "chase",
|
Self::Chase => "chase",
|
||||||
Self::Human => "human",
|
Self::Human => "human",
|
||||||
}
|
}
|
||||||
|
|
102
src/main.rs
102
src/main.rs
|
@ -1,11 +1,7 @@
|
||||||
use std::{
|
use std::cmp::Ordering;
|
||||||
cmp::Ordering,
|
|
||||||
io::{stdout, Write},
|
|
||||||
};
|
|
||||||
|
|
||||||
use anyhow::{bail, Result};
|
use anyhow::{bail, Result};
|
||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use rayon::iter::{IntoParallelIterator, ParallelIterator};
|
|
||||||
use termion::color::{self};
|
use termion::color::{self};
|
||||||
|
|
||||||
mod agents;
|
mod agents;
|
||||||
|
@ -81,9 +77,6 @@ fn play(
|
||||||
);
|
);
|
||||||
is_first_turn = false;
|
is_first_turn = false;
|
||||||
|
|
||||||
print!("Thinking...");
|
|
||||||
stdout().flush()?;
|
|
||||||
|
|
||||||
// Take action
|
// Take action
|
||||||
let action = if is_maxi_turn {
|
let action = if is_maxi_turn {
|
||||||
maxi.step_max(&board)?
|
maxi.step_max(&board)?
|
||||||
|
@ -121,65 +114,68 @@ fn play(
|
||||||
fn main() -> Result<()> {
|
fn main() -> Result<()> {
|
||||||
let cli = cli::Cli::parse();
|
let cli = cli::Cli::parse();
|
||||||
|
|
||||||
rayon::ThreadPoolBuilder::new()
|
|
||||||
.num_threads(8)
|
|
||||||
.build_global()
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
if cli.repeat > 1 {
|
if cli.repeat > 1 {
|
||||||
let x = (0..cli.repeat)
|
let mut red_wins = 0f32;
|
||||||
.into_par_iter()
|
let mut blue_wins = 0f32;
|
||||||
.filter_map(|_| {
|
|
||||||
let mut maxi = cli.red.get_maximizer(Player::Red);
|
|
||||||
let mut mini = cli.blue.get_minimizer(Player::Blue);
|
|
||||||
let red_board = match play_silent(&mut *maxi, &mut *mini) {
|
|
||||||
Ok(x) => x,
|
|
||||||
Err(e) => {
|
|
||||||
println!("Error: {e}");
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut maxi = cli.blue.get_maximizer(Player::Blue);
|
for _ in 0..cli.repeat {
|
||||||
let mut mini = cli.red.get_minimizer(Player::Red);
|
let mut maxi = cli.red.get_maximizer(Player::Red);
|
||||||
let blue_board = match play_silent(&mut *maxi, &mut *mini) {
|
let mut mini = cli.blue.get_minimizer(Player::Blue);
|
||||||
Ok(x) => x,
|
let red_board = match if cli.silent {
|
||||||
Err(e) => {
|
play_silent(&mut *maxi, &mut *mini)
|
||||||
println!("Error: {e}");
|
} else {
|
||||||
return None;
|
play(&mut *maxi, &mut *mini)
|
||||||
}
|
} {
|
||||||
};
|
Ok(x) => x,
|
||||||
|
Err(e) => {
|
||||||
match red_board.evaluate().partial_cmp(&blue_board.evaluate()) {
|
println!("Error: {e}");
|
||||||
Some(Ordering::Equal) => None,
|
continue;
|
||||||
Some(Ordering::Greater) => Some(Player::Red),
|
|
||||||
Some(Ordering::Less) => Some(Player::Blue),
|
|
||||||
None => {
|
|
||||||
println!("Error");
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
};
|
||||||
.collect::<Vec<_>>();
|
|
||||||
|
|
||||||
let red_wins = x.iter().filter(|x| **x == Player::Red).count();
|
let mut maxi = cli.blue.get_maximizer(Player::Blue);
|
||||||
let blue_wins = x.iter().filter(|x| **x == Player::Blue).count();
|
let mut mini = cli.red.get_minimizer(Player::Red);
|
||||||
|
let blue_board = match if cli.silent {
|
||||||
|
play_silent(&mut *maxi, &mut *mini)
|
||||||
|
} else {
|
||||||
|
play(&mut *maxi, &mut *mini)
|
||||||
|
} {
|
||||||
|
Ok(x) => x,
|
||||||
|
Err(e) => {
|
||||||
|
println!("Error: {e}");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
match red_board.evaluate().partial_cmp(&blue_board.evaluate()) {
|
||||||
|
Some(Ordering::Equal) => {}
|
||||||
|
Some(Ordering::Greater) => red_wins += 1.0,
|
||||||
|
Some(Ordering::Less) => blue_wins += 1.0,
|
||||||
|
None => {
|
||||||
|
println!("Error");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
println!("Played {} rounds\n", cli.repeat);
|
println!("Played {} rounds\n", cli.repeat);
|
||||||
println!(
|
println!(
|
||||||
"Red win rate: {:.2} ({})",
|
"Red win rate: {:.2} ({})",
|
||||||
red_wins as f32 / cli.repeat as f32,
|
red_wins / cli.repeat as f32,
|
||||||
cli.red,
|
cli.red,
|
||||||
);
|
);
|
||||||
println!(
|
println!(
|
||||||
"Blue win rate: {:.2} ({}) ",
|
"Blue win rate: {:.2} ({}) ",
|
||||||
blue_wins as f32 / cli.repeat as f32,
|
blue_wins / cli.repeat as f32,
|
||||||
cli.blue,
|
cli.blue,
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
let mut maxi = cli.red.get_maximizer(Player::Red);
|
let mut maxi = cli.red.get_maximizer(Player::Red);
|
||||||
let mut mini = cli.blue.get_minimizer(Player::Blue);
|
let mut mini = cli.blue.get_minimizer(Player::Blue);
|
||||||
let red_board = play(&mut *maxi, &mut *mini)?;
|
let red_board = if cli.silent {
|
||||||
|
play_silent(&mut *maxi, &mut *mini)
|
||||||
|
} else {
|
||||||
|
play(&mut *maxi, &mut *mini)
|
||||||
|
}?;
|
||||||
|
|
||||||
if red_board.is_done() {
|
if red_board.is_done() {
|
||||||
println!(
|
println!(
|
||||||
|
@ -200,7 +196,11 @@ fn main() -> Result<()> {
|
||||||
|
|
||||||
let mut maxi = cli.blue.get_maximizer(Player::Blue);
|
let mut maxi = cli.blue.get_maximizer(Player::Blue);
|
||||||
let mut mini = cli.red.get_minimizer(Player::Red);
|
let mut mini = cli.red.get_minimizer(Player::Red);
|
||||||
let blue_board = play(&mut *maxi, &mut *mini)?;
|
let blue_board = if cli.silent {
|
||||||
|
play_silent(&mut *maxi, &mut *mini)
|
||||||
|
} else {
|
||||||
|
play(&mut *maxi, &mut *mini)
|
||||||
|
}?;
|
||||||
|
|
||||||
if blue_board.is_done() {
|
if blue_board.is_done() {
|
||||||
println!(
|
println!(
|
||||||
|
|
Loading…
Reference in New Issue