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
//! The [`Game`] trait the searches run on, and the [`Side`] that moves in a position.
use Vec;
use crate::;
/// The player who chooses the move in a position.
/// A two-player, zero-sum game as seen by the searches.
///
/// The side to move is a property of the position, not of the move count: one side may move
/// several times in a row, as in games where combatants act by speed. Every score is from
/// [`Side::Max`]'s point of view, whoever is to move.
///
/// A position without moves ends the game; [`Game::evaluate`] then gives its final score.
///
/// # Examples
///
/// ```
/// use game_tree_search::{Game, Side, minimax};
///
/// /// One-pile Nim: take one or two stones; whoever cannot move has lost.
/// struct Nim;
///
/// impl Game for Nim {
/// /// The stones left and the side to move.
/// type Position = (u32, Side);
/// type Move = u32;
/// type Score = i32;
///
/// fn side_to_move(&self, &(_, side): &Self::Position) -> Side {
/// side
/// }
///
/// fn moves(&self, &(stones, _): &Self::Position, moves: &mut Vec<u32>) {
/// moves.extend((1..=2).filter(|&take| take <= stones));
/// }
///
/// fn play(&self, &(stones, side): &Self::Position, take: &u32) -> Self::Position {
/// let next = if side == Side::Max { Side::Min } else { Side::Max };
/// (stones - take, next)
/// }
///
/// fn evaluate(&self, &(stones, side): &Self::Position) -> i32 {
/// // With no stones left, the side to move has lost.
/// match (stones, side) {
/// (0, Side::Max) => -1,
/// (0, Side::Min) => 1,
/// _ => 0,
/// }
/// }
/// }
///
/// // Four stones: taking one leaves a multiple of three, a lost pile for the opponent.
/// let result = minimax(&Nim, &(4, Side::Max), 10);
/// assert_eq!(result.score, 1);
/// assert_eq!(result.best(), Some(&1));
/// ```
///
/// # Costly positions
///
/// A search asks for [`side_to_move`](Game::side_to_move), [`moves`](Game::moves) and
/// [`play`](Game::play) separately for every position it expands. At the depth limit it
/// asks for [`evaluate`](Game::evaluate) and [`noisy_moves`](Game::noisy_moves), and searches
/// on only where noisy moves come back; it also evaluates where the game ends, once
/// [`moves`](Game::moves) came back empty. When the side to move and the moves both
/// come from one costly derivation, such as sorting combatants by speed to find who acts
/// next, keep it in the position and work it out at most once, when a hook first asks:
/// quiet positions at the depth limit then never pay for it, as long as
/// [`noisy_moves`](Game::noisy_moves) can tell a quiet position without it, as the default
/// does by returning none. Working it out eagerly in `play` still pays for every leaf.
///
/// A `std::sync::OnceLock` keeps the position [`Sync`], as the `parallel` searches need;
/// a [`core::cell::OnceCell`] does for single-threaded searches. Leave the cache out of
/// [`Hashed::key`](crate::Hashed::key): it follows from the rest of the position.
///
/// ```
/// use std::sync::OnceLock;
///
/// use game_tree_search::{Game, Side, minimax};
///
/// /// The stones left and the moves made so far.
/// struct Pile {
/// stones: u32,
/// plies: u32,
/// }
///
/// /// Who moves next, `None` once the pile is empty: a stand-in for a costly derivation.
/// fn schedule(pile: &Pile) -> Option<Side> {
/// let side = if pile.plies % 2 == 0 { Side::Max } else { Side::Min };
/// (pile.stones > 0).then_some(side)
/// }
///
/// /// A pile with its schedule, worked out at most once and only when a search asks.
/// struct Position {
/// pile: Pile,
/// next: OnceLock<Option<Side>>,
/// }
///
/// impl Position {
/// fn new(pile: Pile) -> Self {
/// Self { pile, next: OnceLock::new() }
/// }
///
/// fn next(&self) -> Option<Side> {
/// *self.next.get_or_init(|| schedule(&self.pile))
/// }
/// }
///
/// struct Nim;
///
/// impl Game for Nim {
/// type Position = Position;
/// type Move = u32;
/// type Score = i32;
///
/// fn side_to_move(&self, position: &Position) -> Side {
/// position.next().expect("asked only while stones are left")
/// }
///
/// fn moves(&self, position: &Position, moves: &mut Vec<u32>) {
/// if position.next().is_some() {
/// moves.extend((1..=2).filter(|&take| take <= position.pile.stones));
/// }
/// }
///
/// fn play(&self, position: &Position, take: &u32) -> Position {
/// let (stones, plies) = (position.pile.stones - take, position.pile.plies + 1);
/// Position::new(Pile { stones, plies })
/// }
///
/// // Needs no schedule, so positions at the depth limit never work one out.
/// fn evaluate(&self, position: &Position) -> i32 {
/// match (position.pile.stones, position.pile.plies % 2) {
/// (0, 0) => -1,
/// (0, _) => 1,
/// _ => 0,
/// }
/// }
/// }
///
/// let result = minimax(&Nim, &Position::new(Pile { stones: 4, plies: 0 }), 10);
/// assert_eq!(result.best(), Some(&1));
/// ```
/// The moves a search expands at `position` with `depth` plies left: the [`Game::moves`], or
/// at the horizon (`depth == 0`, counted in `stats`) only the [`Game::noisy_moves`]. None
/// where the game ends, or at a quiet horizon.
pub
/// `score`, given from [`Side::Max`]'s point of view, from `side`'s point of view.
pub