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
//! 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));
/// ```
/// 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