-
Notifications
You must be signed in to change notification settings - Fork 0
/
bird.js
66 lines (56 loc) · 1.29 KB
/
bird.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
class Bird {
constructor(network) {
this.y = height / 2;
this.x = 64;
this.gravity = 0.8;
this.jump = -12;
this.speed = 0;
this.score = 0;
this.fitness = 0;
if (network) {
this.network = network.copy();
} else {
this.network = new NeuralNetwork(5, 8, 2);
}
}
show() {
stroke(255);
fill(255, 100);
ellipse(this.x, this.y, 32, 32);
}
up() {
this.speed += this.jump;
}
mutate() {
this.network.mutate(0.1);
}
think(pipes) {
let closest = 0;
let closestD = 1000;
for (let i = 0; i < pipes.length; i++) {
let distance = (pipes[i].x + pipes[i].w) - this.x;
if (distance < closestD && distance > 0) {
closest = pipes[i];
closestD = distance;
}
}
let values = [];
values[0] = this.y / height;
values[1] = closest.top / height;
values[2] = closest.bottom / height;
values[3] = closest.x / width;
values[4] = this.speed / 10;
let output = this.network.predict(values);
if (output[0] > output[1]) {
this.up();
}
}
offScreen() {
return (this.y > height || this.y < 0);
}
update() {
this.score++;
this.speed += this.gravity;
this.y += this.speed;
}
}