const canvas = document.querySelector('canvas');
const ctx = context = canvas.getContext('2d');
canvas.width = 20;
canvas.height = 10;
ctx.imageSmoothingEnabled = false;
let i = ctx.getImageData(0, 0, canvas.width, canvas.height);
const pp = (x,y) => (x + (y*canvas.width)) * 4;
function putpixel(x, y, t) {
const s = pp(x,y);
i.data[s] = t ? 255 : 0;
i.data[s + 3] = t ? 255 : 0;
}
function getpixel(x, y) {
const s = pp(x,y);
return i.data[s] === 255;
}
for (let y = 0; y < 3; y += 1)
for (let x = 0; x < 3; x += 1)
putpixel(x + 4,y + 4,true);
//let add 2 shapes, still work?
for (let y = 0; y < 3; y += 1)
for (let x = 0; x < 3; x += 1)
putpixel(x,y,true);
ctx.putImageData(i, 0, 0);
function findPixel(active) {
while (true) {
const x = Math.trunc(Math.random() * canvas.width);
const y = Math.trunc(Math.random() * canvas.height);
const p = getpixel(x,y);
if (p === active) return {x,y, p:y*canvas.width + x};
}
}
function isValid(p, p2) {
let count = 0;
let hit = false;
const done = {};
function fill(x, y) {
const pstr = `${x}:${y}`;
if (done[pstr]) return;
if (x < 0) return;
if (x >= canvas.width) return;
if (y < 0) return;
if (y >= canvas.height) return;
if (!getpixel(x, y)) return;
count += 1;
if (!hit) {
if (p2.x === x && p2.y === y) hit = true;
}
done[pstr] = true;
fill(x -1, y - 1);
fill(x , y - 1);
fill(x +1, y - 1);
fill(x -1, y);
fill(x +1, y);
fill(x -1, y + 1);
fill(x , y + 1);
fill(x +1, y + 1);
}
fill(p.x, p.y);
return count === 9 && hit;
}
function evolve() {
i = ctx.getImageData(0, 0, canvas.width, canvas.height);
const movePixel = findPixel(true);
const otherPixel = findPixel(true);
if (movePixel.p !== otherPixel.p) {
const rndPixel = findPixel(false);
putpixel(movePixel.x, movePixel.y, false);
putpixel(rndPixel.x ,rndPixel.y, true);
if (isValid(otherPixel, rndPixel))
ctx.putImageData(i, 0, 0);
}
setTimeout(evolve, 0);
}
setTimeout(evolve, 0);
* {
padding: 0;
box-sizing: border-box;
margin: 0;
}
html {
height: 100%;
}
body {
background-color: black;
display: grid;
justify-content: center;
align-content: center;
height: 100%;
}
canvas {
transform: scale(19);
image-rendering: pixelated;
}
<canvas>
</canvas>