Skip to content

Instantly share code, notes, and snippets.

@faddah
Last active August 29, 2015 14:25
Show Gist options
  • Save faddah/d5f83736df51f07ff6a9 to your computer and use it in GitHub Desktop.
Save faddah/d5f83736df51f07ff6a9 to your computer and use it in GitHub Desktop.
my version of Lea Verou's game of life life.js file
(function() {
var _ = self.Life = function(seed) {
this.seed = seed;
this.height = seed.length;
this.width = seed[0].length;
this.prevBoard = [];
this.board = cloneArray(seed);
};
_.prototype = {
next: function() {
this.prevBoard = cloneArray(this.board);
for(var y = 0; y < this.height; y++) {
for(var x = 0; x < this.width; x++) {
var neighbors = this.aliveNeighbors(this.prevBoard, x, y);
// console.log("y is: " + y, "x is: " + x, ": " + neighbors);
var alive = !!this.board[y][x];
if(alive) {
if(neighbors < 2 || neighbors > 3) {
this.board[y][x] = 0;
}
}
else {
if(neighbors === 3) {
this.board[y][x] = 1;
}
}
}
}
},
aliveNeighbors: function(array, x, y) {
var prevRow = array[y - 1] || [];
var nextRow = array[y + 1] || [];
var neighbors = [
prevRow[x - 1], prevRow[x], prevRow[x + 1],
array[y][x - 1], array[y][x + 1],
nextRow[x - 1], nextRow[x], nextRow[x + 1]
].reduce(function(prev, cur) {
return prev + +!!cur;
}, 0);
},
toString: function() {
return this.board.map(function(row) { return row.join(' ') }).join('\n');
}
};
// Helpers
// Warning: only clones 2D arrays
function cloneArray(array) {
return array.slice().map(function(row) { return row.slice(); });
}
})();
var game = new Life([
[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 0, 0]
]);
console.log(game + '');
game.next();
console.log(game + '');
game.next();
console.log(game + '');
@damluar
Copy link

damluar commented Jul 19, 2015

You forgot to return the result of the function aliveNeighbors. Use return [ instead of var neighbors = [.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment