-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathminimax.js
90 lines (67 loc) · 1.57 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
78
79
80
81
82
83
//function to value the game
const valueGame = function (gameArr) {
//define all the axes
const axes = {
row1 : [0,1,2],
row2 : [3,4,5],
row3 : [6,7,8],
column1 : [0,3,6],
column2 : [1,4,7],
column3 : [2,5,8],
diagonal1 : [0,4,8],
diagonal2 : [2,4,6],
}
for (const axis in axes) {
if (gameArr[axes[axis][0]] === gameArr[axes[axis][1]] && gameArr[axes[axis][0]] === gameArr[axes[axis][2]] ) {
if (gameArr[axes[axis][0]] === "O") {
return 10;
} else if (gameArr[axes[axis][0]] === "X") {
return -10;
}
}
}
if (!gameArr.includes(NaN)) {
return "0";
}
} // end of value game
const miniMax = function (gameArr, isMaxPlayer, depth = 0) {
if (valueGame(gameArr)) {
return {"value" : valueGame(gameArr)}
} else {
const values = []
depth++
//max player
if (isMaxPlayer) {
gameArr.forEach((e,i,a) => {
if (!e){
a[i] = "O"
const obj = {
"index" : i,
"value": miniMax(a.slice(0), false).value - depth
}
values.push(obj)
a[i] = NaN
}
})
// console.log(values);
const max = values.reduce((x, y) => x.value > y.value ? x : y);
return max
//min player
} else if (!isMaxPlayer) {
gameArr.forEach((e,i,a) => {
if (!e){
a[i] = "X"
const obj = {
"index" : i,
"value": miniMax(a.slice(0), true).value - depth
}
values.push(obj)
a[i] = NaN
}
})
// console.log(values);
const min = values.reduce((x, y) => x.value < y.value ? x : y);
return min
}
}//end of else (not a value)
} // end of minimax function