game_solver/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
//! `game_solver` is a library for solving games.
//!
//! If you want to read how to properly use this library,
//! [the book](https://leodog896.github.io/game-solver/book) is
//! a great place to start.

pub mod disjoint_game;
pub mod game;
pub mod player;
pub mod stats;
pub mod loopy;
// TODO: reinforcement
// #[cfg(feature = "reinforcement")]
// pub mod reinforcement;
pub mod transposition;

use core::panic;
#[cfg(feature = "rayon")]
use std::hash::BuildHasher;
use std::sync::atomic::Ordering;

use game::{upper_bound, GameState};
use player::{ImpartialPlayer, TwoPlayer};
use stats::Stats;

use crate::game::Game;
use crate::transposition::{Score, TranspositionTable};
use std::hash::Hash;
use thiserror::Error;

#[derive(Error, Debug)]
pub enum GameSolveError<T: Game> {
    #[error("could not make a move")]
    MoveError(T::MoveError),
}

/// Runs the two-player minimax variant on a zero-sum game.
/// Since it uses alpha-beta pruning, you can specify an alpha beta window.
fn negamax<T: Game<Player = impl TwoPlayer + 'static> + Eq + Hash>(
    game: &T,
    transposition_table: &mut dyn TranspositionTable<T>,
    mut alpha: isize,
    mut beta: isize,
    stats: Option<&Stats<T::Player>>,
) -> Result<isize, GameSolveError<T>> {
    if let Some(stats) = stats {
        stats.states_explored.fetch_add(1, Ordering::Relaxed);
    }

    // TODO: debug-based depth counting
    // if let Some(stats) = stats {
    //     stats.max_depth.fetch_max(depth, Ordering::Relaxed);
    // }

    // TODO(perf): if find_immediately_resolvable_game satisfies its contract,
    // we can ignore this at larger depths.
    match game.state() {
        GameState::Playable => (),
        GameState::Tie => {
            if let Some(stats) = stats {
                stats.terminal_ends.tie.fetch_add(1, Ordering::Relaxed);
            }
            return Ok(0);
        }
        GameState::Win(winning_player) => {
            // TODO: can we not duplicate this
            if let Some(stats) = stats {
                if let Ok(player) = castaway::cast!(winning_player, ImpartialPlayer) {
                    if ImpartialPlayer::from_move_count(
                        stats.original_move_count,
                        game.move_count(),
                    ) == player
                    {
                        stats.terminal_ends.winning.fetch_add(1, Ordering::Relaxed);
                    } else {
                        stats.terminal_ends.losing.fetch_add(1, Ordering::Relaxed);
                    }
                } else if stats.original_player == winning_player {
                    stats.terminal_ends.winning.fetch_add(1, Ordering::Relaxed);
                } else {
                    stats.terminal_ends.losing.fetch_add(1, Ordering::Relaxed);
                }
            }

            // if the next player is the winning player,
            // the score should be positive.
            if game.player() == winning_player {
                // we add one to make sure games that use up every move
                // aren't represented by ties.
                //
                // take the 2 heap game where each heap has one object in Nim, for example
                // player 2 will always win since 2 moves will always be used,
                // but since the upper bound is 2, 2 - 2 = 0,
                // but we reserve 0 for ties.
                return Ok(upper_bound(game) - game.move_count() as isize + 1);
            } else {
                return Ok(-(upper_bound(game) - game.move_count() as isize + 1));
            }
        }
    };

    // check if this is a winning configuration
    if let Ok(Some(board)) = game.find_immediately_resolvable_game() {
        match board.state() {
            GameState::Playable => panic!("A resolvable game should not be playable."),
            GameState::Tie => {
                if let Some(stats) = stats {
                    stats.terminal_ends.tie.fetch_add(1, Ordering::Relaxed);
                }
                return Ok(0);
            }
            GameState::Win(winning_player) => {
                if let Some(stats) = stats {
                    if let Ok(player) = castaway::cast!(winning_player, ImpartialPlayer) {
                        if ImpartialPlayer::from_move_count(
                            stats.original_move_count,
                            game.move_count(),
                        ) == player
                        {
                            stats.terminal_ends.winning.fetch_add(1, Ordering::Relaxed);
                        } else {
                            stats.terminal_ends.losing.fetch_add(1, Ordering::Relaxed);
                        }
                    } else if stats.original_player == winning_player {
                        stats.terminal_ends.winning.fetch_add(1, Ordering::Relaxed);
                    } else {
                        stats.terminal_ends.losing.fetch_add(1, Ordering::Relaxed);
                    }
                }

                if game.player().turn() == winning_player {
                    return Ok(upper_bound(&board) - board.move_count() as isize + 1);
                } else {
                    return Ok(-(upper_bound(&board) - board.move_count() as isize + 1));
                }
            }
        }
    }

    // fetch values from the transposition table
    {
        let score = transposition_table
            .get(game)
            .unwrap_or_else(|| Score::UpperBound(upper_bound(game)));

        match score {
            Score::UpperBound(max) => {
                if beta > max {
                    beta = max;
                    if alpha >= beta {
                        if let Some(stats) = stats {
                            stats.cache_hits.fetch_add(1, Ordering::Relaxed);
                        }
                        return Ok(beta);
                    }
                }
            }
            Score::LowerBound(min) => {
                if alpha < min {
                    alpha = min;
                    if alpha >= beta {
                        if let Some(stats) = stats {
                            stats.cache_hits.fetch_add(1, Ordering::Relaxed);
                        }
                        return Ok(alpha);
                    }
                }
            }
        };
    }

    // for [principal variation search](https://www.chessprogramming.org/Principal_Variation_Search)
    let mut first_child = true;

    for m in &mut game.possible_moves() {
        let mut board = game.clone();
        board
            .make_move(&m)
            .map_err(|err| GameSolveError::MoveError::<T>(err))?;

        let score = if first_child {
            -negamax(
                &board,
                transposition_table,
                -beta,
                -alpha,
                stats
            )?
        } else {
            let score = -negamax(
                &board,
                transposition_table,
                -alpha - 1,
                -alpha,
                stats
            )?;
            if score > alpha {
                -negamax(
                    &board,
                    transposition_table,
                    -beta,
                    -alpha,
                    stats
                )?
            } else {
                score
            }
        };

        // alpha-beta pruning - we can return early
        if score >= beta {
            if let Some(stats) = stats {
                stats.pruning_cutoffs.fetch_add(1, Ordering::Relaxed);
            }
            transposition_table.insert(game.clone(), Score::LowerBound(score));
            return Ok(beta);
        }

        if score > alpha {
            alpha = score;
        }

        first_child = false;
    }

    transposition_table.insert(game.clone(), Score::UpperBound(alpha));

    Ok(alpha)
}

