-
Notifications
You must be signed in to change notification settings - Fork 3
/
sketch.js
101 lines (83 loc) · 1.9 KB
/
sketch.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
92
93
94
95
96
97
98
99
100
101
// Daniel Shiffman & Manuel Romero
// Neuro-Evolution Flappy Bird with TensorFlow.js
// http://thecodingtrain.com
// https://youtu.be/cdUNkwXx-I4
const TOTAL = 250;
let birds = [];
let savedBirds = [];
let pipes = [];
let counter = 0;
let bg;
let slider;
let displayGeneration;
let displaySpeed;
let generationNumber = 1;
function keyPressed() {
if (key === "S" || key === "s") {
let bird = birds[0];
saveJSON(bird.brain, "bird.json");
}
}
function setup() {
bg = loadImage("background.png");
createCanvas(640, 480);
displayGeneration = createP("Generation");
displaySpeed = createP("Speed");
slider = createSlider(1, 10, 1);
for (let i = 0; i < TOTAL; i++) {
birds[i] = new Bird();
}
tf.setBackend('cpu');
}
function draw() {
for (let n = 0; n < slider.value(); n++) {
if (counter % 75 == 0) {
pipes.push(new Pipe());
}
counter++;
for (let i = pipes.length - 1; i >= 0; i--) {
pipes[i].update();
for (let j = birds.length - 1; j >= 0; j--) {
if (pipes[i].hits(birds[j])) {
savedBirds.push(birds.splice(j, 1)[0]);
}
}
if (pipes[i].offscreen()) {
pipes.splice(i, 1);
}
}
for (let i = birds.length - 1; i >= 0; i--) {
if (birds[i].offScreen()) {
savedBirds.push(birds.splice(i, 1)[0]);
}
}
for (let bird of birds) {
bird.think(pipes);
bird.update();
}
if (birds.length === 0) {
counter = 0;
generationNumber++;
nextGeneration();
pipes = [];
}
}
// All the drawing stuff
background(bg);
displayGeneration.html(
`Generation Number: <strong>${generationNumber}</strong>`
);
displaySpeed.html(`Speed:`);
for (let bird of birds) {
bird.show();
}
for (let pipe of pipes) {
pipe.show();
}
}
// function keyPressed() {
// if (key == ' ') {
// bird.up();
// //console.log("SPACE");
// }
// }