IA_PathFinder/Population.pde

97 lines
1.8 KiB
Plaintext
Raw Permalink Normal View History

2022-05-07 12:08:13 +00:00
class Population{
int champIndex=0;
float sumOfFitness;
Dot[] dots;
//constructor
Population(int size){
dots=new Dot[size];
for(int i=0; i<dots.length; i++){
dots[i]=new Dot();
}
}
//update
void update(){
for(int i=0; i<dots.length; i++){
dots[i].update();
}
}
boolean hasDotAlive(){
for(int i=0; i<dots.length; i++){
if(dots[i].alive()){
return true;
}
}
return false;
}
//calculate fitnesses
void calcFitness(){
sumOfFitness=0;
for(int i=0; i<dots.length; i++){
sumOfFitness+=dots[i].calcFitness();
}
}
//get best dot as parent
Dot getChampion(){
float big=0;
for(int i=0; i<dots.length; i++){
if(dots[i].fitness>big){
big=dots[i].fitness;
champIndex=i;
}
}
return dots[champIndex];
}
//get a perfect parent based on their fitness
Dot getAParent(){
float rand=random(sumOfFitness);
float sum=0;
for(int i=0; i<dots.length; i++){
sum+=dots[i].fitness;
if(sum>rand){
return dots[i];
}
}
//shouldn't get here
return null;
}
//natural selection
void naturalSelection(){
Dot[] nextGen=new Dot[dots.length];
calcFitness();
nextGen[0]=getChampion().getChild();
nextGen[0].champ=true;
for(int i=1; i<dots.length; i++){
nextGen[i]=getAParent().getChild();
}
dots=nextGen.clone();
}
//mutate the next generation
void mutate(){
for(int i=1; i<dots.length; i++){
dots[i].brain.mutate();
}
}
//display
void display(){
for(int i=1; i<dots.length; i++){
dots[i].display();
}
dots[0].display();
}
}