Created
February 20, 2019 15:09
-
-
Save questsin/da9aca965190dff57003c9aa649ae326 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var _ = require('lodash'); | |
module.exports = function (node, options) { | |
var best = {node: null, score: -Infinity} | |
, opts = options || {} | |
, color = opts.color || -1 | |
, depth = opts.depth || 10; | |
// negamax algorithm taken from http://wikipedia.org/wiki/Negamax | |
function getScore(node, depth, alpha, beta, color) { | |
var bestValue = -Infinity; | |
if (depth === 0 || node.isTerminal()) { | |
return color * node.value(); | |
} | |
_.each(node.children(), function (child) { | |
var value = -getScore(child, depth - 1, -beta, -alpha, -color); | |
bestValue = Math.max(value, bestValue); | |
var skip = Math.max(alpha, value) >= beta; | |
if (skip) return false; | |
}); | |
return bestValue; | |
}; | |
// return node with highest score | |
_.each(node.children(), function (child) { | |
var score = color * getScore(child, depth, -Infinity, Infinity, color); | |
if (score <= best.score) return; | |
best.node = child; | |
best.score = score; | |
}); | |
return best; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment