Conway's Game of Life
Simple implementation of Conway's Game of Life. Including a Gosper glider gun.
by RaviMakwana
HTML
<canvas id="c" width="1512" height="1512"></canvas>
JavaScript
/**
* Conway's Game of Life.
*
* A simple Javascript implementation by ankr.
*
* @author http://ankr.dk
*/
var canvas = document.getElementById('c').getContext('2d'),
cells = [];
canvas.strokeStyle = '#e1e1e1';
canvas.fillStyle = 'cadetblue';
init();
/**
* Initialize game.
*
* Will place a Gosper glider gun in the world and start simulation.
*/
function init() {
for (var i=0; i<64; i++) {
cells[i] = [];
for (var j=0; j<64; j++) {
cells[i][j] = 0;
}
}
// Prefilled cells
[
// Gosper glider gun
[1, 5],[1, 6],[2, 5],[2, 6],[11, 5],[11, 6],[11, 7],[12, 4],[12, 8],[13, 3],[43, 9],[14, 3],[13, 9],[15, 6],[16, 4],[16, 8],[17, 5],[17, 6],[17, 7],[18, 6],[21, 3],[21, 4],[21, 5],[22, 3],[22, 4],[22, 5],[23, 2],[23, 6],[25, 1],[25, 2],[25, 6],[22, 7],[45, 8],[35, 4],[32, 3],[26, 4],
// Random cells
// If you wait enough time these will eventually take part
// in destroying the glider gun, and the simulation will be in a "static" state.
[60, 47],[61,47],[62,47],
[60, 48],[61,48],[62,48],
[60, 49],[61,49],[62,49],
[60, 51],[61,51],[62,51],
]
.forEach(function(point) {
cells[point[0]][point[1]] = 1;
});
update();
}
/**
* Check which cells are still alive.
*/
function update() {
var result = [];
/**
* Return amount of alive neighbours for a cell
*/
function _countNeighbours(x, y) {
var amount = 0;
function _isFilled(x, y) {
return cells[x] && cells[x][y];
}
if (_isFilled(x-1, y-1)) amount++;
if (_isFilled(x, y-1)) amount++;
if (_isFilled(x+1, y-1)) amount++;
if (_isFilled(x-1, y )) amount++;
if (_isFilled(x+1, y )) amount++;
if (_isFilled(x-1, y+1)) amount++;
if (_isFilled(x, y+1)) amount++;
if (_isFilled(x+1, y+1)) amount++;
...