Skip to content

Instantly share code, notes, and snippets.

@joehakimrahme
Created September 18, 2012 23:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joehakimrahme/3746671 to your computer and use it in GitHub Desktop.
Save joehakimrahme/3746671 to your computer and use it in GitHub Desktop.
Conway's Game of life
function draw_matrix(context, matrix, startx, starty, cellsize)
{
var x = startx;
var y = starty;
var colors = ['yellow', 'red'];
for (var i=0; i<matrix.length; ++i) {
line = matrix[i];
for (var j=0; j<line.length; ++j) {
context.beginPath();
context.rect(x, y, cellsize, cellsize);
context.fillStyle = colors[line[j]];
context.fill();
x += cellsize;
}
x = startx;
y += cellsize;
}
}
function random_matrix(width, length)
{
matrix = [];
for (var i=0; i<length; ++i) {
line = [];
for (var j=0; j<width; ++j)
line.push(Math.floor(Math.random()*2))
matrix.push(line);
}
return matrix;
}
function next_matrix(matrix) {
newmatrix = [];
firstline = [];
lastline = [];
for (var _=0; _<matrix.length; ++_){
firstline.push(0);
lastline.push(0);
}
newmatrix.push(firstline);
for (var i=1; i<matrix.length-1; ++i) {
newline = [];
newline.push(0);
line = matrix[i];
for (var j=1; j<matrix.length-1; ++j) {
cell = matrix[i][j];
neighbours = matrix[i-1][j-1] + matrix[i-1][j] + matrix[i-1][j+1]+
matrix[i][j-1] + matrix[i][j+1] +
matrix[i+1][j-1] + matrix[i+1][j] + matrix[i+1][j+1];
newvalue=cell;
if (cell === 1) {
if (neighbours < 2)
newvalue = 0;
if (neighbours > 3)
newvalue = 0;
if (neighbours === 2 || neighbours === 3)
newvalue = 1;
}
else {
if (neighbours === 3)
newvalue = 1;
}
newline.push(newvalue);
}
newline.push(0);
newmatrix.push(newline);
}
newmatrix.push(lastline);
return newmatrix;
}
var matrix = random_matrix(10, 10);
function main(context, canvas){
context.clearRect(0,0,canvas.width, canvas.height);
draw_matrix(context, matrix, 50,50, 20);
matrix = next_matrix(matrix);
}
window.onload = function () {
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
setInterval(main, 1000, context, canvas);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment