-
Notifications
You must be signed in to change notification settings - Fork 4
/
ai.js
102 lines (94 loc) · 2.16 KB
/
ai.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
var alpha = -999999999;
var beta = 999999999;
/* Really dumb eval function:
*
* f(p) = 200(K-K')
* + 9(Q-Q')
* + 5(R-R')
* + 3(B-B' + N-N')
* + 1(P-P')
* - 0.5(D-D' + S-S' + I-I')
* + 0.1(M-M') + ...
*
* KQRBNP = number of kings, queens, rooks, bishops, knights and pawns
* D,S,I = doubled, blocked and isolated pawns
* M = Mobility (the number of legal moves)
*
*/
var RANK = {};
_.each({k: -200, q: -9, r: -5, b: -3, n: -3, p: -1}, function(val, key) {
RANK[key] = val;
RANK[key.toUpperCase()] = val * -1;
});
// score the chess game based on the above algorithm.
function score(chess) {
var pieces = _.toArray(fen_pieces(chess));
var tally = _.tally(pieces);
var s = 0;
var turn = -1;
if (chess.turn() == 'b')
{
turn = 1;//white just moved, evaluate from white's perspective
}
_.each(tally, function(val, p) {
s = s + val*RANK[p];
});
return s * turn;
}
function fen_pieces(chess) {
return chess.fen().split(' ')[0].replace(/\//g, '').replace(/\d/g, '');
}
function startAlphaBeta(tchess, depth)
{
var best_score = -9999;
var best_move = '';
var moves = tchess.moves();
for (var index = 0; index < moves.length; index++)
{
var tempchess = new Chess(tchess.fen());
tempchess.move(moves[index]);
var move_score;
if (tempchess.in_checkmate()){
move_score = 9998;//last player to make move won
} else{
if (depth == 0)
{
move_score = score(tempchess);
}
else {
move_score = -alphaBeta(tempchess, depth-1);
}
}
if (move_score > best_score){
best_score = move_score;
best_move = moves[index];
}
}
return best_move;
}
function alphaBeta(tchess,depth)
{
var best_score = -9999;
var moves = tchess.moves();
for (var index = 0; index < moves.length; index++)
{
var tempchess = new Chess(tchess.fen());
tempchess.move(moves[index]);
var move_score;
if (tempchess.in_checkmate()){
move_score = 9998;//last player to make move won
} else{
if (depth == 0)
{
move_score = score(tempchess);
}
else {
move_score = -alphaBeta(tempchess, depth-1);
}
}
if (move_score > best_score){
best_score = move_score;
}
}
return best_score;
}