fours 0.1.0

Four in a row in your terminal, with three levels of opponent.
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
use crate::bot::Bot;
use crate::bot::random_numbers;
use crate::game::Cell;
use crate::game::GameState;
use crate::game::LINE_LENGTH;
use crate::game::Player;
use rand::rngs::StdRng;
use rand::seq::IndexedRandom;

/// The score of a won game, larger than anything [`Position::evaluate`] can reach.
const WIN: i32 = 1_000_000;

/// A score no game can reach, used as the open end of a search window.
const INFINITY: i32 = WIN * 2;

/// The four directions a line can run in, as a step from one cell to the next.
const DIRECTIONS: [(isize, isize); 4] = [(1, 0), (0, 1), (1, 1), (1, -1)];

/// A bot that searches ahead.
///
/// It walks the game tree with alpha beta pruning, prefers the wins it can reach soonest, and
/// judges the positions it cannot see the end of by how much room each player has left to build a
/// line. Moves are searched from the middle outwards, which prunes the tree faster.
///
/// The search runs over a board of its own rather than over a [`GameState`], so that a move can be
/// taken back instead of the position being copied at every node.
///
/// # Examples
///
/// ```
/// use fours::bot::Bot;
/// use fours::bot::SearchBot;
/// use fours::game::Game;
///
/// // Red has three in a row along the bottom and it is red's turn.
/// let game = Game::from_moves([0, 0, 1, 1, 2, 2]).unwrap();
/// let mut bot = SearchBot::seeded(1);
///
/// assert_eq!(bot.choose_move(game.state()), Some(3));
/// ```
#[derive(Debug, Clone)]
pub struct SearchBot {
    random_numbers: StdRng,
    depth: Option<u32>,
}

impl SearchBot {
    /// A bot seeded from the operating system, which breaks ties differently every run.
    pub fn from_entropy() -> Self {
        Self::with_seed(None)
    }

    /// A bot seeded with a fixed value, which plays the same way every run.
    pub fn seeded(seed: u64) -> Self {
        Self::with_seed(Some(seed))
    }

    /// A bot that searches to a fixed depth, in moves.
    ///
    /// Without this the depth follows the size of the board. Shallow depths make a weaker and
    /// faster opponent, which is useful for tests.
    pub fn with_depth(seed: u64, depth: u32) -> Self {
        Self {
            depth: Some(depth),
            ..Self::seeded(seed)
        }
    }

    pub(crate) fn with_seed(seed: Option<u64>) -> Self {
        Self {
            random_numbers: random_numbers(seed),
            depth: None,
        }
    }
}

impl Default for SearchBot {
    fn default() -> Self {
        Self::from_entropy()
    }
}

impl Bot for SearchBot {
    fn choose_move(&mut self, state: &GameState) -> Option<usize> {
        if state.is_over() {
            return None;
        }

        let mut position = Position::of(state);
        let depth = self.depth.unwrap_or_else(|| position.sensible_depth());
        let (_, best) = position.best_moves(depth);

        best.choose(&mut self.random_numbers).copied()
    }

    fn name(&self) -> &'static str {
        "Searching bot"
    }
}

/// A board the search can play moves on and take them back again.
///
/// Cells are held in one row major list, and every line of [`LINE_LENGTH`] cells that fits on
/// the board is worked out once so that judging a position is a walk over a list.
#[derive(Debug, Clone)]
struct Position {
    column_count: usize,
    row_count: usize,
    cells: Vec<Option<Player>>,
    heights: Vec<usize>,
    to_move: Player,
    played: usize,
    /// The columns to try, from the middle outwards.
    order: Vec<usize>,
    /// Every line of four cells that fits on the board, as indexes into `cells`.
    lines: Vec<[usize; LINE_LENGTH]>,
}

