xxxxxxxxxx
79
function pickOne() {
let index = 0;
let r = random(1);
while (r > 0) {
r = r - population[index].fitness;
index++;
}
index--;
return population[index].brain;
}
let population = [];
let target;
let counter = 0;
function setup() {
createCanvas(400, 400);
ml5.tf.setBackend('cpu');
for (let i = 0; i < 100; i++) {
population[i] = new Particle();
}
target = createVector(350, 50);
}
function draw() {
background(0);
for (let p of population) {
p.update();
p.think();
p.show();
}
counter++;
if (counter == 100) {
// next generation
for (let p of population) {
p.calculateFitness();
}
// Normalize Fitness
let sum = 0;
for (let p of population) {
sum += p.fitness;
}
for (let p of population) {
p.fitness /= sum;
}
let newPop = [];
for (let i = 0; i < population.length; i++) {
let brainA = pickOne();
let brainB = pickOne();
let childBrain = brainA.crossover(brainB);
childBrain.mutate();
newPop[i] = new Particle(childBrain);
}
population = newPop;
counter = 0;
}
fill(0, 255, 200);
ellipse(target.x, target.y, 20);
}
function mousePressed() {
target.x = mouseX;
target.y = mouseY;
}