-
Notifications
You must be signed in to change notification settings - Fork 0
/
minimax.js
65 lines (61 loc) · 1.54 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
56
57
58
59
60
61
62
63
64
65
function bestMove() {
// AI to make its turn
let bestScore = -Infinity;
let move;
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
// Is the spot available?
if (board[i][j] == '') {
board[i][j] = ai;
let score = minimax(board, 0, false);
board[i][j] = '';
if (score > bestScore) {
bestScore = score;
move = { i, j };
}
}
}
}
board[move.i][move.j] = ai;
currentPlayer = human;
}
let scores = {
X: 10,
O: -10,
tie: 0
};
function minimax(board, depth, isMaximizing) {
let result = checkWinner();
if (result !== null) {
return scores[result];
}
if (isMaximizing) {
let bestScore = -Infinity;
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
// Is the spot available?
if (board[i][j] == '') {
board[i][j] = ai;
let score = minimax(board, depth + 1, false);
board[i][j] = '';
bestScore = max(score, bestScore);
}
}
}
return bestScore;
} else {
let bestScore = Infinity;
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
// Is the spot available?
if (board[i][j] == '') {
board[i][j] = human;
let score = minimax(board, depth + 1, true);
board[i][j] = '';
bestScore = min(score, bestScore);
}
}
}
return bestScore;
}
}