impl Position {
    fn of(state: &GameState) -> Self {
        let column_count = state.column_count();
        let row_count = state.row_count();
        let mut position = Self {
            column_count,
            row_count,
            cells: vec![None; column_count * row_count],
            heights: vec![0; column_count],
            to_move: state.current_player(),
            played: 0,
            order: columns_from_the_middle(column_count),
            lines: lines_of(column_count, row_count),
        };

        for row in 0..row_count {
            for column in 0..column_count {
                if let Some(player) = state.piece_at(Cell::new(column, row)) {
                    position.cells[row * column_count + column] = Some(player);
                    position.heights[column] += 1;
                    position.played += 1;
                }
            }
        }

        position
    }

    /// The best score the player to move can reach, and the columns that reach it.
    fn best_moves(&mut self, depth: u32) -> (i32, Vec<usize>) {
        let mut best = Vec::new();
        let mut best_rank = (-INFINITY, -INFINITY);

        for index in 0..self.order.len() {
            let column = self.order[index];
            if !self.can_play(column) {
                continue;
            }

            let rank = self.rank_of_playing(column, depth);
            if rank > best_rank {
                best_rank = rank;
                best.clear();
            }
            if rank == best_rank {
                best.push(column);
            }
        }

        (best_rank.0, best)
    }

    /// What playing a column is worth to the player to move: what the search makes of it, and
    /// how the board looks afterwards.
    ///
    /// The second half only separates moves the search cannot tell apart. Once a game is lost
    /// every move loses, so the search scores them all the same and the bot has nothing to choose
    /// between; picking by the look of the board keeps it blocking and holding the middle instead
    /// of playing anywhere, which is what giving up looks like from the other side of the board.
    fn rank_of_playing(&mut self, column: usize, depth: u32) -> (i32, i32) {
        if self.wins_with(column) {
            return (win_score(self.played), 0);
        }

        self.play(column);
        let score = -self.best_score(depth.saturating_sub(1), -INFINITY, INFINITY);
        let board = -self.evaluate();
        self.undo(column);

        (score, board)
    }

    /// The best the player to move can do, as far ahead as the depth allows.
    ///
    /// Scores are read from the point of view of the player to move, so a good position for one
    /// player is the same number with the other sign for the other.
    fn best_score(&mut self, depth: u32, mut alpha: i32, beta: i32) -> i32 {
        if !self.has_moves() {
            return 0;
        }

        if self.winning_move().is_some() {
            return win_score(self.played);
        }

        if depth == 0 {
            return self.evaluate();
        }

        for index in 0..self.order.len() {
            let column = self.order[index];
            if !self.can_play(column) {
                continue;
            }

            self.play(column);
            let score = -self.best_score(depth - 1, -beta, -alpha);
            self.undo(column);

            if score >= beta {
                return score;
            }
            alpha = alpha.max(score);
        }

        alpha
    }

    /// How good the position looks to the player to move, when the end is out of sight.
    ///
    /// A line of four that only one player can still complete is worth more the closer that player
    /// is to completing it, and the middle of the board is worth holding.
    fn evaluate(&self) -> i32 {
        let mut score = self.centre_control();

        for line in &self.lines {
            score += self.line_balance(line);
        }

        score
    }

    /// What a line of four is worth to the player who can still complete it.
    ///
    /// A line both players have a disc in is worth nothing to either of them. Otherwise it is
    /// worth more the closer its owner is to filling it, and much more when the slot that would
    /// fill it can actually be reached: on a crowded board most of the gaps are buried under
    /// empty air, and counting those as threats is how a search talks itself into ignoring the
    /// ones that matter.
    fn line_balance(&self, line: &[usize; LINE_LENGTH]) -> i32 {
        let mut mine = 0;
        let mut theirs = 0;
        let mut reach = usize::MAX;

        for index in line {
            match self.cells[*index] {
                Some(player) if player == self.to_move => mine += 1,
                Some(_) => theirs += 1,
                None => reach = reach.min(self.discs_below(*index)),
            }
        }

        match (mine, theirs) {
            (mine, 0) => room_value(mine, reach),
            (0, theirs) => -room_value(theirs, reach),
            _ => 0,
        }
    }

