Game of life

Game of life in the canvas

by Oliver Caldwell

HTML

<canvas id='canvas' width='500' height='500'></canvas>
<input type='submit' id='start' value='Start' />
<input type='submit' id='stop' value='Stop' />

CSS

html, body {
    width: 100%;
    margin: 0;
    padding: 0;
    background-color: #888888;
}

canvas {
    margin: 30px auto;
    height: 500px;
    width: 500px;
    display: block;
    background-color: #FFFFFF;
}

input {
    margin: 10px auto;
    width: 150px;
    display: block;
}

JavaScript

var canvas = $('canvas').getContext('2d'),
    cells = [],
    x = null,
    y = null,
    alive = null,
    size = 10, // This is how big the squares are, 10 is good, 1 would crash your browser
    amount = 500 / size,
    edgeAmount = Math.floor(499 / size),
    interval = null,
    drawX = null,
    drawY = null,
    e = null,
    settings = {
        toLive: 3,
        toDie: {
            min: 2,
            max: 3
        }
    };

// Initialise the cells
for(x = 0; x < amount; x++) {
    cells[x] = [];
    
    for(y = 0; y < amount; y++) {
        cells[x][y] = false;
    }
}

/**
 * Draws the grid
 */
function lines() {
    canvas.fillStyle = 'rgb(150, 150, 150)';
    
    for(x = 0; x < amount; x++) {
        canvas.fillRect(x * size, 0, 1, 500);
        canvas.fillRect(0, x * size, 500, 1);
    }
    
    canvas.fillStyle = 'rgb(0, 0, 0)';
}

/**
 * All logic for every frame
 */
function frame() {
    // Loop over the cells
    for(x = 1; x < amount - 1; x++) {
        for(y = 1; y < amount - 1; y++) {
            // Count the live ones
            alive = 0;
            
            if(cells[x - 1][y]) {
                alive++;
            }
            
            if(cells[x - 1][y - 1]) {
                alive++;
            }
            
            if(cells[x][y - 1]) {
                alive++;
            }
            
            if(cells[x + 1][y - 1]) {
                alive++;
            }
            
            if(cells[x + 1][y]) {
                alive++;
            }
            
            if(cells[x + 1][y + 1]) {
                alive++;
            }
            
            if(cells[x][y + 1]) {
                alive++;
            }
            
            if(cells[x - 1][y + 1]) {
                alive++;
            }
            
            // If less than two live neighbours or more than three, die
            if(alive < settings.toDie.min || alive > settings.toDie.max) {
                cells[x][y] = false;
         ...