我最近使用JavaScript编写的极小极大算法,但是当我执行递归,JavaScript的递归变量问题
似乎以一种不可思议的方式变量的变化,这里是代码:
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;
}
其中函数在moveValue
函数调用
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);
}
}
,我CONSOLE.LOG状态和即将状态置,我发现,状态和即将状态置在这也是让我无法同时变化了解有关程序,并在递归
回报的状态保持不变(不回到以前的调用堆栈值)
getState
是,我在文件中创建单元格并使用require.js注入每次我想要使用它。
function getState(){
var state = [];
for (var i=0; i<9; i++){
state.push(cells[i].value)
}
return state;
}
stateMove
功能在这里,并且firstPlayer,secondPlayer是相同的方式与细胞
function stateMove(state, move, nextTurn){
var value = firstPlayer;
if (nextTurn == -1) value = secondPlayer;
state[move] = value
return state
}
我怀疑你的'stateMove'功能改变'istate'阵列_in place_而不是复制。如果您为该功能添加代码,则会使问题更易于诊断。 –
嗨,@musically_ut,我添加它,谢谢你的回答 –