I am going through an exercise to recreate Conway's Game of Life and I have a basic strategy and I'm still very much in the "making it work" stage, so I know this looks pretty funny.
The problem I'm running up against right now is that I'm trying iterate through the 2-D array and each time, call the functions that determine whether the cells live or die. This is the last block of code which is returning 'undefined' for 'col'.
The functions work when called outside the loop (with variables assigned to row and col).
However, when I try and call the functions inside the loop, I get undefined values. I'm assuming this is an issue of scope, but I'm not sure exactly how to fix it.
Here is the code:
// this is the world that is being calculated
var world = [
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 1, 0],
[0, 1, 0, 1, 0],
[0, 0, 0, 0, 0]
];
// this is where the new calculated values are stored until they are ready to
// be transferred back to the first array: world
var tempWorld = [
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]
];
function getNeighbors(row, col) {
// variables that get the values of the 8 neighboring cells
var currentCell = world[row][col];
var upperLeftCorner = world[row - 1][col - 1];
var above = world[row - 1][col];
var upperRightCorner = world[row - 1][col + 1];
var left = world[row][col - 1];
var right = world[row][col + 1];
var bottomLeft = world[row + 1][col - 1];
var bottom = world[row + 1][col];
var bottomRight = world[row + 1][col + 1];
// this variable adds the neighboring cells together
var totalNumberOfNeighbors = upperLeftCorner + above + upperRightCorner + left + right + bottomLeft + bottom + bottomRight
return totalNumberOfNeighbors;
};
// test to confirm that getNeighbors is working
console.log("value of getNeighbors is: " + getNeighbors(row, col));
function deadCellsLiveOrDie (row, col) {
// Rule to make dead cells living
if (world[row][col] === 0) {
if (getNeighbors(row, col) === 3) {
tempWorld[row][col] = 1;
}
}
};
deadCellsLiveOrDie(row, col);
livingCellsLiveOrDie(row, col);
function livingCellsLiveOrDie (row, col) {
// Rule to determine if living cells die or live
if (world[row][col] === 1) {
if ((getNeighbors(row, col) === 2) || (getNeighbors(row, col) === 3)) {
tempWorld[row][col] = 1;
} else tempWorld[row][col] = 0
}
};
// test to confirm that rules of life work for a cell
console.log("tempWorld row, col is: " + tempWorld[row][col]);
// iterate over the 2-D array
for (row = 0; row < world.length; ++ row)
{
var col;
for (col = 0; col < world[row].length; ++ col) {
deadCellsLiverOrDie(row, col);
livingCellsLiveOrDie(row, col);
}
}
row
andcol
variables that were never initialized. Also, the loop in the last block would initializerow
as global. Furthermore, you misspelleddeadCellsLiveOrDie
in your loop.getNeighbors
method does not have any boundary check, i.e. it will try to access the array index-1
.