    /// How many discs have to fall into a column before an empty slot can be filled.
    fn discs_below(&self, index: usize) -> usize {
        let column = index % self.column_count;
        let row = index / self.column_count;

        row.saturating_sub(self.heights[column])
    }

    fn centre_control(&self) -> i32 {
        let middle = self.column_count / 2;

        (0..self.row_count)
            .filter_map(|row| self.piece(middle, row))
            .map(|player| if player == self.to_move { 3 } else { -3 })
            .sum()
    }

    fn has_moves(&self) -> bool {
        self.played < self.cells.len()
    }

    fn can_play(&self, column: usize) -> bool {
        self.heights[column] < self.row_count
    }

    /// A column that wins the game for the player to move, if there is one.
    fn winning_move(&self) -> Option<usize> {
        self.order
            .iter()
            .copied()
            .find(|column| self.wins_with(*column))
    }

    /// Whether the player to move wins the game by playing a column.
    fn wins_with(&self, column: usize) -> bool {
        if !self.can_play(column) {
            return false;
        }

        let row = self.heights[column];
        DIRECTIONS.iter().any(|(along, up)| {
            let forwards = self.run(column, row, (*along, *up));
            let backwards = self.run(column, row, (-*along, -*up));

            1 + forwards + backwards >= LINE_LENGTH
        })
    }

    /// The discs of the player to move in a row, walking away from a cell in one direction.
    fn run(&self, column: usize, row: usize, step: (isize, isize)) -> usize {
        let mut count = 0;
        let mut column = column;
        let mut row = row;

        loop {
            let (Some(next_column), Some(next_row)) = (
                column.checked_add_signed(step.0),
                row.checked_add_signed(step.1),
            ) else {
                return count;
            };

            if self.piece(next_column, next_row) != Some(self.to_move) {
                return count;
            }

            column = next_column;
            row = next_row;
            count += 1;
        }
    }

    fn piece(&self, column: usize, row: usize) -> Option<Player> {
        if column >= self.column_count || row >= self.row_count {
            return None;
        }

        self.cells[row * self.column_count + column]
    }

    fn play(&mut self, column: usize) {
        let row = self.heights[column];
        self.cells[row * self.column_count + column] = Some(self.to_move);
        self.heights[column] += 1;
        self.to_move = self.to_move.opponent();
        self.played += 1;
    }

    fn undo(&mut self, column: usize) {
        self.heights[column] -= 1;
        let row = self.heights[column];
        self.cells[row * self.column_count + column] = None;
        self.to_move = self.to_move.opponent();
        self.played -= 1;
    }

    /// How far ahead it is worth looking on a board of this size.
    fn sensible_depth(&self) -> u32 {
        match self.cells.len() {
            0..=42 => 6,
            43..=100 => 5,
            _ => 4,
        }
    }
}

/// A win is worth more the sooner it arrives.
///
/// The same arithmetic makes a loss worth more the later it arrives, so a search that cannot win
/// takes the longest way down as readily as it takes the shortest way up.
fn win_score(played: usize) -> i32 {
    WIN - i32::try_from(played).unwrap_or(0)
}

/// What a line is worth to the only player who can still complete it, given how far out of reach
/// its emptiest slot is.
fn room_value(discs: usize, reach: usize) -> i32 {
    match (discs, reach) {
        (3, 0) => 120,
        (3, 1) => 30,
        (3, _) => 10,
        (2, 0 | 1) => 8,
        (2, _) => 3,
        (1, _) => 1,
        _ => 0,
    }
}

/// The columns of a board, from the middle outwards.
fn columns_from_the_middle(column_count: usize) -> Vec<usize> {
    let middle = column_count / 2;
    let mut columns: Vec<usize> = (0..column_count).collect();
    columns.sort_by_key(|column| column.abs_diff(middle));

    columns
}

