-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPopulation.pde
More file actions
104 lines (83 loc) · 2.62 KB
/
Population.pde
File metadata and controls
104 lines (83 loc) · 2.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
class Population {
Rocket[] rockets;
Rocket[] matingPool;
Population() {
this.rockets = new Rocket[popSize];
for (int i = 0; i < popSize; i++) {
this.rockets[i] = new Rocket();
}
}
void evaluate() {
float maxFit = 0;
for (int i = 0; i< popSize; i++) {
this.rockets[i].calcFitness();
if (this.rockets[i].fitness > maxFit) {
maxFit = this.rockets[i].fitness;
}
}
// Normalises fitnesses
for (int i = 0; i < popSize; i++) {
this.rockets[i].fitness /= maxFit;
}
int lengthOfMatingPool = 0;
for (int i = 0; i < popSize; i++) {
int n = (int) (this.rockets[i].fitness * 100);
lengthOfMatingPool += n;
}
int currentIndex = 0;
this.matingPool = new Rocket[lengthOfMatingPool];
for (int i = 0; i < popSize; i++) {
int n = (int) (this.rockets[i].fitness * 100);
for (int j = 0; j < n; j++) {
this.matingPool[currentIndex]= this.rockets[i];
currentIndex++;
}
}
}
void selection() {
Rocket[] newRockets = new Rocket[this.rockets.length];
for (int i = 0; i< (popSize-randomOnes); i++) {
// Picks random indexes for crossover
int parentAindex = floor(random(this.matingPool.length));
int parentBindex = floor(random(this.matingPool.length));
Rocket parentA = this.matingPool[parentAindex];
Rocket parentB = this.matingPool[parentBindex];
// Creates child by using crossover function
Dna child = parentA.dna.crossover(parentB.dna);
child.mutation();
// Creates new rocket with child dna
newRockets[i] = new Rocket(child);
// The color of the "child" is a mix of the parents' colors
newRockets[i].paint = (parentA.paint + parentB.paint) / 2;
}
for (int i = (popSize-randomOnes); i<popSize; i++) {
newRockets[i] = new Rocket();
}
this.rockets = newRockets;
}
boolean allCrashed() {
boolean crashed = true;
// if there's an alive rocket, not all have crashed
for (int i = 0; i < this.rockets.length; i++) {
if (!this.rockets[i].crashed && !this.rockets[i].completed) {
crashed = false;
}
}
return crashed;
}
// Calls for update and show functions
void run() {
for (int i = 0; i < this.rockets.length; i++) {
if (!this.rockets[i].completed) {
this.rockets[i].update(count);
// Displays rockets to screen
}
if (this.rockets[i].completed && !timeLogged) {
bestTime = this.rockets[i].time;
timeLogged = true;
bestRocket = new Rocket(this.rockets[i].dna);
}
this.rockets[i].show();
}
}
}