JSFiddle - React, Tailwind, and code Playground

by eurica

HTML

<canvas id="board" style="border:1px solid red;"></canvas>
<!--
Simple game of life

-->

JavaScript

console.log(new Date())
var seed = 1;
function random() {
    var x = Math.sin(seed++) * 10000;
    return x - Math.floor(x);
}

var STATE = 1;
var NEWSTATE = 2;
var colors = ["#000088", "#ccccff"]
var width = 128;
var pixelSize = 4
var canvas = document.getElementById('board');
canvas.width = width * pixelSize;
canvas.height = width * pixelSize;
var context = canvas.getContext('2d');

var size = width * width;
var buffer = new ArrayBuffer(size);
var int8View = new Int8Array(buffer);


    for (x = 4; x < width-4; x++) {
        for (y = 4; y < width-4; y++) {
            i = y * width + x
    int8View[i] |= (random() > .9) ? STATE + NEWSTATE : 0;
        }
        }



drawcells = function () {
    cs = 0
    ns = 0
    es = 0
    changed = 0
    for (x = 0; x < width; x++) {
        for (y = 0; y < width; y++) {
            me = y * width + x
            currentstate = int8View[me] & STATE
            cs += currentstate
            newstate = (int8View[me] & NEWSTATE) >> 1
            ns += newstate
            int8View[me] &= ~STATE //reset the bit
            int8View[me] |= newstate //set the new state bit
            es += int8View[me] & STATE
            if (newstate != currentstate) changed += 1
            if (newstate != currentstate || true) { //dirty, paint
                if(int8View[me] & STATE) {
                    context.fillStyle = "#004488";
                } else {
                    context.fillStyle = "#ffffff";
                }

                context.fillRect(x * pixelSize, y * pixelSize, pixelSize-1, pixelSize-1);
            }
        }
    }
    console.log("From " + cs + " to " + ns + " (" + es + ") cells. Changed:" + changed)

}

cellstate = function (x, y) {
    return 0 + int8View[
    ((y + width) % width) * width + ((x + width) % width)] & 1
}

neighbors = function (x, y) {
    count = cellstate(x - 1, y - 1) + cellstate(x, y - 1) + cellstate(x + 1, y - 1) + 
        cellstate(x-1, y) + cellstate(x+1, y) + 
        cellstate(x...