Conway's Life

A version of CGoL I made as a learning exercise.

by Vince Aggrippino

HTML

<canvas id="myCanvas" width="400" height="400" style="border:1px solid #000000;"></canvas>

JavaScript

var gridHeight = 400;
	var gridWidth = 400;
	var theGrid = createArray(gridWidth);
	var mirrorGrid = createArray(gridWidth);
	var c = document.getElementById("myCanvas");
	var ctx = c.getContext("2d");
	ctx.fillStyle = "#FF0000";

	fillRandom(); //create the starting state for the grid by filling it with random cells

	tick(); //call main loop

	//functions
	function tick() { //main loop
	    console.time("loop");
	    drawGrid();
	    updateGrid();
	    console.timeEnd("loop");
	    requestAnimationFrame(tick);
	}

	function createArray(rows) { //creates a 2 dimensional array of required height
	    var arr = [];
	    for (var i = 0; i < rows; i++) {
	        arr[i] = [];
	    }
	    return arr;
	}

	function fillRandom() { //fill the grid randomly
	    for (var j = 100; j < gridHeight - 100; j++) { //iterate through rows
	        for (var k = 100; k < gridWidth - 100; k++) { //iterate through columns
	            theGrid[j][k] = Math.round(Math.random());
	        }
	    }
	}

	function drawGrid() { //draw the contents of the grid onto a canvas
var liveCount = 0;
	    ctx.clearRect(0, 0, gridHeight, gridWidth); //this should clear the canvas ahead of each redraw
	    for (var j = 1; j < gridHeight; j++) { //iterate through rows
	        for (var k = 1; k < gridWidth; k++) { //iterate through columns
	            if (theGrid[j][k] === 1) {
	                ctx.fillRect(j, k, 1, 1);
                    liveCount++;
                    
	            }
	        }
	    }
        console.log(liveCount/100);
	}

	function updateGrid() { //perform one iteration of grid update
       
	    for (var j = 1; j < gridHeight - 1; j++) { //iterate through rows
	        for (var k = 1; k < gridWidth - 1; k++) { //iterate through columns
	            var totalCells = 0;
	            //add up the total values for the surrounding cells
	            totalCells += theGrid[j - 1][k - 1]; //top left
	            totalCells += theGrid[j - 1][k]; //top center
	            totalCells +=...