diff --git a/Cargo.toml b/Cargo.toml index 925d92d..3ff9ea1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,4 +6,7 @@ members = [ [profile.dev] -opt-level = 3 \ No newline at end of file +opt-level = 3 + +[profile.release] +debug = true \ No newline at end of file diff --git a/minmax-rs/src/connect4/board.rs b/minmax-rs/src/connect4/board.rs index 2b83e9c..17b33a1 100644 --- a/minmax-rs/src/connect4/board.rs +++ b/minmax-rs/src/connect4/board.rs @@ -3,9 +3,10 @@ use std::{ ops::{Index, IndexMut}, }; -use crate::{Game, Player, Score, State}; - -type Position = Option; +use crate::{ + state::{position_as_int, Position}, + Game, Player, Score, State, +}; const WIDTH: usize = 7; const HEIGTH: usize = 4; @@ -83,16 +84,19 @@ impl Connect4 { } fn check_four(&self, a: usize, b: usize, c: usize, d: usize) -> State { - self[a] - .map(|player| { - if player == self[a] && player == self[b] && player == self[c] && player == self[d] - { - State::Winner(player) - } else { - State::InProgress - } - }) - .unwrap_or(State::InProgress) + // Instead of doing a branch after each field (slow) we just check all fields. + // On each field, we get the integer value of the field (empty -> 0, X -> 1, O -> 16). + // We sum them all. If all of them are X, the sum is 4. If all of them are O, the sum is 64. + let sum = position_as_int(self[a]) + + position_as_int(self[b]) + + position_as_int(self[c]) + + position_as_int(self[d]); + + match sum { + 4 => State::Winner(Player::X), + 64 => State::Winner(Player::O), + _ => State::InProgress, + } } fn rate(&self, player: Player) -> Score { @@ -156,7 +160,9 @@ impl Game for Connect4 { fn possible_moves(&self) -> impl Iterator { let board = self.clone(); - [3, 2, 4, 1, 5, 0, 6].into_iter().filter(move |col| board[*col].is_none()) + [3, 2, 4, 1, 5, 0, 6] + .into_iter() + .filter(move |col| board[*col].is_none()) } fn result(&self) -> State { diff --git a/minmax-rs/src/lib.rs b/minmax-rs/src/lib.rs index 8c5f868..171377c 100644 --- a/minmax-rs/src/lib.rs +++ b/minmax-rs/src/lib.rs @@ -8,9 +8,9 @@ pub mod connect4; mod minmax; -pub mod tic_tac_toe; - pub mod player; +mod state; +pub mod tic_tac_toe; use std::{ fmt::{Debug, Display}, @@ -18,7 +18,7 @@ use std::{ }; pub use self::minmax::PerfectPlayer; -pub use player::{Player, State}; +pub use self::state::{Player, State}; pub trait GamePlayer { fn next_move(&mut self, board: &mut G, this_player: Player); diff --git a/minmax-rs/src/player.rs b/minmax-rs/src/player.rs index b76ddc8..1c2b470 100644 --- a/minmax-rs/src/player.rs +++ b/minmax-rs/src/player.rs @@ -1,94 +1,6 @@ -use std::{ - fmt::Display, - ops::{ControlFlow, Try}, -}; - +use crate::{Game, GamePlayer, Player}; use rand::Rng; -use crate::{Game, GamePlayer}; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Player { - X, - O, -} - -impl PartialEq> for Player { - fn eq(&self, other: &Option) -> bool { - match (self, other) { - (Player::X, Some(Player::X)) => true, - (Player::O, Some(Player::O)) => true, - _ => false, - } - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum State { - Winner(Player), - InProgress, - Draw, -} - -impl Player { - pub fn opponent(self) -> Self { - match self { - Self::X => Self::O, - Self::O => Self::X, - } - } - - pub fn from_u8(num: u8) -> Result, ()> { - Ok(match num { - 0 => Some(Player::X), - 1 => Some(Player::O), - 2 => None, - _ => return Err(()), - }) - } - - pub fn as_u8(this: Option) -> u8 { - match this { - Some(Player::X) => 0, - Some(Player::O) => 1, - None => 2, - } - } -} - -impl Display for Player { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str(match self { - Self::X => "X", - Self::O => "O", - }) - } -} - -impl std::ops::FromResidual for State { - fn from_residual(residual: ::Residual) -> Self { - residual - } -} - -impl Try for State { - // InProgress - type Output = Self; - - type Residual = Self; - - fn from_output(_: Self::Output) -> Self { - Self::InProgress - } - - fn branch(self) -> ControlFlow { - match self { - Self::InProgress => ControlFlow::Continue(self), - Self::Winner(_) | Self::Draw => ControlFlow::Break(self), - } - } -} - #[derive(Clone, Default)] pub struct GreedyPlayer; diff --git a/minmax-rs/src/state.rs b/minmax-rs/src/state.rs new file mode 100644 index 0000000..9daad49 --- /dev/null +++ b/minmax-rs/src/state.rs @@ -0,0 +1,120 @@ +use std::{ + fmt::Display, + ops::{ControlFlow, Try}, +}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Player { + X = 1, + O = 16, +} + +pub type Position = Option; + +pub fn position_as_int(pos: Position) -> u8 { + // we make sure that this is branchless by setting the repr of Player + match pos { + None => 0, + Some(Player::X) => 1, + Some(Player::O) => 16, + } +} + +impl PartialEq> for Player { + fn eq(&self, other: &Option) -> bool { + match (self, other) { + (Player::X, Some(Player::X)) => true, + (Player::O, Some(Player::O)) => true, + _ => false, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum State { + Winner(Player), + InProgress, + Draw, +} + +impl Player { + pub fn opponent(self) -> Self { + match self { + Self::X => Self::O, + Self::O => Self::X, + } + } + + pub fn from_u8(num: u8) -> Result, ()> { + Ok(match num { + 0 => Some(Player::X), + 1 => Some(Player::O), + 2 => None, + _ => return Err(()), + }) + } + + pub fn as_u8(this: Option) -> u8 { + match this { + Some(Player::X) => 0, + Some(Player::O) => 1, + None => 2, + } + } +} + +impl Display for Player { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::X => "X", + Self::O => "O", + }) + } +} + +impl std::ops::FromResidual for State { + fn from_residual(residual: ::Residual) -> Self { + residual + } +} + +impl Try for State { + // InProgress + type Output = Self; + + type Residual = Self; + + fn from_output(_: Self::Output) -> Self { + Self::InProgress + } + + fn branch(self) -> ControlFlow { + match self { + Self::InProgress => ControlFlow::Continue(self), + Self::Winner(_) | Self::Draw => ControlFlow::Break(self), + } + } +} + +#[cfg(test)] +mod tests { + use std::mem; + + use crate::Player; + + use super::Position; + + #[test] + fn position_size_and_repr() { + assert_eq!(mem::size_of::(), 1); + // this is uh maybe a tiny little not fully sound but pretty much sound + unsafe { + assert_eq!(0, mem::transmute::(Position::None)); + assert_eq!(1, mem::transmute::(Position::Some(Player::X))); + assert_eq!( + 16, + mem::transmute::(Position::Some(Player::O)) + ); + } + } +}