-
Notifications
You must be signed in to change notification settings - Fork 0
/
ball.js
76 lines (67 loc) · 1.55 KB
/
ball.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
function mutate(x) {
if (random(1) < 0.1) {
let offset = randomGaussian() * 0.5;
let newx = x + offset;
return newx;
} else {
return x;
}
}
class Ball {
constructor(memory) {
this.x = 64;
this.y = height / 2;
this.r = 12;
this.gravity = 0.8;
this.lift = -12;
this.velocity = 0;
if (memory instanceof NeuralNetwork) {
this.memory = memory.copy();
this.memory.mutate(mutate);
} else {
this.memory = new NeuralNetwork(5, 8, 2);
}
this.score = 1;
this.fitness = 0;
}
copy() {
return new Ball(this.memory);
}
show() {
image(ballSprite, this.x, this.y, this.r * 2, this.r * 2);
}
think(pipes) {
let closest = null;
let record = Infinity;
for (let i = 0; i < pipes.length; i++) {
let diff = pipes[i].x - this.x;
if (diff > 0 && diff < record) {
record = diff;
closest = pipes[i];
}
}
if (closest != null) {
let inputs = [];
inputs[0] = map(closest.x, this.x, width, 0, 1);
inputs[1] = map(closest.top, 0, height, 0, 1);
inputs[2] = map(closest.bottom, 0, height, 0, 1);
inputs[3] = map(this.y, 0, height, 0, 1);
inputs[4] = map(this.velocity, -5, 5, 0, 1);
let action = this.memory.predict(inputs);
if (action[1] > action[0]) {
this.up();
}
}
}
up() {
this.velocity += this.lift;
}
bottomTop() {
return (this.y > height || this.y < 0);
}
update() {
this.velocity += this.gravity;
this.y += this.velocity;
this.score += 0.1;
}
}