/
GA.js
66 lines (61 loc) · 1.8 KB
/
GA.js
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
function simulateOneGeneration() {
readyScore();
let newGames = [];
games.sort((a, b) => b.score - a.score);
let bestGame = games[0];
let bestYVel = Math.abs(bestGame.rocket.vel.y);
//let worstGame = games[popnSize - 1];
//let worstYVel = Math.abs(worstGame.rocket.vel.y);
//console.error(bestYVel, worstYVel);
if (bestYVel < 5) {
mutationRate = 0.01;
} else if (bestYVel >= 5 && bestYVel < 10) {
mutationRate = 0.1;
} else {
mutationRate = 1;
}
for (let i = 0; i < games.length; i++) {
let indToCopy1 = pickOne();
games[indToCopy1].mutate(mutationRate);
let tmpNewGame = new Game(startingX, startingY, rocketR);
for (let j = 0; j < tmpNewGame.noOfMoves; j++) {
let indToPush = indToCopy1;
let toPush = [games[indToPush].moveList[j][0], games[indToPush].moveList[j][1]];
tmpNewGame.moveList.push(toPush);
}
newGames.push(tmpNewGame);
}
games = newGames;
gens++;
}
function readyScore() {
let velocities = [];
games.forEach((g) => {
g.simulateTillDeath();
g.calcFitness();
});
let sum = 0;
for (let i = 0; i < games.length; i++) {
sum += games[i].getScore();
velocities.push([games[i].rocket.vel.x, games[i].rocket.vel.y]);
}
velocities.sort((a, b) => b[1] - a[1]);
console.error(velocities[0], velocities[popnSize - 1]);
for (let i = 0; i < games.length; i++) {
let normScore = games[i].getScore() / sum;
games[i].setScore(normScore);
}
}
function pickOne() {
let index = 0;
let r = random(1);
while (r > 0) {
r -= games[index].getScore();
if (index >= popnSize - 1) {
break;
}
index++;
}
index--;
return index;
}