/
negamax.js
24 lines (24 loc) · 962 Bytes
/
negamax.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
ma.players.negamax = function(options) {
options = options || {};
var maxDepth = options.maxDepth || Number.MAX_VALUE,
evalFunc = options.evalFunc || ma.utilFunc;
return function(game) {
return (function negamax(game, curDepth) {
if (game.isGameOver() || curDepth === maxDepth) {
return { score: evalFunc(game, game.currentPlayer()) };
}
var bestMove = null,
bestScore = -Number.MAX_VALUE,
moves = game.moves();
for (var move = 0; move < moves.length; move++) {
var moveScore = negamax(game.copy().move(move), curDepth + 1);
var curScore = -moveScore.score;
if (curScore > bestScore) {
bestMove = move;
bestScore = curScore;
}
}
return { move: bestMove, score: bestScore };
}(game, 0)).move;
};
};