This commit is contained in:
nora 2022-12-05 11:05:23 +01:00
parent 6172250ff5
commit 5b0c3106c0
No known key found for this signature in database
11 changed files with 560 additions and 185 deletions

View file

@ -1,46 +1,32 @@
use std::ops::Neg;
use crate::{Game, GamePlayer, Player, State};
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Score(i32);
impl Score {
const LOST: Self = Self(i32::MIN);
const TIE: Self = Self(0);
const WON: Self = Self(i32::MAX);
pub fn new(int: i32) -> Self {
Self(int)
}
}
impl Neg for Score {
type Output = Self;
fn neg(self) -> Self::Output {
Self(-self.0)
}
}
use crate::{Game, GamePlayer, Player, Score, State};
#[derive(Clone)]
pub struct PerfectPlayer<B: Game> {
best_move: Option<B::Move>,
pub struct PerfectPlayer<G: Game> {
best_move: Option<G::Move>,
max_depth: Option<usize>,
}
impl<B: Game> Default for PerfectPlayer<B> {
impl<G: Game> Default for PerfectPlayer<G> {
fn default() -> Self {
Self::new()
}
}
impl<B: Game> PerfectPlayer<B> {
impl<G: Game> PerfectPlayer<G> {
pub fn new() -> Self {
Self { best_move: None }
Self {
best_move: None,
max_depth: G::REASONABLE_SEARCH_DEPTH,
}
}
fn minmax(&mut self, board: &mut B, player: Player, depth: usize) -> Score {
if let Some(max_depth) = B::REASONABLE_SEARCH_DEPTH && depth >= max_depth {
pub fn with_max_depth(mut self, max_depth: Option<usize>) -> Self {
self.max_depth = max_depth;
self
}
fn minmax(&mut self, board: &mut G, player: Player, depth: usize) -> Score {
if let Some(max_depth) = self.max_depth && depth >= max_depth {
return board.rate(player);
}
@ -54,7 +40,7 @@ impl<B: Game> PerfectPlayer<B> {
}
State::Draw => Score::TIE,
State::InProgress => {
let mut max_value = Score::LOST;
let mut max_value = Score::MIN;
for pos in board.possible_moves() {
board.make_move(pos, player);
@ -78,6 +64,8 @@ impl<B: Game> PerfectPlayer<B> {
impl<G: Game> GamePlayer<G> for PerfectPlayer<G> {
fn next_move(&mut self, board: &mut G, this_player: Player) {
println!("{board}");
self.best_move = None;
self.minmax(board, this_player, 0);