-
-
Save reidblomquist/0b02c31504b0016371ce to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8"> | |
<title>Faddah's Life</title> | |
<meta name="description" content="Faddah's Life"> | |
<meta name="author" content="Faddah"> | |
<script src="https://rawgit.com/faddah/d5f83736df51f07ff6a9/raw/5a764d3041ceada28bc4dac9f8bbfb0e959d6943/life.js"></script> | |
<!--[if lt IE 9]> | |
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> | |
<![endif]--> | |
</head> | |
<body> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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 + ''); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment