JSFiddle - React, Tailwind, and code Playground
by popsul
HTML
<canvas id="game" width=400 height=400></canvas>
<button id="start">Start</button>
CSS
canvas {
display: block;
width:400px;
height: 400px;
border-top: 1px solid black;
border-left: 1px solid black;
margin: 0 auto;
}
JavaScript
var cellWidth = 5
var rows = 80
var cols = 80
var fieldWidth = cols * cellWidth
var fieldHeight = rows * cellWidth
var gameState = []
for (var i = 0; i < cols; i++) {
for (var j = 0; j < rows; j++) {
var k = (!gameState[i] ? gameState[i] = [] : gameState[i]);
k[j] = false;
}
}
gameState[5][5] = true;
gameState[6][6] = true;
gameState[6][7] = true;
gameState[4][7] = true;
gameState[5][7] = true;
var canvas = document.getElementById("game");
var c = canvas.getContext('2d');
var filledCell = c.getImageData(0, 0, cellWidth, cellWidth);
var emptyCell = c.getImageData(0, 0, cellWidth, cellWidth);
for (var k = 0; k < cellWidth; k++) {
var start = cellWidth*4*k + ((cellWidth-1) * 4);
emptyCell.data[start] = 0;
emptyCell.data[start+1] = 0;
emptyCell.data[start+2] = 0;
emptyCell.data[start+3] = 255;
var start = 4*(cellWidth*(cellWidth-1)+k);
emptyCell.data[start] = 0;
emptyCell.data[start+1] = 0;
emptyCell.data[start+2] = 0;
emptyCell.data[start+3] = 255;
}
for (var x = 0; x < Math.pow(cellWidth, 2)*4; x+=4) {
filledCell.data[x] = 0;
filledCell.data[x+1] = 0;
filledCell.data[x+2] = 0;
filledCell.data[x+3] = 255;
}
function draw() {
c.fillStyle = "white";
c.fillRect(0, 0, fieldWidth, fieldHeight);
for (var i = 0; i< cols; i++) {
for (var j = 0; j < rows; j++) {
var filled = gameState[i][j];
var d = null;
if (filled) {
d = filledCell;
} else {
d = emptyCell;
}
c.putImageData(d, i*cellWidth, j*cellWidth);
}
}
}
/**
function __draw() {
var start = new Date().getTime();
_draw();
var end = new Date().getTime();
var time = end - start;
console.log('Execution time: ' + time);
}
*/
function countNeib (i, j) {
var count = 0;
for (var x = i-1; x <= i+1; x++) {
for (var y = j-1; y <= j+1; y++) {
if (x == i && y...