xxxxxxxxxx
63
// The Nature of Code
// Daniel Shiffman
// http://natureofcode.com
let walkers = [];
let stepSize = 5;
function setup() {
createCanvas(400, 400);
walkers.push(new Walker());
background(0);
}
function draw() {
for (let i = walkers.length - 1; i >= 0; i--) {
let walker = walkers[i];
walker.step();
walker.show();
if (random(1) < 0.01) {
console.log("split");
let w = new Walker(walker.x, walker.y);
walkers.push(w);
}
if (walker.lifespan < 0) {
walkers.splice(i, 1);
}
}
}
class Walker {
constructor(x, y) {
if (random(1) > 0.5) {
this.col = color(255);
} else {
this.col = color(0);
}
this.x = x || width / 2;
this.y = y || height / 2;
this.lifespan = 500;
}
show() {
fill(this.col);
square(this.x, this.y, stepSize);
}
step() {
this.lifespan--;
const choice = floor(random(4));
if (choice == 0) {
this.x += stepSize;
} else if (choice == 1) {
this.x -= stepSize;
} else if (choice == 2) {
this.y += stepSize;
} else {
this.y -= stepSize;
}
}
}