I’m working on the Game of Life project. Mostly done but I am having difficult in implementing the game logic in componentDidUpdate.
I have a 2D array that serves as the game board. I want to iterate through the 2D array and check the status of each array element (individual board square) and see if it is “alive” in the Game of Life sense.
The algorithm for determining if an individual square is “alive” or not is as follows:
// Compare current square in array to each of the following neighboring squares:
[x][y - 1];
[x + 1][y - 1];
[x - 1][y];
[x + 1][y];
[x - 1][y + 1];
[x][y + 1];
[x + 1][y + 1];
I need to compare the current 2D array element to each of those neighboring squares. Then I figure I would create a tally variable and keep track of how many of it’s neighbors are alive or dead.
I’d keep the tally in a variable and then have if/else statements that handle whether or not that individual square lives on, dies, or reproduces.
The problem is my componentDidUpdate function is running into errors. I am not properly iterating through the 2D array. Been stuck on this for a while and I think I’m overthinking it. Any pointers would be helpful.
The project on is Codesandox and here is the particular function that I’m having trouble with:
// Should apply Game of Life rules and decide with squares are alive/dead every time the board is updated
componentDidUpdate = (prevProps, prevState) => {
//console.log('PrevState is : ' + prevProps, prevState);
const oldBoard = this.state.board;
const newBoard = this.state.nextBoard;
console.log('oldBoard ' + oldBoard);
console.log('newBoard ' + newBoard);
// Checks that board has changed and prevents infinite loop in componentDidUpdate
for(let x = 0; x < this.state.boardHeight; x++) {
for(let y = 0; y < this.state.boardWidth; y++) {
let neighborCount = 0;
// Game of Life logic pertaining to squares being alive/dead
neighborCount += oldBoard[x - 1][y - 1];
neighborCount += oldBoard[x][y - 1];
neighborCount += oldBoard[x + 1][y - 1];
neighborCount += oldBoard[x - 1][y];
neighborCount += oldBoard[x + 1][y];
neighborCount += oldBoard[x - 1][y + 1];
neighborCount += oldBoard[x][y + 1];
neighborCount += oldBoard[x + 1][y + 1];
console.log('neighborCount ' + neighborCount[x]);
// If square has 2 live neighbors it stays alive
if(neighborCount == 2) {
newBoard[x][y] = oldBoard[x][y];
}
// If square has exactly 3 neighbors a new life square is born
else if (neighborCount == 3) {
newBoard[x][y] = 1;
}
// Is square has more than 3 live neighbors it dies
else if(neighborCount > 3){
newBoard[x][y] = 0;
}
}
}
if(newBoard !== oldBoard) {
// after applying rules set the nextBoard
this.setState({ board: newBoard });
}
}
I get an error that says these blocks neighborCount += oldBoard[x - 1][y - 1];
of code are undefined.
I’ve also unsuccessfully made a Stackoverflow post for this question.