l-emi l-emi - 2 months ago 13
Javascript Question

"Maximum call stack size exceeded" error

So I'm trying to make a Tic Tac Toe game following this tutorial. When I run it and look at the Chrome dev tools, it says

Uncaught RangeError: Maximum call stack size exceeded
, and point me to the line of this function:

var State = function(oldState) {
this.turn = "";
this.oMovesCount = 0;
this.result = "still running";
this.board = [];


//get the information from the previous state to use it for following states
if (typeof oldState !== "undefined") {
var len = oldState.board.length;
this.board = new Array(len);
for (var i = 0; i < len; i++) {
this.board[i] = oldState.board[i];
}
this.oMovesCount = oldState.oMovesCount;
this.result = oldState.result;
this.turn = oldState.turn;
}

//change to X or O accordingly
this.advanceTurn = function() {
//Was it just X's turn? If so, change to O. If not, change to X.
this.turn = this.turn === "x" ? "o" : "x";
};

//checks for victory
this.result = "still running";
this.isTerminal = function() {
var B = this.board;

//check to see if there has been a victory
//check rows
for(var i = 0; i <= 6; i = i + 3) {
if(B[i] !== "E" && B[i] === B[i+1] && B[i+1] == B[i+2]) {
this.result = B[i] + " has won!";
return true;
}
}
//check columns
for(var i = 0; i <= 2 ; i++) {
if(B[i] !== "E" && B[i] === B[i+3] && B[i+3] === B[i+6]) {
this.result = B[i] + " has won!";
return true;
}
}
//check diagonals
for(var i = 0, j = 4; i <= 2 ; i = i + 2, j = j - 2) {
if(B[i] !== "E" && B[i] == B[i+j] && B[i+j] === B[i + 2*j]) {
this.result = B[i] + " has won!";
return true;
}
};

//if there have been no wins, check the number of empty cells
//if there are no empty cells, it's a draw
var available = this.emptyCells();
if (available.length == 0) {
this.result = "draw";
return true;
}
else {
return false;
}
};
//keeps track of how many empty cells there are on the board
this.emptyCells = function() {
var indxs = [];
for (var i = 0; i < 9; i++) {
if (this.board[i] === "E") {
indxs.push(i);
}
}
return indxs;
}
};


I don't understand why. Here's the full code, the error shows up when you click
Play
then
OK
then on one of the cells. Here it is hosted on another site if it helps.

Thank you!

Answer

There is a typo in the AIAction method:

this.oMovesPosition = pos; //the position on the board where the O would be placed
this.minimaxVal = 0; //the minimax value of the state that the action leads to

this.applyTo = function(state) {
    var next = new State(state);

    //if the current turn in the current state is O, increment .oMovesCount
    next.board[this.movePosition] = state.turn;
    if (state.turn === "o") {
        next.oMovesCount++;
    }
    next.advanceTurn();
    return next;
};

Notice the this.oMovesPosition in the first line, but then the applyTo method refers to this.movePosition instead.

Comments