/// Every line of [`LINE_LENGTH`] cells that fits on a board, as indexes into its cells.
fn lines_of(column_count: usize, row_count: usize) -> Vec<[usize; LINE_LENGTH]> {
    let mut lines = Vec::new();

    for row in 0..row_count {
        for column in 0..column_count {
            for (along, up) in DIRECTIONS {
                if let Some(line) = line_from(column, row, (along, up), column_count, row_count) {
                    lines.push(line);
                }
            }
        }
    }

    lines
}

/// The line of cells that starts at a cell and runs in one direction, if it fits on the board.
fn line_from(
    column: usize,
    row: usize,
    step: (isize, isize),
    column_count: usize,
    row_count: usize,
) -> Option<[usize; LINE_LENGTH]> {
    let mut line = [0; LINE_LENGTH];

    for (offset, cell) in line.iter_mut().enumerate() {
        let distance = isize::try_from(offset).ok()?;
        let line_column = column.checked_add_signed(step.0 * distance)?;
        let line_row = row.checked_add_signed(step.1 * distance)?;

        if line_column >= column_count || line_row >= row_count {
            return None;
        }

        *cell = line_row * column_count + line_column;
    }

    Some(line)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::game::Game;

    /// The position after a sequence of moves.
    fn position_after(moves: &[usize]) -> GameState {
        let game = Game::from_moves(moves.iter().copied()).expect("the moves are legal");

        game.state().clone()
    }

    /// What the bot answers to a position, at the depth it plays at.
    fn answer_to(moves: &[usize]) -> Option<usize> {
        SearchBot::seeded(1).choose_move(&position_after(moves))
    }

    // Positions one move from a line, one for each direction a line can run in.
    const HORIZONTAL: [usize; 6] = [0, 0, 1, 1, 2, 2];
    const VERTICAL: [usize; 6] = [2, 3, 2, 3, 2, 4];
    const RISING: [usize; 10] = [0, 1, 1, 2, 2, 3, 2, 3, 3, 0];
    const FALLING: [usize; 10] = [6, 5, 5, 4, 4, 3, 4, 3, 3, 0];

    #[test]
    fn it_takes_a_win_in_any_direction() {
        assert_eq!(answer_to(&HORIZONTAL), Some(3));
        assert_eq!(answer_to(&VERTICAL), Some(2));
        assert_eq!(answer_to(&RISING), Some(3));
        assert_eq!(answer_to(&FALLING), Some(3));
    }

    #[test]
    fn it_takes_a_win_however_shallow_it_is_looking() {
        for depth in 0..4 {
            let mut bot = SearchBot::with_depth(1, depth);
            assert_eq!(
                bot.choose_move(&position_after(&HORIZONTAL)),
                Some(3),
                "a bot looking {depth} moves ahead missed a win in one"
            );
        }
    }

    #[test]
    fn it_blocks_the_only_threat_against_it() {
        // Red owns three of the bottom row, so yellow has one move that does not end the game.
        assert_eq!(answer_to(&[0, 5, 1, 6, 2]), Some(3));
    }

    #[test]
    fn it_takes_its_own_win_before_stopping_one() {
        // Both sides are one move from a line and the bot is the one to move.
        assert_eq!(answer_to(&[0, 4, 1, 5, 2, 6]), Some(3));
    }

    #[test]
    fn it_does_not_carry_the_other_player_up_to_a_win() {
        // Yellow owns three of the second row, so a disc in column zero or four lifts yellow to
        // the slot it needs.
        let answer = answer_to(&[1, 2, 0, 3, 3, 1, 0, 0, 0, 2]).expect("the game is live");

        assert!(answer != 0 && answer != 4, "the bot answered {answer}");
    }

    #[test]
    fn it_has_nothing_to_say_about_a_finished_game() {
        assert_eq!(answer_to(&[3, 4, 3, 4, 3, 4, 3]), None);
    }

    #[test]
    fn it_answers_the_same_way_twice() {
        let state = position_after(&[3, 3, 4]);
        let ask = |seed| SearchBot::seeded(seed).choose_move(&state);

        assert_eq!(ask(4), ask(4));
    }

    #[test]
    fn a_position_mirrors_the_board_it_was_made_from() {
        let state = position_after(&[3, 3, 4, 5, 3]);
        let position = Position::of(&state);

        assert_eq!(position.played, 5);
        assert_eq!(position.to_move, state.current_player());
        assert_eq!(position.heights, vec![0, 0, 0, 3, 1, 1, 0]);
        assert_eq!(position.piece(3, 0), state.piece_at(Cell::new(3, 0)));
        assert_eq!(position.piece(3, 2), state.piece_at(Cell::new(3, 2)));
        assert_eq!(position.piece(0, 0), None);
        assert_eq!(position.piece(9, 9), None);
    }

    #[test]
    fn taking_a_move_back_leaves_the_position_as_it_was() {
        let mut position = Position::of(&position_after(&[3, 3, 4]));
        let before = position.clone();

        for column in 0..7 {
            position.play(column);
            position.undo(column);

            assert_eq!(position.cells, before.cells, "column {column} left a mark");
            assert_eq!(position.heights, before.heights);
            assert_eq!(position.played, before.played);
            assert_eq!(position.to_move, before.to_move);
        }
    }

    #[test]
    fn it_sees_a_line_coming_in_any_direction() {
        for (moves, column) in [
            (HORIZONTAL.as_slice(), 3),
            (VERTICAL.as_slice(), 2),
            (RISING.as_slice(), 3),
            (FALLING.as_slice(), 3),
        ] {
            let position = Position::of(&position_after(moves));

            assert!(position.wins_with(column), "missed a win at {column}");
            for other in 0..7 {
                if other != column {
                    assert!(!position.wins_with(other), "imagined a win at {other}");
                }
            }
        }
    }

    #[test]
    fn an_empty_board_favours_neither_player() {
        let position = Position::of(&GameState::new());

        assert_eq!(position.evaluate(), 0);
    }

    #[test]
    fn a_line_is_worth_more_the_closer_it_is_to_being_finished() {
        assert!(room_value(3, 0) > room_value(2, 0));
        assert!(room_value(2, 0) > room_value(1, 0));
        assert!(room_value(1, 0) > room_value(0, 0));
    }

    #[test]
    fn a_line_is_worth_more_when_its_empty_slot_can_be_reached() {
        assert!(room_value(3, 0) > room_value(3, 1));
        assert!(room_value(3, 1) > room_value(3, 5));
        assert!(room_value(2, 1) > room_value(2, 5));
    }

    #[test]
    fn a_win_is_worth_more_the_sooner_it_comes() {
        assert!(win_score(10) > win_score(12));
        assert!(win_score(0) > win_score(42));
    }

    #[test]
    fn the_middle_of_the_board_is_searched_first() {
        assert_eq!(columns_from_the_middle(7), vec![3, 2, 4, 1, 5, 0, 6]);
        assert_eq!(columns_from_the_middle(1), vec![0]);
    }

    #[test]
    fn a_board_has_a_line_for_every_four_slots_that_fit_on_it() {
        // Twenty four across, twenty one up, and twelve each way on the diagonals.
        assert_eq!(lines_of(7, 6).len(), 69);
        assert_eq!(lines_of(4, 1).len(), 1);
        assert_eq!(lines_of(3, 3).len(), 0);
    }

    #[test]
    fn a_winning_position_scores_as_a_win() {
        let mut position = Position::of(&position_after(&HORIZONTAL));
        let (score, best) = position.best_moves(4);

        assert!(score > WIN / 2, "a win in one scored {score}");
        assert_eq!(best, vec![3]);
    }

    #[test]
    fn a_lost_position_scores_as_a_loss() {
        // Red owns the middle of the bottom row with both ends of it open, so yellow can only
        // stop one of them.
        let mut position = Position::of(&position_after(&[1, 6, 2, 6, 3]));
        let (score, _) = position.best_moves(4);

        assert!(score < -WIN / 2, "a loss in two scored {score}");
    }
}