【发布时间】:2017-04-27 15:31:44
【问题描述】:
var chessboard = [[2,1,0],[2,1,0],[0,0,0]];
function checkwins(array){}//The function is too long.I will explain here.It decides
//whether there is a winner.If there is a winner it will return 1 or 0
//(1 stand for number 2's win on the chessboard 0 stands for number 1's win)If there is no winner, it will return 2)
function score(board,depth){
if(checkwins(board)===0)return depth-10;
if(checkwins(board)==1)return 10-depth;
else return 0;
}
function count_move(board,depth,current_turn){
board = board.slice();
var possible_moves = possible_movements(board);
if(checkwins(board)!=2|| possible_moves.length===0)return score(board,depth);
var move_score;
var new_board;
depth++;
if(current_turn===0)move_score = -1000;
else move_score = 1000;
if(!current_turn){
possible_moves.forEach(function(possible_location){
var new_board = board.slice();
new_board[possible_location[0]][possible_location[1]] = 1;
var current_score = count_move(new_board,depth,1);
if(current_score > move_score)move_score = current_score;
});
}else{
possible_moves.forEach(function(possible_location){
var new_board = board.slice();
new_board[possible_location[0]][possible_location[1]] = 2;
var current_score = count_move(new_board,depth,0);
if(current_score < move_score)move_score = current_score;
});
}
return move_score;
}
function ai(board){
var possible_moves = possible_movements(board);
var best_move;
var move_score = -1000;
var current_score ;
possible_moves.forEach(function(move){
var next_board = board.slice();
next_board[move[0]][move[1]] = 1;
current_score = count_move(next_board,0,1);
console.log("Current Move :"+move+"\nCurrent Score :"+current_score+'\nCurrent Board :'+next_board+'\n');
if(current_score > move_score){
move_score = current_score;
best_move = move;
}
});
console.log(best_move);
}
console.log(chessboard);
ai(chessboard);
console.log(chessboard);
我正在使用Minimax算法编写井字游戏Ai。我目前在使用javascript时遇到了一些问题。我发现当我将数组作为参数传递给函数然后在函数中对其进行修改时。它会改变数组传递甚至在函数之外。控制台结果如下:
[ [ 2, 1, 0 ], [ 2, 1, 0 ], [ 0, 0, 0 ] ]
Current Move :0,2
Current Score :-8
Current Board :2,1,1,2,1,2,2,2,2
Current Move :1,2
Current Score :10
Current Board :2,1,1,2,1,1,2,2,2
Current Move :2,0
Current Score :-10
Current Board :2,1,1,2,1,1,1,2,2
Current Move :2,1
Current Score :-10
Current Board :2,1,1,2,1,1,1,1,2
Current Move :2,2
Current Score :-10
Current Board :2,1,1,2,1,1,1,1,1
[ 1, 2 ]
[ [ 2, 1, 1 ], [ 2, 1, 1 ], [ 1, 1, 1 ] ]
然后发现好像用了
new_array = array.slice()
函数内部应该避免它,所以我将它添加到我的函数中。结果仍然没有改变。我在这里很困惑。
【问题讨论】:
-
您能否准确描述您正在谈论的阵列,因为我无法理解确切的问题。您可能正在对全局变量进行其他操作?
-
第1行有一个叫做chessboard的数组,我用它来测试函数。
标签: javascript arrays parameter-passing minimax