-
Notifications
You must be signed in to change notification settings - Fork 0
/
genetic.js
78 lines (73 loc) · 1.55 KB
/
genetic.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
67
68
69
70
71
72
73
74
75
76
77
78
// let c = 0;
// function nextGeneration() {
// // console.log(deadBirds.length);
// let sum = 0;
// deadBirds.forEach((bird) => {
// sum += bird.score;
// });
// deadBirds.forEach((bird) => {
// bird.fitness = bird.score / sum;
// });
// c = 0;
// for (let i = 0; i < TOTAL; i++) {
// birds.push(pickOne(sum));
// }
// console.log(c);
// pipes = [];
// pipes.push(new Pipe());
// count = 1;
// deadBirds = [];
// // console.log(score);
// console.log('new generation');
// score = 0;
// gen++;
// }
// function pickOne(sum) {
// let index = 0;
// let r = random(sum);
// while (r > 0) {
// r = r - deadBirds[index].score;
// index++;
// }
// index--;
// let child = deadBirds[index];
// let newChild = new Bird();
// newChild.brain = child.brain.copy();
// if (Math.random() < 0.1) if (newChild.brain.mutate(0.1)) c++;
// return newChild;
// }
function nextGeneration() {
console.log('next generation');
calculateFitness();
for (let i = 0; i < TOTAL; i++) {
birds[i] = pickOne();
}
pipes = [];
pipes.push(new Pipe());
count = 1;
deadBirds = [];
score = 0;
gen++;
}
function pickOne() {
let index = 0;
let r = random(1);
while (r > 0) {
r = r - deadBirds[index].fitness;
index++;
}
index--;
let bird = deadBirds[index];
let child = new Bird(bird.brain);
child.brain.mutate();
return child;
}
function calculateFitness() {
let sum = 0;
for (let bird of deadBirds) {
sum += bird.score;
}
for (let bird of deadBirds) {
bird.fitness = bird.score / sum;
}
}