-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.js
85 lines (79 loc) · 2.71 KB
/
bot.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
84
85
INF = 1000000000000000;
function heuristic(chess) {
if (chess.end() === true) {return INF;};
if (chess.end() === false) {return -INF;};
return getQueenMoves(chess.wPos, chess.blocks).length - getQueenMoves(chess.bPos, chess.blocks).length;
}
// function minimax(depth, chess) {
// if (chess.end() != null || depth <= 0) {return heuristic(chess);};
// if (chess.wFirst) {
// let maxRes = -INF;
// let ite = chess.iterNexts();
// for (let nex = ite.next(); nex.value !== undefined; nex = ite.next()) {
// alt = minimax(depth-1, nex.value[0]);
// maxRes = Math.max(maxRes, alt);
// }
// return maxRes;
// }
// else {
// let minRes = INF;
// let ite = chess.iterNexts();
// for (let nex = ite.next(); nex.value !== undefined; nex = ite.next()) {
// alt = minimax(depth-1, nex.value[0]);
// minRes = Math.min(minRes, alt);
// }
// return minRes;
// }
// }
function minimax(depth, chess, alpha = -INF, beta = INF) {
if (chess.end() != null || depth <= 0) { return heuristic(chess); }
if (chess.wFirst) {
let maxRes = -INF;
let ite = chess.iterNexts();
for (let nex = ite.next(); nex.value !== undefined; nex = ite.next()) {
if (beta <= alpha) {
continue;
}
let alt = minimax(depth - 1, nex.value[0], alpha, beta);
maxRes = Math.max(maxRes, alt);
alpha = Math.max(alpha, maxRes);
}
return maxRes;
} else {
let minRes = INF;
let ite = chess.iterNexts();
for (let nex = ite.next(); nex.value !== undefined; nex = ite.next()) {
if (beta <= alpha) {
continue;
}
let alt = minimax(depth - 1, nex.value[0], alpha, beta);
minRes = Math.min(minRes, alt);
beta = Math.min(beta, minRes);
}
return minRes;
}
}
function optimize(depth, chess) {
if (chess.wFirst) {
let maxRes = -INF*2;
let ite = chess.iterNexts();
let move;
for (let nex = ite.next(); nex.value !== undefined; nex = ite.next()) {
alt = minimax(depth-1, nex.value[0]);
if (alt > maxRes) {move = nex.value[1];};
maxRes = Math.max(maxRes, alt);
}
return move;
}
else {
let minRes = INF*2;
let ite = chess.iterNexts();
let move;
for (let nex = ite.next(); nex.value !== undefined; nex = ite.next()) {
alt = minimax(depth-1, nex.value[0]);
if (alt < minRes) {move = nex.value[1];};
minRes = Math.min(minRes, alt);
}
return move;
}
}