xxxxxxxxxx
75
class Population {
constructor(leaveEmpty) {
this.runners = [];
this.size = 100;
if (!leaveEmpty) {
for (let i = 0; i < this.size; i++) {
this.runners[i] = new Runner();
}
}
}
mutate(inp) {
inp.dna.actions[random(inp.dna.actions.length)];
}
crossover(parentA, parentB) {
let newDNA = new DNA();
let newActions = [];
let firstParent;
let secondParent;
if (random(2) > 0.5) {
firstParent = parentA;
secondParent = parentB;
} else {
firstParent = parentB;
secondParent = parentA;
}
for (let i = 0; i < lifespan; i++) {
if (i > lifespan / 2) {
newActions[i] = firstParent.dna.actions[i];
} else {
print(secondParent)
newActions[i] = secondParent.dna.actions[i];
}
}
newDNA.actions = newActions;
let child = new Runner(newDNA);
return child;
}
loop() {
for (let runner of this.runners) {
runner.loop();
}
}
evaluate() {
let newPopul = new Population(true);
let pool = [];
let newRunners = [];
for (let i = 0; i < this.runners.length; i++) {
this.runners[i].calcFit();
for (let i = 0; i < int(this.runners[i].fitness * 1000); i++) {
print(this.runners[i])
pool.push(this.runners[i]);
}
}
//crossover and mutation:
for (let i = 0; i < this.size; i++) {
let child;
child = this.crossover(random(pool), random(pool));
child = this.mutate(child);
newRunners.push(child);
}
newPopul.runners = newRunners;
return newPopul;
}
}