-
Notifications
You must be signed in to change notification settings - Fork 6
/
bird.js
91 lines (75 loc) · 2.01 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
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
class Bird {
constructor(brain) {
this.actualHeight = height - groundImg.height;
this.x = 50;
this.y = this.actualHeight / 2;
this.width = birdImg.width;
this.height = birdImg.height;
this.gravity = 0.8;
this.upLift = -12;
this.velocity = 0;
// How many frames the bird stays alive
this.score = 0;
// The fitness of the bird
this.fitness = 0;
if (brain instanceof NeuralNetwork) {
this.brain = brain.copy();
this.brain.mutate(0.1);
} else {
// Parameters are number of inputs, number of units in hidden Layer, number of outputs
this.brain = new NeuralNetwork(5, 8, 1);
}
}
copy() {
return new Bird(this.brain);
}
// mutate(rate) {
// this.brain.mutate(rate);
// }
show() {
image(birdImg, this.x, this.y);
}
chooseAction(pipes) {
let closest = null;
let minimum = Infinity;
for (let i = 0; i < pipes.length; i++) {
let diff = pipes[i].x + pipes[i].width - this.x;
if (diff > 0 && diff < minimum) {
minimum = diff;
closest = pipes[i];
}
}
if (closest != null) {
// We get all the inputs and normalize them between 0 and 1
let inputs = [];
// The 5 inpputs I have chosen for the network are
// 1. The horizontal distance of the pipe from the bird
inputs[0] = map(closest.x, this.x, width, 0, 1);
// 2. top of the closest pipe
inputs[1] = map(closest.top, 0, this.actualHeight, 0, 1);
// 3. bottom of the closest pipe
inputs[2] = map(closest.bottom, 0, this.actualHeight, 0, 1);
// 4. bird's y position
inputs[3] = map(this.y, 0, this.actualHeight, 0, 1);
// 5. bird's velocity
inputs[4] = map(this.velocity, -12, 12, 0, 1);
const action = this.brain.predict(inputs);
if (action[0] > 0.5) {
this.jump();
}
}
}
jump() {
this.velocity += this.upLift;
this.velocity *= 0.9;
}
bottomTopCollision() {
return this.y + this.height / 2 > this.actualHeight || this.y - this.hieght / 2 < 0;
}
update() {
this.velocity += this.gravity;
this.velocity *= 0.9;
this.y += this.velocity;
this.score++;
}
}