-
Notifications
You must be signed in to change notification settings - Fork 0
/
dino.js
74 lines (73 loc) · 2.01 KB
/
dino.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
let Dino = function(brain) {
// position and size of dino
this.x = 64;
this.y = height - 75 ;
this.r = 60;
this.brain = brain;
this.dinoImage = new Image();
this.dinoImage.src = "img/dino.png";
// Gravity and velocity
this.gravity = 1.55;
this.velocity = 0;
// Score is how many frames it's been alive
this.score = 0;
// Fitness is normalized version of score
this.fitness = 0;
// Create a copy of this dino
this.copys = function(){
return new Dino(this.brain);
}
//Draw the Dino
this.draw = function(){
ctx.drawImage(this.dinoImage, this.x, this.y, this.r, this.r);
}
// Dino determines if it should jump or not!
this.think = function(cactus) {
// First find the closest cactus
let closest = null;
let record = Infinity;
for (let i = 0; i < cactus.length; i++) {
let diff = cactus[i].x - this.x;
if (diff > 0 && diff < record) {
record = diff;
closest = cactus[i];
}
}
// Now create the inputs to the neural network
if (closest != null) {
let inputs = [];
inputs[0] = map(closest.x, this.x, width, 0, 1);
inputs[1] = map(closest.bottom, 0, height, 0, 1);
inputs[2] = map(this.y, 0, height, 0, 1);
inputs[3] = map(this.velocity, -5, 5, 0, 1);
// Get the outputs from the network
let action = this.brain.activate(inputs);
// Decide to jump or not!
if (action[1] > action[0]) {
this.up();
}
}
}
// Jump up
this.up = function() {
if(this.y == height - 75) {
this.velocity = -20;
}
}
//// Dino dies when hits bottom?
this.bottomTop = function(){
return (this.y > height || this.y < 0);
}
// Update dino's position based on velocity, gravity, etc.
this.update = function(){
this.y += this.velocity;
this.velocity += this.gravity;
this.y = constrain(this.y, 0, height - 75);
// Every frame it is alive increases the score
this.score++;
}
this.getScore = function(){
return this.score;
}
return this;
}