/// Solves a game, returning the evaluated score.
///
/// The score of a position is defined by the best possible end result for the player whose turn it is.
/// In 2 player games, if a score > 0, then the player whose turn it is has a winning strategy.
/// If a score < 0, then the player whose turn it is has a losing strategy.
/// Else, the game is a draw (score = 0).
pub fn solve<T: Game<Player = impl TwoPlayer + 'static> + Eq + Hash>(
    game: &T,
    transposition_table: &mut dyn TranspositionTable<T>,
    stats: Option<&Stats<T::Player>>
) -> Result<isize, GameSolveError<T>> {
    let mut alpha = -upper_bound(game);
    let mut beta = upper_bound(game) + 1;

    // we're trying to guess the score of the board via null windows
    while alpha < beta {
        let med = alpha + (beta - alpha) / 2;

        // do a [null window search](https://www.chessprogramming.org/Null_Window)
        let evaluation = negamax(
            game,
            transposition_table,
            med,
            med + 1,
            stats
        )?;

        if evaluation <= med {
            beta = evaluation;
        } else {
            alpha = evaluation;
        }
    }

    Ok(alpha)
}

/// Utility function to get a list of the move scores of a certain game.
/// Since its evaluating the same game, you can use the same transposition table.
///
/// If you want to evaluate the score of a board as a whole, use the `solve` function.
///
/// # Returns
///
/// An iterator of tuples of the form `(move, score)`.
pub fn move_scores<'a, T: Game<Player = impl TwoPlayer + 'static> + Eq + Hash>(
    game: &'a T,
    transposition_table: &'a mut dyn TranspositionTable<T>,
    stats: Option<&'a Stats<T::Player>>
) -> impl Iterator<Item = Result<(T::Move, isize), GameSolveError<T>>> + 'a {
    game.possible_moves().map(move |m| {
        let mut board = game.clone();
        board
            .make_move(&m)
            .map_err(|err| GameSolveError::MoveError(err))?;
        // We flip the sign of the score because we want the score from the
        // perspective of the player playing the move, not the player whose turn it is.
        Ok((
            m,
            -solve(&board, transposition_table, stats)?,
        ))
    })
}

