xxxxxxxxxx
const pixelSize = 3;
const agentCount = 12;
const agentArray = [];
const agentSpeed = 20;
let world;
function setup() {
createCanvas(windowWidth, windowHeight);
colorMode(HSB, 1, 1, 1);
noStroke();
init();
}
function init() {
background("white");
world = array2d();
for (let i = 0; i < agentCount; i++) {
agentArray[i] = agent();
}
}
mouseClicked = () => init();
function draw() {
scale(pixelSize);
for (let i = 0; i < agentSpeed; i++) {
agentArray.forEach((agent) => agent.next());
}
}
function* agent() {
const colour = "#" + hex(random(0xffffff), 6);
const x = floor(random(world.maxX));
const y = floor(random(world.maxY));
const stack = [{ x, y }];
world.set(x, y, colour);
while (stack.length) {
const current = stack.pop();
const directions = shuffle([
{ dx: +1, dy: 0 },
{ dx: 0, dy: +1 },
{ dx: -1, dy: 0 },
{ dx: 0, dy: -1 },
]);
for (const { dx, dy } of directions) {
const x = current.x + dx;
const y = current.y + dy;
if (!world.canMoveTo(x, y)) continue;
stack.push({ x, y });
world.set(x, y, colour);
yield;
}
}
}
function array2d() {
const empty = false;
const filled = true;
const maxX = floor(width / pixelSize);
const maxY = floor(height / pixelSize);
const array = [];
for (let x = 0; x < maxX; x++) {
array[x] = [];
for (let y = 0; y < maxY; y++) {
array[x][y] = empty;
}
}
return {
maxX,
maxY,
canMoveTo: (x, y) =>
0 <= x && x < maxX && 0 <= y && y < maxY && array[x][y] === empty,
set: (x, y, colour) => {
array[x][y] = filled;
fill(colour);
rect(x, y, 1);
},
};
}