-
Notifications
You must be signed in to change notification settings - Fork 0
/
minimax.js
55 lines (50 loc) · 1.12 KB
/
minimax.js
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
function minimax(play, isMaximizing) {
let result = whoWin(play)
if (result !== 'continue')
return state[result]
let emptyCells = getEmptyCells(play)
let bestScore = isMaximizing ? -Infinity : Infinity
if (isMaximizing) {
for (cell of emptyCells) {
let i = cell.i
let j = cell.j
play[i][j] = ai.char
bestScore = Math.max(bestScore, minimax(play, false))
play[i][j] = '.'
}
} else {
for (cell of emptyCells) {
let i = cell.i
let j = cell.j
play[i][j] = human.char
bestScore = Math.min(bestScore, minimax(play, true))
play[i][j] = '.'
}
}
return bestScore
}
function bestMove(play) {
let bestScore = -Infinity
let move
let emptyCells = getEmptyCells(play)
for (cell of emptyCells) {
let i = cell.i
let j = cell.j
play[i][j] = ai.char
let score = minimax(play, false)
play[i][j] = '.'
if (score > bestScore) {
bestScore = score
move = [i, j]
}
}
return move
}
function getEmptyCells(play) {
let emptyCells = []
for (let i = 0; i < play.length; i++)
for (let j = 0; j < play.length; j++)
if (play[i][j] === '.')
emptyCells.push({i, j})
return emptyCells
}