xxxxxxxxxx
151
const cells = 100;
let s;
const maxAgents = 100;
const minAgents = 10;
let agents = [];
let freeSpots;
let pallette = [
// Peachy
// "#BA7BA1",
// "#C28CAE",
// "#D0ABA0",
// "#DEC4A1",
// "#EDCF8E",
// Forest
// "#395e66",
// "#387d7a",
// "#32936f",
// "#26a96c",
// "#2bc016",
// Sunrise
"#F9C80E",
"#EF5D60",
"#EC4067",
"#A01A7D",
"#5E239D",
];
function setup() {
createCanvas(900, 900);
randomSeed(1);
s = width/cells;
setFreeSpots();
for(let i = 0; i < maxAgents; i ++) {
newAgent();
}
noStroke();
background(255);
// noLoop();
}
function draw() {
if(numFreeSpots() || agents.length) {
for(let a = agents.length - 1; a >= 0; a --) {
agents[a].draw();
if(!agents[a].update()) {
agents.splice(a, 1);
}
}
if(agents.length < minAgents) {
let n = min(minAgents - agents.length, numFreeSpots());
for(let i = 0; i < n; i ++) {
newAgent();
}
}
}
}
class Agent {
constructor(x, y) {
this.p = createVector(x, y);
this.c = randomColour();
this.d = floor(random(4));
this.draw();
this.s = createVector(x, y);
}
update() {
let dirs = [this.d, left(this.d), right(this.d)];
let next;
for(let d of dirs) {
next = move(this.p, d);
if(next && freeSpots[next]) {
this.p = next;
this.d = d;
delete freeSpots[next];
return true;
}
}
if(!(this.p.x === this.s.x && this.p.y === this.s.y)) {
this.p.x = this.s.x;
this.p.y = this.s.y;
return this.update();
}
return false;
}
draw() {
fill(this.c);
square(this.p.x * s, this.p.y * s, s);
}
}
function newAgent() {
let keys = Object.keys(freeSpots);
let k = keys[floor(random(keys.length))];
let p = freeSpots[k];
agents.push(new Agent(p.x, p.y));
delete freeSpots[k];
}
function numFreeSpots() {
return Object.keys(freeSpots).length;
}
function setFreeSpots() {
freeSpots = {};
for(let i = 0; i < cells; i ++) {
for(let j = 0; j < cells; j ++) {
let v = createVector(i, j);
freeSpots[v] = v;
}
}
}
function move(pos, dir) {
let a = dir * HALF_PI;
let n = createVector(pos.x + round(cos(a)), pos.y + round(sin(a)));
if(n.x < 0 || n.x >= cells || n.y < 0 || n.y >= cells) {
return null;
}
return n;
}
function left(dir) {
return (dir - 1) % 4;
}
function right(dir) {
return (dir + 1) % 4;
}
function randomColour() {
return pallette[floor(random(pallette.length))];
}