pub type CollectedMoves<T> = Vec<Result<(<T as Game>::Move, isize), GameSolveError<T>>>;

/// Parallelized version of `move_scores`. (faster by a large margin)
/// This requires the `rayon` feature to be enabled.
/// It uses rayon's parallel iterators to evaluate the scores of each move in parallel.
///
/// This also allows you to pass in your own hasher, for transposition table optimization.
///
/// # Returns
///
/// A vector of tuples of the form `(move, score)`.
#[cfg(feature = "rayon")]
pub fn par_move_scores_with_hasher<
    T: Game<Player = impl TwoPlayer + Sync + 'static> + Eq + Hash + Sync + Send + 'static,
    S,
>(
    game: &T,
    stats: Option<&Stats<T::Player>>
) -> CollectedMoves<T>
where
    T::Move: Sync + Send,
    T::MoveError: Sync + Send,
    S: BuildHasher + Default + Sync + Send + Clone + 'static,
{
    use crate::transposition::TranspositionCache;
    use rayon::prelude::*;
    use std::sync::Arc;

    // we need to collect it first as we cant parallelize an already non-parallel iterator
    let all_moves = game.possible_moves().collect::<Vec<_>>();
    let hashmap = Arc::new(TranspositionCache::<T, S>::new());

    all_moves
        .par_iter()
        .map(move |m| {
            let mut board = game.clone();
            board
                .make_move(m)
                .map_err(|err| GameSolveError::MoveError::<T>(err))?;
            // We flip the sign of the score because we want the score from the
            // perspective of the player pla`ying the move, not the player whose turn it is.
            let mut map = Arc::clone(&hashmap);
            Ok((
                (*m).clone(),
                -solve(&board, &mut map, stats)?,
            ))
        })
        .collect::<Vec<_>>()
}

/// Parallelized version of `move_scores`. (faster by a large margin)
/// This requires the `rayon` feature to be enabled.
/// It uses rayon's parallel iterators to evaluate the scores of each move in parallel.
///
/// By default, this uses the cryptograpphically unsecure `XxHash64` hasher.
/// If you want to use your own hasher, use [`par_move_scores_with_hasher`].
///
/// # Returns
///
/// A vector of tuples of the form `(move, score)`.
#[cfg(feature = "rayon")]
pub fn par_move_scores<
    T: Game<Player = impl TwoPlayer + Sync + 'static> + Eq + Hash + Sync + Send + 'static,
>(
    game: &T,
    stats: Option<&Stats<T::Player>>
) -> CollectedMoves<T>
where
    T::Move: Sync + Send,
    T::MoveError: Sync + Send,
{
    if cfg!(feature = "xxhash") {
        use twox_hash::RandomXxHashBuilder64;
        par_move_scores_with_hasher::<T, RandomXxHashBuilder64>(game, stats)
    } else {
        use std::collections::hash_map::RandomState;
        par_move_scores_with_hasher::<T, RandomState>(game, stats)
    }
}