optimize check_four

This commit is contained in:
nora 2023-01-16 09:40:49 +01:00
parent 468532bb62
commit 91e3573e26
5 changed files with 148 additions and 107 deletions

View file

@ -7,3 +7,6 @@ members = [
[profile.dev]
opt-level = 3
[profile.release]
debug = true

View file

@ -3,9 +3,10 @@ use std::{
ops::{Index, IndexMut},
};
use crate::{Game, Player, Score, State};
type Position = Option<Player>;
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<Item = Self::Move> {
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 {

View file

@ -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<G: ?Sized + Game> {
fn next_move(&mut self, board: &mut G, this_player: Player);

View file

@ -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<Option<Player>> for Player {
fn eq(&self, other: &Option<Player>) -> 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<Option<Self>, ()> {
Ok(match num {
0 => Some(Player::X),
1 => Some(Player::O),
2 => None,
_ => return Err(()),
})
}
pub fn as_u8(this: Option<Player>) -> 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: <Self as Try>::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<Self::Residual, Self::Output> {
match self {
Self::InProgress => ControlFlow::Continue(self),
Self::Winner(_) | Self::Draw => ControlFlow::Break(self),
}
}
}
#[derive(Clone, Default)]
pub struct GreedyPlayer;

120
minmax-rs/src/state.rs Normal file
View file

@ -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<Player>;
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<Option<Player>> for Player {
fn eq(&self, other: &Option<Player>) -> 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<Option<Self>, ()> {
Ok(match num {
0 => Some(Player::X),
1 => Some(Player::O),
2 => None,
_ => return Err(()),
})
}
pub fn as_u8(this: Option<Player>) -> 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: <Self as Try>::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<Self::Residual, Self::Output> {
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::<Position>(), 1);
// this is uh maybe a tiny little not fully sound but pretty much sound
unsafe {
assert_eq!(0, mem::transmute::<Position, u8>(Position::None));
assert_eq!(1, mem::transmute::<Position, u8>(Position::Some(Player::X)));
assert_eq!(
16,
mem::transmute::<Position, u8>(Position::Some(Player::O))
);
}
}
}