ai-othello 0.1.1

An Othello rules, evaluation, and alpha-beta search engine
Documentation
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
use crate::{
    Evaluation, EvaluationProfile, GameResult, Move, MoveList, Position, Square, evaluate,
};

const INFINITY: i32 = 40_000;
const TERMINAL: i32 = 30_000;

/// Search score with exact results kept outside the heuristic band.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Score(i32);

impl Score {
    pub const fn raw(self) -> i32 {
        self.0
    }

    pub const fn kind(self) -> ScoreKind {
        if self.0 >= TERMINAL {
            ScoreKind::Win {
                margin: (self.0 - TERMINAL) as u8,
            }
        } else if self.0 <= -TERMINAL {
            ScoreKind::Loss {
                margin: (-self.0 - TERMINAL) as u8,
            }
        } else {
            ScoreKind::Estimate(self.0)
        }
    }

    const fn negated(self) -> Self {
        Self(-self.0)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScoreKind {
    Win { margin: u8 },
    Draw,
    Loss { margin: u8 },
    Estimate(i32),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SearchConfig {
    pub depth: u8,
    pub evaluator: EvaluationProfile,
    pub exact_endgame_empties: u8,
}

impl SearchConfig {
    pub const fn fixed_depth(depth: u8, evaluator: EvaluationProfile) -> Self {
        Self {
            depth,
            evaluator,
            exact_endgame_empties: 0,
        }
    }
}

/// A named search depth and exact-endgame threshold for interactive play.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SearchPreset {
    pub name: &'static str,
    pub depth: u8,
    pub exact_endgame_empties: u8,
}

impl SearchPreset {
    pub const fn config(self, evaluator: EvaluationProfile) -> SearchConfig {
        SearchConfig {
            depth: self.depth,
            evaluator,
            exact_endgame_empties: self.exact_endgame_empties,
        }
    }
}

/// The built-in strength ladder, ordered from least to most search work.
pub const SEARCH_PRESETS: [SearchPreset; 6] = [
    SearchPreset {
        name: "beginner",
        depth: 1,
        exact_endgame_empties: 0,
    },
    SearchPreset {
        name: "easy",
        depth: 2,
        exact_endgame_empties: 0,
    },
    SearchPreset {
        name: "medium",
        depth: 4,
        exact_endgame_empties: 2,
    },
    SearchPreset {
        name: "hard",
        depth: 5,
        exact_endgame_empties: 4,
    },
    SearchPreset {
        name: "expert",
        depth: 6,
        exact_endgame_empties: 8,
    },
    SearchPreset {
        name: "maximum",
        depth: 7,
        exact_endgame_empties: 8,
    },
];

/// Finds a built-in strength preset by its lowercase name.
pub fn search_preset(name: &str) -> Option<SearchPreset> {
    SEARCH_PRESETS
        .iter()
        .copied()
        .find(|preset| preset.name == name)
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct SearchStats {
    pub nodes: u64,
    pub leaves: u64,
    pub cutoffs: u64,
    pub passes: u64,
    pub exact_nodes: u64,
    pub max_ply: u8,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Candidate {
    pub mv: Move,
    pub score: Score,
    pub nodes: u64,
    pub cutoffs: u64,
    pub flipped: u64,
}

/// Complete result of one search.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SearchReport {
    pub config: SearchConfig,
    pub best_move: Option<Move>,
    pub score: Score,
    pub exact: bool,
    pub principal_variation: Vec<Move>,
    pub candidates: Vec<Candidate>,
    pub evaluation: Evaluation,
    pub stats: SearchStats,
}

#[derive(Debug, Clone, Copy)]
struct Line {
    moves: [Move; 64],
    len: u8,
}

impl Default for Line {
    fn default() -> Self {
        Self {
            moves: [Move::Pass; 64],
            len: 0,
        }
    }
}

impl Line {
    fn prepend(mv: Move, child: Self) -> Self {
        let mut line = Self::default();
        line.moves[0] = mv;
        let child_len = usize::from(child.len).min(63);
        if child_len > 0 {
            line.moves[1..=child_len].copy_from_slice(&child.moves[..child_len]);
        }
        line.len = child_len as u8 + 1;
        line
    }

    fn to_vec(self) -> Vec<Move> {
        self.moves[..usize::from(self.len)].to_vec()
    }
}

#[derive(Debug, Clone, Copy)]
struct NodeResult {
    score: Score,
    line: Line,
}

struct Searcher<F: Fn() -> bool> {
    config: SearchConfig,
    stats: SearchStats,
    should_stop: F,
    stopped: bool,
}

impl<F: Fn() -> bool> Searcher<F> {
    fn stop_requested(&mut self) -> bool {
        if self.stopped || (self.should_stop)() {
            self.stopped = true;
        }
        self.stopped
    }

    fn node(
        &mut self,
        position: &mut Position,
        depth: u8,
        ply: u8,
        mut alpha: Score,
        beta: Score,
    ) -> Option<NodeResult> {
        if self.stop_requested() {
            return None;
        }
        self.stats.nodes += 1;
        self.stats.max_ply = self.stats.max_ply.max(ply);
        if position.empty_count() <= self.config.exact_endgame_empties {
            self.stats.exact_nodes += 1;
        }
        if let Some(score) = terminal_score(*position) {
            self.stats.leaves += 1;
            return Some(NodeResult {
                score,
                line: Line::default(),
            });
        }
        let exact = position.empty_count() <= self.config.exact_endgame_empties;
        if depth == 0 && !exact {
            self.stats.leaves += 1;
            return Some(NodeResult {
                score: Score(evaluate(*position, self.config.evaluator).total),
                line: Line::default(),
            });
        }

        let mut best = Score(-INFINITY);
        let mut best_move = None;
        let mut best_line = Line::default();
        for mv in ordered_moves(*position) {
            if mv == Move::Pass {
                self.stats.passes += 1;
            }
            let undo = position
                .make_move(mv)
                .expect("generated moves must be legal");
            let next_depth = if mv == Move::Pass {
                depth
            } else {
                depth.saturating_sub(1)
            };
            let child = self.node(
                position,
                next_depth,
                ply + 1,
                beta.negated(),
                alpha.negated(),
            );
            position.unmake_move(undo);
            let child = child?;
            let score = child.score.negated();
            if score > best || (score == best && prefer(mv, best_move)) {
                best = score;
                best_move = Some(mv);
                best_line = Line::prepend(mv, child.line);
            }
            alpha = alpha.max(score);
            if alpha >= beta {
                self.stats.cutoffs += 1;
                break;
            }
        }
        Some(NodeResult {
            score: best,
            line: best_line,
        })
    }
}

/// Searches `position` to the configured depth.
pub fn search(position: Position, config: SearchConfig) -> SearchReport {
    search_until(position, config, || false)
        .expect("a search with a constant false stop signal must complete")
}

/// Search a fixed depth while polling a cooperative stop signal at node entry.
/// A stopped partial result is discarded.
pub fn search_until<F: Fn() -> bool>(
    position: Position,
    config: SearchConfig,
    should_stop: F,
) -> Option<SearchReport> {
    let exact = position.empty_count() <= config.exact_endgame_empties;
    let evaluation = evaluate(position, config.evaluator);
    let mut searcher = Searcher {
        config,
        stats: SearchStats {
            nodes: 1,
            ..SearchStats::default()
        },
        should_stop,
        stopped: false,
    };
    if searcher.stop_requested() {
        return None;
    }
    if let Some(score) = terminal_score(position) {
        searcher.stats.leaves = 1;
        return Some(SearchReport {
            config,
            best_move: None,
            score,
            exact: true,
            principal_variation: Vec::new(),
            candidates: Vec::new(),
            evaluation,
            stats: searcher.stats,
        });
    }
    if config.depth == 0 && !exact {
        searcher.stats.leaves = 1;
        return Some(SearchReport {
            config,
            best_move: None,
            score: Score(evaluation.total),
            exact: false,
            principal_variation: Vec::new(),
            candidates: Vec::new(),
            evaluation,
            stats: searcher.stats,
        });
    }

    let mut best = Score(-INFINITY);
    let mut best_move = None;
    let mut best_line = Line::default();
    let mut candidates = Vec::new();
    for mv in ordered_moves(position) {
        if searcher.stop_requested() {
            return None;
        }
        if mv == Move::Pass {
            searcher.stats.passes += 1;
        }
        let before_nodes = searcher.stats.nodes;
        let before_cutoffs = searcher.stats.cutoffs;
        let flipped = mv.square().map_or(0, |square| position.flips_for(square));
        let mut child_position = position;
        child_position
            .make_move(mv)
            .expect("generated moves must be legal");
        let next_depth = if mv == Move::Pass {
            config.depth
        } else {
            config.depth.saturating_sub(1)
        };
        let child = searcher.node(
            &mut child_position,
            next_depth,
            1,
            Score(-INFINITY),
            Score(INFINITY),
        )?;
        let score = child.score.negated();
        candidates.push(Candidate {
            mv,
            score,
            nodes: searcher.stats.nodes - before_nodes,
            cutoffs: searcher.stats.cutoffs - before_cutoffs,
            flipped,
        });
        if score > best || (score == best && prefer(mv, best_move)) {
            best = score;
            best_move = Some(mv);
            best_line = Line::prepend(mv, child.line);
        }
    }

    Some(SearchReport {
        config,
        best_move,
        score: best,
        exact,
        principal_variation: best_line.to_vec(),
        candidates,
        evaluation,
        stats: searcher.stats,
    })
}

fn terminal_score(position: Position) -> Option<Score> {
    match position.result() {
        GameResult::Ongoing => None,
        GameResult::Draw { .. } => Some(Score(0)),
        GameResult::Win {
            winner,
            black,
            white,
        } => {
            let margin = i32::from(black.abs_diff(white));
            if winner == position.side_to_move() {
                Some(Score(TERMINAL + margin))
            } else {
                Some(Score(-TERMINAL - margin))
            }
        }
    }
}

fn ordered_moves(position: Position) -> MoveList {
    const CORNERS: [u8; 4] = [0, 7, 56, 63];
    let legal = position.legal_moves();
    if legal.as_slice() == [Move::Pass] {
        return legal;
    }
    let mut ordered = MoveList::default();
    for index in CORNERS {
        let mv = Move::Place(Square::new(index));
        if legal.as_slice().contains(&mv) {
            ordered.push(mv);
        }
    }
    for mv in legal {
        if !ordered.as_slice().contains(&mv) {
            ordered.push(mv);
        }
    }
    ordered
}

fn prefer(candidate: Move, current: Option<Move>) -> bool {
    current.is_none_or(|mv| candidate < mv)
}