xxxxxxxxxx
const agentCount = 1000;
const agentArray = [];
const agentSpeed = 5;
let world;
function setup() {
createCanvas(windowWidth, windowHeight);
noStroke();
init();
}
function init() {
background(0);
world = array2d();
agentArray.length = 0;
for (let i = 0; i < agentCount; i++) {
agentArray.push(agent());
}
}
mouseClicked = () => init();
function draw() {
for (let i = 0; i < agentSpeed; i++) {
agentArray.forEach((agent) => agent.next());
}
}
function* agent() {
const colour = "#" + hex(random(), 6);
const x = floor(random(width));
const y = floor(random(height));
const stack = [{ x, y }];
world.set(x, y, colour);
const directions = [
{ dx: +1, dy: +1 },
{ dx: 0, dy: +1 },
{ dx: -1, dy: 0 },
{ dx: 0, dy: -1 },
{ dx: +1, dy: 0 },
];
random(2) < 1 && directions.push(directions.shift());
while (stack.length) {
const { x, y } = stack.pop();
for (const { dx, dy } of directions) {
if (random() < 0.12) continue;
const newX = (x + dx + width) % width;
const newY = (y + dy + height) % height;
if (!world.canMoveTo(newX, newY)) continue;
stack.push({ x: newX, y: newY });
world.set(newX, newY, colour);
yield;
}
}
}
function array2d() {
const array = Array.from({ length: width }, () => Array(height).fill(false));
return {
canMoveTo: (x, y) => {
return array[x][y] === false;
},
set: (x, y, colour) => {
array[x][y] = true;
fill(colour);
rect(x, y, 1);
},
};
}