100 lines
2.0 KiB
Plaintext
100 lines
2.0 KiB
Plaintext
class Dot{
|
|
PVector pos;
|
|
PVector vel;
|
|
boolean dead=false;
|
|
boolean deadByObstacle=false;
|
|
boolean reachedGoal=false;
|
|
boolean champ=false;
|
|
float fitness;
|
|
Brain brain;
|
|
|
|
//constructor
|
|
Dot(){
|
|
brain=new Brain(1000);
|
|
|
|
//start position (bottom center)
|
|
pos=new PVector(width/2, height-10);
|
|
vel=new PVector(0, 0);
|
|
}
|
|
|
|
//do movement
|
|
void move(){
|
|
PVector accl=brain.next(); //get next acceleration
|
|
if(accl==null){
|
|
dead=true; //we're dead. No solution
|
|
}
|
|
else{
|
|
vel.add(accl); //add acceleration
|
|
vel.limit(20); //limit speed
|
|
pos.add(vel); //update position
|
|
}
|
|
|
|
//detect if exiting area or is intersecting
|
|
if(pos.x <= 2 || pos.y <= 2 || pos.x >= width-2 || pos.y >= height-2){
|
|
dead=true;
|
|
}
|
|
//check if intersects obstacle
|
|
else if(obstacles.isIntersecting(this)){
|
|
dead=true;
|
|
deadByObstacle=true;
|
|
}
|
|
|
|
//detect if reached goal
|
|
if(dist(pos.x, pos.y, goal.x, goal.y) < 2){
|
|
reachedGoal=true;
|
|
}
|
|
}
|
|
|
|
//update point
|
|
boolean update(){
|
|
if(!dead && !reachedGoal){
|
|
move();
|
|
return true;
|
|
}
|
|
else{
|
|
return false;
|
|
}
|
|
}
|
|
|
|
//calculate fitness
|
|
float calcFitness(){
|
|
if(reachedGoal){
|
|
fitness=10000.0/(brain.step*brain.step);
|
|
}
|
|
else if(!deadByObstacle){
|
|
float distToGoal=dist(pos.x, pos.y, goal.x, goal.y);
|
|
fitness=2.0/(distToGoal*distToGoal);
|
|
}
|
|
else{
|
|
float distToGoal=dist(pos.x, pos.y, goal.x, goal.y);
|
|
fitness=1.0/(distToGoal*distToGoal);
|
|
}
|
|
|
|
return fitness;
|
|
}
|
|
|
|
//get children
|
|
Dot getChild(){
|
|
Dot child=new Dot();
|
|
child.brain=brain.clone();
|
|
return child;
|
|
}
|
|
|
|
//is alive
|
|
boolean alive(){
|
|
return !(dead || reachedGoal);
|
|
}
|
|
|
|
//display dot
|
|
void display(){
|
|
if(champ){
|
|
fill(0, 255, 0);
|
|
ellipse(pos.x, pos.y, 8, 8);
|
|
}
|
|
else{
|
|
fill(0);
|
|
ellipse(pos.x, pos.y, 4, 4);
|
|
}
|
|
}
|
|
}
|