Building Game of Life here and working on a function to loop through all the neighbors of a cell and sum up the scores (each cell is 0 or 1). Board is represented by a 2-dimensional array. Normally a cell has 8 neighbours. The problem is that cells in the corner of the board have only 3 neighbors and cells on the side have 5. If I loop through the array using the code below, some neighbors return undefined in the array. I want to convert undefined to 0 and use that to sum up the scores, but i get the error:
Uncaught TypeError: Cannot read property '-1' of undefined
Thanks for your help!
var array = [
[0,0,1,0,1,0,1,0,1,1],
[0,0,1,0,1,0,1,0,1,1],
[0,0,1,0,1,0,1,0,1,1],
[0,0,1,0,1,0,1,0,1,1],
[0,0,1,0,1,0,1,0,1,1],
[0,0,1,0,1,0,1,0,1,1],
[0,0,1,0,1,0,1,0,1,1],
[0,0,1,0,1,0,1,0,1,1],
[0,0,1,0,1,0,1,0,1,1],
[0,0,1,0,1,0,1,0,1,1]
]
for(var i=0; i < array.length; i++){
for(var j=0; j < array[i].length; j++){
var totalScore = 0;
var scores = [
//i = row in loop
//j = column nested loop
array[i-1][j-1],
//upper left corner
array[i-1][j],
//top side
array[i-1][j+1],
//upper right corner
array[i][j-1],
//left side
array[i][j+1],
//right side
array[i+1][j-1],
//bottom left corner
array[i+1][j],
//bottom side
array[i+1][j+1]
//bottom right corner
];
scores.forEach(function(item){
var score = item;
if(score === "undefined"){
score = 0;
}
totalScore += score;
})
console.log(totalScore);
}
}
@Matt Timmermans proposition solves a lot of problems. If you want to keep existing structure, consider next approach:
Form code describing cell position in the matrix (I assume boolean is evaluated as 0/1):
Build array containing all possible combinations (size 16, binary
0b0000..0b1111
) of neighbour shifts:For every cell calculate code and use corresponding array of shifts