Created
July 6, 2017 15:35
-
-
Save byanofsky/c8dd06cd1b1fb8d06a9dd695d07e403e to your computer and use it in GitHub Desktop.
Minimax algorithm with alpha beta pruning
This file contains 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 calcBestMove = function(depth, game, playerColor, | |
alpha=Number.NEGATIVE_INFINITY, | |
beta=Number.POSITIVE_INFINITY, | |
isMaximizingPlayer=true) { | |
// Base case: evaluate board | |
if (depth === 0) { | |
value = evaluateBoard(game.board(), playerColor); | |
return [value, null] | |
} | |
// Recursive case: search possible moves | |
var bestMove = null; // best move not set yet | |
var possibleMoves = game.moves(); | |
// Set random order for possible moves | |
possibleMoves.sort(function(a, b){return 0.5 - Math.random()}); | |
// Set a default best move value | |
var bestMoveValue = isMaximizingPlayer ? Number.NEGATIVE_INFINITY | |
: Number.POSITIVE_INFINITY; | |
// Search through all possible moves | |
for (var i = 0; i < possibleMoves.length; i++) { | |
var move = possibleMoves[i]; | |
// Make the move, but undo before exiting loop | |
game.move(move); | |
// Recursively get the value from this move | |
value = calcBestMove(depth-1, game, playerColor, alpha, beta, !isMaximizingPlayer)[0]; | |
// Log the value of this move | |
console.log(isMaximizingPlayer ? 'Max: ' : 'Min: ', depth, move, value, | |
bestMove, bestMoveValue); | |
if (isMaximizingPlayer) { | |
// Look for moves that maximize position | |
if (value > bestMoveValue) { | |
bestMoveValue = value; | |
bestMove = move; | |
} | |
alpha = Math.max(alpha, value); | |
} else { | |
// Look for moves that minimize position | |
if (value < bestMoveValue) { | |
bestMoveValue = value; | |
bestMove = move; | |
} | |
beta = Math.min(beta, value); | |
} | |
// Undo previous move | |
game.undo(); | |
// Check for alpha beta pruning | |
if (beta <= alpha) { | |
console.log('Prune', alpha, beta); | |
break; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment