const a = tryCreateAgent();
if (a) agentArray.push(a);
agentArray.forEach((e) => e.update());
agentArray = agentArray.filter((e) => e.isInScreen());
agentArray.forEach((e) => e.show());
const agent = (x, y, w, h, direction) => ({
fill(this.direction == 0 ? color1 : color2);
rect(this.x, this.y, this.w, this.h);
return this.x < width + this.w / 2 && this.y < height + this.h / 2;
const d = this.direction;
const newx = this.x + cos(d) * step;
const newy = this.y + sin(d) * step;
const excludingSelf = agentArray.filter((e) => e != this);
const collide = isCollide(excludingSelf, newx, newy, this.w, this.h);
function tryCreateAgent() {
const w = random(minSize, maxSize);
const h = random(minSize, maxSize);
const direction = random(2) < 1 ? 0 : PI / 2;
y = random(10 + h / 2, height - h / 2);
x = random(10 + w / 2, width - w / 2);
const collide = isCollide(agentArray, x, y, w, h);
return collide ? null : agent(x, y, w, h, direction);
function isCollide(array, x, y, w, h) {
(e) => abs(e.x - x) < (e.w + w) / 2 && abs(e.y - y) < (e.h + h) / 2