I recently write the MinMax algorithm using javascript, but when I implement the recursion,
it seems that the variable changes in a weird way, here is the code:
function moveValue(istate, move, moveFor, nextTurn, depth){
console.log("the original state is: ", istate)
var state = stateMove(istate, move, nextTurn);
var winner = status.detectWin(state)
console.log("now the istate is:", istate)
console.log("now the state is: ", state)
if (winner == 'tie'){
return 0;
} else if (winner != 0){
if (moveFor == nextTurn) return 10 - depth;
else return depth - 10;
}
//if the the current operation is not the same with the original, minimum scenario
//if the the current operation is the same with the original, maximum scenario
var hope = 999;
if (moveFor != nextTurn) hope = -999;
var moves = getLegalMoves(state);
for (var i=0; i<9; i++){
if (moves.indexOf(i) > -1) {
var value = moveValue(state, i, moveFor, -nextTurn, depth+1);
if (moveFor == nextTurn && value < hope ||moveFor != nextTurn && value > hope ){
hope = value;
}
}
}
return hope;
}
where the function be called
function perfectMove(){
var state = status.getState();
var winner = status.detectWin(state);
if (winner == 0){
var moves = getLegalMoves(state);
//Because the AI is unbeatable, so this is the minimum scenario
var hope = -999;
var goodMoves = []
//var is = []
//not blank or just one scenario
if (goodMoves.length == 0){
for (var i=0; i<9; i++){
//for these legal move
if (moves.indexOf(i)> -1) {
var value = moveValue(state, i, turn, turn, 1);
if (value > hope){
hope = value;
goodMoves = [];
}
//get all the possible best move
if (hope == value){
goodMoves.push(i);
}
}
}
}
moveRandom(goodMoves);
}
}
in the moveValue
function, I console.log the state and istate, I found that state and istate
change at the same time which is so beyond my understand about program, and when the recursion
return the state remain the same (doesn't get back to the previous call stack value)
getState
is, I create the cells in a file and using require.js to inject everytime I want to use it.
function getState(){
var state = [];
for (var i=0; i<9; i++){
state.push(cells[i].value)
}
return state;
}
stateMove
function is here, and firstPlayer, secondPlayer is the same way with cells
function stateMove(state, move, nextTurn){
var value = firstPlayer;
if (nextTurn == -1) value = secondPlayer;
state[move] = value
return state
}