xxxxxxxxxx
const DEAD = 0;
const ALIVE = 1;
const n = 300;
const brushThickness = 5;
let cells;
let g;
function setup() {
p5.disableFriendlyErrors = true;
const m = min(windowWidth, windowHeight);
createCanvas(m, m);
cells = new Uint8Array(n * n).fill(DEAD);
g = createGraphics(n, n);
g.background(0).pixelDensity(1).loadPixels();
}
function draw() {
background("white");
brush();
let next = new Uint8Array(cells);
for (let y = 1; y < n - 1; y++) {
for (let x = 1; x < n - 1; x++) {
const i = x + y * n;
const sum0 =
cells[i + 1]
+ cells[i - 1]
+ cells[i - n]
+ cells[i + n];
const sum1 =
+ cells[i - 1 - n]
+ cells[i - 1 + n]
+ cells[i + 1 - n]
+ cells[i + 1 + n];
const all = sum0 + sum1;
const status = cells[i]
? all < 1 || all > 4
: sum0 > sum1 * 2;
next[i] = status;
g.pixels[i * 4 + 3] = status ? 0 : 255;
}
}
cells = next;
g.updatePixels();
image(g, 0, 0, width, height);
}
function brush() {
let mx = ceil(map(mouseX, 0, width, 0, n - 1));
let my = ceil(map(mouseY, 0, height, 0, n - 1));
const b = brushThickness;
for (dy = -b; dy <= b; dy++) {
for (dx = -b; dx <= b; dx++) {
let d = sqrt(dx ** 2 + dy ** 2);
if (d > b) continue;
let x = mx + dx;
let y = my + dy;
if (x < 0 || x >= n || y < 0 || y >= n) continue;
cells[x + y * n] = mouseIsPressed
? random(2) < 1 ? ALIVE : DEAD
: ALIVE;
}
}
}