diff options
| author | Charles Cabergs <me@cacharle.xyz> | 2021-02-01 23:10:19 +0100 |
|---|---|---|
| committer | Charles Cabergs <me@cacharle.xyz> | 2021-02-01 23:10:19 +0100 |
| commit | 2b0619720474ce8191326751950442b6ba45da26 (patch) | |
| tree | 45186039af5023834dcf681d4726effd84559035 /src/solve.rs | |
| parent | f9cf59ba3ec085e889bf252e462659716514b8b7 (diff) | |
| download | connect4-2b0619720474ce8191326751950442b6ba45da26.tar.gz connect4-2b0619720474ce8191326751950442b6ba45da26.tar.bz2 connect4-2b0619720474ce8191326751950442b6ba45da26.zip | |
Refactoring in separated modules
Diffstat (limited to 'src/solve.rs')
| -rw-r--r-- | src/solve.rs | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/src/solve.rs b/src/solve.rs new file mode 100644 index 0000000..2c7e0d2 --- /dev/null +++ b/src/solve.rs @@ -0,0 +1,43 @@ +use crate::position::{Position, WIDTH, HEIGHT}; + +pub fn solve(p: Position, a: i32, b: i32) -> i32 { + if p.is_draw() { + return 0; + } + for x in 0..WIDTH { + if p.is_valid_play(x) && p.is_winning_play(x) { + return (((WIDTH * HEIGHT + 1) as i32) - (p.play_count as i32)) / 2; + } + } + + let mut alpha = a; + let mut beta = b; + + let max = (((WIDTH * HEIGHT + 1) as i32) - (p.play_count as i32)) / 2; + + if beta > max { + beta = max; + if alpha >= beta { + return beta; + } + } + + for x in 0..WIDTH { + if !p.is_valid_play(x) { + continue + } + + let score = -solve(p.play(x), -beta, -alpha); + + if score >= beta { + return score; + } + + if score > alpha { + alpha = score; + } + } + return alpha; +} + + |
