Skip to content

Instantly share code, notes, and snippets.

@schani
Created August 13, 2021 14:02
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 schani/05549e6d3d4895d4c3794039c0146756 to your computer and use it in GitHub Desktop.
Save schani/05549e6d3d4895d4c3794039c0146756 to your computer and use it in GitHub Desktop.
<html>
<head>
<title>Game of Life</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<canvas id="canvas" width="300" height="300"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
// draw 2d array of booleans to canvas efficiently
function draw(canvas, array) {
var ctx = canvas.getContext("2d");
var w = canvas.width;
var h = canvas.height;
// cells is a 2D array of booleans
function drawCells(ctx, cells) {
ctx.clearRect(0, 0, 300, 300);
for (var i = 0; i < cells.length; i++) {
for (var j = 0; j < cells[i].length; j++) {
if (cells[i][j]) {
ctx.fillStyle = "black";
} else {
ctx.fillStyle = "white";
}
ctx.fillRect(j, i, 1, 1);
}
}
}
function gameOfLifeStep(cells) {
var nextCells = new Array(cells.length);
for (var i = 0; i < cells.length; i++) {
nextCells[i] = new Array(cells[i].length);
for (var j = 0; j < cells[i].length; j++) {
var liveNeighbors = 0;
for (var k = -1; k <= 1; k++) {
for (var l = -1; l <= 1; l++) {
if ((k === 0 && l === 0) || i + k < 0 || i + k >= cells.length || j + l < 0 || j + l >= cells[i].length) {
continue;
}
if (cells[i + k][j + l]) {
liveNeighbors++;
}
}
}
if (cells[i][j]) {
if (liveNeighbors < 2) {
nextCells[i][j] = false;
} else if (liveNeighbors > 3) {
nextCells[i][j] = false;
} else {
nextCells[i][j] = true;
}
} else {
if (liveNeighbors == 3) {
nextCells[i][j] = true;
} else {
nextCells[i][j] = false;
}
}
}
}
return nextCells;
}
// init cells randomly
var cells = [];
for (var i = 0; i < 300; i++) {
cells[i] = [];
for (var j = 0; j < 300; j++) {
cells[i][j] = Math.random() > 0.7;
}
}
var canvas = $("#canvas")[0];
var ctx = canvas.getContext("2d");
var width = canvas.width;
var height = canvas.height;
var cellX, cellY;
var cellColor = "#111";
var cellColorActive = "#444";
console.log("script");
// draw on each animation frame
requestAnimationFrame(function draw() {
drawCells(ctx, cells);
var nextCells = gameOfLifeStep(cells);
cells = nextCells;
requestAnimationFrame(draw);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment