xxxxxxxxxx
92
let target;
let genes;
function preload() {
target = loadImage("terrain.png");
}
function setup() {
createCanvas(400, 400);
genes = randomGenes();
}
function draw() {
background(220);
displayGenes(genes);
mutate(genes, 0.1);
}
function displayGenes(genes) {
genes.forEach(gene => {
strokeWeight(gene.thickness());
stroke(gene.red(), gene.green(), gene.blue());
line(gene.x1(), gene.x2(), gene.y1(), gene.y2());
});
}
function mutate(genes, rate) {
for(let i = 0; i < genes.length; i ++) {
genes[i].mutate(rate);
}
if(random() < rate/10) {
genes.push(randomGene());
}
if(random() < rate/10) {
const i = round(random(genes.length - 1));
genes.splice(i, 1);
}
}
function randomGenes() {
let num = random(3, 10);
let genes = [];
for(let i = 0; i < num; i ++) {
genes.push(randomGene());
}
return genes;
}
function randomGene() {
return new Gene(random(255), random(255), random(255), random(width), random(width), random(height), random(height), random(1, 20));
}
class Gene {
constructor(r, g, b, x1, x2, y1, y2, t) {
this.values = [r, g, b, x1, x2, y1, y2, t];
}
red() { return this.values[0]; }
green() { return this.values[1]; }
blue() { return this.values[2]; }
x1() { return this.values[3]; }
x2() { return this.values[4]; }
y1() { return this.values[5]; }
y2() { return this.values[6]; }
thickness() { return this.values[7]; }
clone() {
return new Gene(this.values[0], this.values[1], this.values[2], this.values[3], this.values[4], this.values[5], this.values[6], this.values[7]);
}
mutate(rate) {
if(random() < rate) {
const i = round(random(this.values.length) - 1);
this.values[i] += random(-5, 5);
}
}
}