Skip to content

Instantly share code, notes, and snippets.

@Luomint
Created January 5, 2016 12:23
Show Gist options
  • Save Luomint/06927011ecf723e3f40e to your computer and use it in GitHub Desktop.
Save Luomint/06927011ecf723e3f40e to your computer and use it in GitHub Desktop.
function minimax(level, player) {
if (checkWin(player) || level === 0 || checkWin(AI)) {
score = evaluate();
return score;
}
if (checkWin(human)) {
// console.log("1x")
return -10;
} else if (checkWin(AI)) {
// console.log("2x")
return 10;
} else if (checkDraw()) {
console.log("tie");
return 0;
} else {
var moves = validMoves();
if (player == AI) {
var bestScore = 100;
// var alpha = -1;
for (var i = 0; i < moves.length; i++) {
var m = moves[i];
copy[m] = AI;
// recursive call
var score = minimax(level - 1, human);
if (score < bestScore) {
bestScore = score;
alpha = m;
// stop it here if the win condition is met
if (checkWin(AI) === true) {
copy[m] = "";
return [alpha, bestScore];
}
}
copy[m] = "";
draw();
}
return [alpha, bestScore];
} else {
var bestScore = -100;
// var alpha = -1;
for (var x = 0; x < moves.length; x++) {
var m = moves[x];
copy[m] = human;
// recursive call
var score = minimax(level - 1, AI);
if (score > bestScore) {
bestScore = score;
alpha = m;
}
copy[m] = "";
draw();
}
return [alpha, bestScore];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment