Created
July 6, 2017 15:15
-
-
Save byanofsky/8ed19b3a101e651e5216c933b5f1b871 to your computer and use it in GitHub Desktop.
Evaluate the best move using Minimax
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 calcBestMoveNoAB = function(depth, game, playerColor, | |
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 of this move | |
value = calcBestMoveNoAB(depth-1, game, playerColor, !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; | |
} | |
} else { | |
// Look for moves that minimize position | |
if (value < bestMoveValue) { | |
bestMoveValue = value; | |
bestMove = move; | |
} | |
} | |
// Undo previous move | |
game.undo(); | |
} | |
// Log the best move at the current depth | |
console.log('Depth: ' + depth + ' | Best Move: ' + bestMove + ' | ' + bestMoveValue); | |
// Return the best move, or the only move | |
return [bestMoveValue, bestMove || possibleMoves[0]]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment