我试图将AI编码为井字游戏
完整代码在这里:http://jsbin.com/tiweniludoqe/10/edit?js,console,output
我试图用"分数"来保持数组。 AI可以在线上进行的可能移动:
moveScoreArray[initialMoveNum] += scoreStack.pop();
但是控制台说moveScoreArray[initialMoveNum]
未定义。这是一个逻辑错误还是JavaScript不允许将分数传递给数组,就像我在这里做的那样。
function minimax(inputBoard, player, availableMoves, steps) {
var copyBoard = inputBoard.clone();
if(availableMoves === 0) {
console.log("tie");
scoreStack.push(0);
} else if(player < 0) {
for(var i = 0; i < board.length; i++) {
for(var j = 0; j < board.length; j++) {
if(copyBoard[i][j] !== 0) {
j++;
} else {
copyBoard[i][j] = -1;
if (checkForWin(copyBoard) < 0) {
scoreStack.push(-10);
//free up board for next for-loop iteration.
copyBoard[i][j] = 0;
} else {
minimax(copyBoard, 1, availableMoves - 1, steps++);
//free up the board for next for-loop iteration.
copyBoard[i][j] = 0;
}
}
}
}
//after finding all outcomes check if we're back to the initial step
//if this is one of the AI's initial moves then add it's score to an Array of scores.
if(availableMoves - steps === 1) {
var initialMoveNum = moveScoreArray.length;
while(scoreStack.length !== 0) {
moveScoreArray[initialMoveNum] += scoreStack.pop();
//console.log(scoreStack[scoreStack.length - 1]);
}
console.log("moveScoreArray value of initial move x: " + moveScoreArray[initialMoveNum]);
}
} else if(player > 0) {
for(var i = 0; i < board.length; i++) {
for(var j = 0; j < board.length; j++) {
if(copyBoard[i][j] !== 0) {
j++;
} else {
copyBoard[i][j] = 1;
if (checkForWin(copyBoard) > 0) {
scoreStack.push(10);
copyBoard[i][j] = 0;
} else {
minimax(copyBoard, -1, availableMoves - 1, steps++);
copyBoard[i][j] = 0;
}
}
}
}
}
}
全局变量:
//keep track of the number of moves made
var moveNumber = 0;
//create a game board
var board = [];
//populate the board with arrays filled with zeroes
var board = [rOne = initArray(3, 0),
rTwo = initArray(3, 0),
rThree = initArray(3, 0)];
//number of total available moves
var totalMoves = board.length * board.length;
//fill an array with zeroes
function initArray(length, value) {
var arr = [], i = 0;
arr.length = length;
for(i; i < length; i++) {
arr[i] = value;
}
return arr;
}
//an array used as a stack to hold scores for moves
var scoreStack = [];
//an array to keep scores for each initial move the AI can make
var moveScoreArray = [];
答案 0 :(得分:0)
如果
var ar = [1,2,3]
ar[ar.length] += 3;
永远无法运作
var initialMoveNum = moveScoreArray.length;
moveScoreArray[initialMoveNum] += scoreStack.pop();
永远不会奏效。
答案 1 :(得分:0)
未初始化的数组包含未定义的值。因此,向其添加数字会导致NaN。例如:
var ar = [];
var ar[ar.length] += "someText";
console.log(ar[0]);
导致输出“undefinedsomeText”
var ar = [];
var ar[ar.length] += 33;
console.log(ar[0]);
导致NaN