-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathminimax.js
77 lines (61 loc) · 1.83 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
66
67
68
69
70
71
72
73
74
75
76
77
let scores = {
x: 1,
o: -1,
tie: 0
}
function bestMove() {
let bestScore = -Infinity;
let move;
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
// Is the spot available?
if (gameBoard.getField(i, j) == '') {
//moving ai to that spot
gameBoard.setField(i, j, aiPlayer.getSign());
let score = minimax(gameBoard.getBoard(), 0 , false);
console.log(score);
//undo the move
gameBoard.setField(i, j, '');
if (score > bestScore) {
bestScore = score;
move = { i, j };
}
}
}
}
gameBoard.setField(move.i, move.j, aiPlayer.getSign());
current_player = humanPlayer;
}
function minimax(board, depth, isMaximizing) {
let result = gameController.checkWinner();
// console.log(result);
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++) {
if (gameBoard.getField(i, j) == '') {
gameBoard.setField(i, j, aiPlayer.getSign());
let score = minimax(board, depth + 1, false);
gameBoard.setField(i, j, '');
bestScore = Math.max(score, bestScore);
}
}
}
return bestScore;
} else {
let bestScore = Infinity;
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (gameBoard.getField(i, j) == '') {
gameBoard.setField(i, j, humanPlayer.getSign());
let score = minimax(board, depth + 1, true);
gameBoard.setField(i, j, '');
bestScore = Math.min(score, bestScore);
}
}
}
return bestScore;
}