forked from xviniette/FlappyLearning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.js
361 lines (323 loc) · 8.06 KB
/
game.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
//https://chenxqiyu.github.io/FlappyLearning/
(function () {
var timeouts = [];
var messageName = "zero-timeout-message";
function setZeroTimeout(fn) {
timeouts.push(fn);
window.postMessage(messageName, "*");
}
function handleMessage(event) {
if (event.source == window && event.data == messageName) {
event.stopPropagation();
if (timeouts.length > 0) {
var fn = timeouts.shift();
fn();
}
}
}
window.addEventListener("message", handleMessage, true);
window.setZeroTimeout = setZeroTimeout;
})();
//神经网络-声明123
var Neuvol;
var game;
var FPS = 60;
var maxScore = 0;
var images = {};
//速度类
var speed = function (fps) {
FPS = parseInt(fps);
}
//加载类
var loadImages = function (sources, callback) {
var nb = 0;
var loaded = 0;
var imgs = {};
for (var i in sources) {
nb++;
imgs[i] = new Image();
imgs[i].src = sources[i];
imgs[i].onload = function () {
loaded++;
if (loaded == nb) {
callback(imgs);
}
}
}
}
//鸟类
class Bird {
constructor(json) {
this.x = 80;
this.y = 250;
this.width = 40;
this.height = 30;
this.alive = true;
this.gravity = 0;
this.velocity = 0.3;
this.jump = -6;
this.init(json);
}
init(json) {
for (var i in json) {
this[i] = json[i];
}
}
flap() {
this.gravity = this.jump;
}
update() {
this.gravity += this.velocity;
this.y += this.gravity;
}
isDead(height, pipes) {
if (this.y >= height || this.y + this.height <= 0) {
return true;
}
for (var i in pipes) {
if (!(
this.x > pipes[i].x + pipes[i].width ||
this.x + this.width < pipes[i].x ||
this.y > pipes[i].y + pipes[i].height ||
this.y + this.height < pipes[i].y
)) {
return true;
}
}
}
}
//管道类
class Pipe {
constructor(json) {
this.x = 0;
this.y = 0;
this.width = 50;
this.height = 40;
this.speed = 3;
this.init(json);
}
init(json) {
for (var i in json) {
this[i] = json[i];
}
}
update() {
this.x -= this.speed;
}
isOut() {
if (this.x + this.width < 0) {
return true;
}
}
}
//游戏类
class Game {
constructor() {
/** 管道数组 */
this.pipes = [];
/** 鸟数组 */
this.birds = [];
/**分数 */
this.score = 0;
/**画布节点 */
this.canvas = document.querySelector("#flappy");
/**画布对象 */
this.ctx = this.canvas.getContext("2d");
/**宽度 */
this.width = this.canvas.width;
/**高度 */
this.height = this.canvas.height;
/**产卵时间间隔 */
this.spawnInterval = 90;
/**间隔 */
this.interval = 0;
/**下一代数组 */
this.gen = [];
/**鸟的存活数量 */
this.alives = 0;
/**代数统计 */
this.generation = 0;
/**背景移动速度 */
this.backgroundSpeed = 0.5;
this.backgroundx = 0;
/**最大分数 */
this.maxScore = 0;
}
start() {
//初始化变量
this.interval = 0;
this.score = 0;
this.pipes = [];
this.birds = [];
//神经网络-下一代
this.gen = Neuvol.nextGeneration();
for (var i in this.gen) {
var b = new Bird();
this.birds.push(b)
}
this.generation++;
this.alives = this.birds.length;
}
update() {
//移动背景
this.backgroundx += this.backgroundSpeed;
/**下一个霍尔 */
var nextHoll = 0;
//如果鸟的数量大于0
if (this.birds.length > 0) {
//遍历管道数组
for (var i = 0; i < this.pipes.length; i += 2) {
//如果鸟在一个管道的左边
if (this.pipes[i].x + this.pipes[i].width > this.birds[0].x) {
nextHoll = this.pipes[i].height / this.height;
break;
}
}
}
//遍历鸟数组
for (var i in this.birds) {
//如果该鸟还活着
if (this.birds[i].alive) {
//初始化输入值
var inputs = [
this.birds[i].y / this.height,//鸟的y/屏幕高度
nextHoll //管道高度/屏幕高度
];
console.log("this.birds[i].y:" + this.birds[i].y)
//神经计算输入
var res = this.gen[i].compute(inputs);
//神经计算输出
if (res > 0.5) {
this.birds[i].flap();
}
//鸟更新
this.birds[i].update();
//如果鸟碰撞管道
if (this.birds[i].isDead(this.height, this.pipes)) {
this.birds[i].alive = false;
this.alives--;
//console.log(this.alives);
//神经网络-得分
Neuvol.networkScore(this.gen[i], this.score);
//鸟数量为0重置游戏
if (this.isItEnd()) {
this.start();
}
}
}
}
//遍历管道数组
for (var i = 0; i < this.pipes.length; i++) {
this.pipes[i].update();
if (this.pipes[i].isOut()) {
this.pipes.splice(i, 1);
i--;
}
}
//生成管道
if (this.interval == 0) {
var deltaBord = 50;
var pipeHoll = 120;
//开口大小
var hollPosition = Math.round(Math.random() * (this.height - deltaBord * 2 - pipeHoll)) + deltaBord;
this.pipes.push(new Pipe({ x: this.width, y: 0, height: hollPosition }));
this.pipes.push(new Pipe({ x: this.width, y: hollPosition + pipeHoll, height: this.height }));
}
//重新生成管道
this.interval++;
if (this.interval == this.spawnInterval) {
this.interval = 0;
}
//分数统计
this.score++;
this.maxScore = (this.score > this.maxScore) ? this.score : this.maxScore;
var self = this;
if (FPS == 0) {
setZeroTimeout(function () {
self.update();
});
} else {
setTimeout(function () {
self.update();
}, 1000 / FPS);
}
}
isItEnd() {
//**判断鸟是否还有存活 */
for (var i in this.birds) {
if (this.birds[i].alive) {
return false;
}
}
return true;
}
display() {
//清除背景
this.ctx.clearRect(0, 0, this.width, this.height);
//画背景
for (var i = 0; i < Math.ceil(this.width / images.background.width) + 1; i++) {
this.ctx.drawImage(images.background, i * images.background.width - Math.floor(this.backgroundx % images.background.width), 0)
}
//画管道
for (var i in this.pipes) {
if (i % 2 == 0) {
this.ctx.drawImage(images.pipetop, this.pipes[i].x, this.pipes[i].y + this.pipes[i].height - images.pipetop.height, this.pipes[i].width, images.pipetop.height);
} else {
this.ctx.drawImage(images.pipebottom, this.pipes[i].x, this.pipes[i].y, this.pipes[i].width, images.pipetop.height);
}
}
//画鸟
this.ctx.fillStyle = "#FFC600";
this.ctx.strokeStyle = "#CE9E00";
for (var i in this.birds) {
if (this.birds[i].alive) {
this.ctx.save();
this.ctx.translate(this.birds[i].x + this.birds[i].width / 2, this.birds[i].y + this.birds[i].height / 2);
this.ctx.rotate(Math.PI / 2 * this.birds[i].gravity / 20);
this.ctx.drawImage(images.bird, -this.birds[i].width / 2, -this.birds[i].height / 2, this.birds[i].width, this.birds[i].height);
this.ctx.restore();
}
}
//画分数
this.ctx.fillStyle = "white";
this.ctx.font = "20px Oswald, sans-serif";
this.ctx.fillText("得分 : " + this.score, 10, 25);
this.ctx.fillText("最高分数 : " + this.maxScore, 10, 50);
this.ctx.fillText("代数 : " + this.generation, 10, 75);
//神经网络-显示神经网络人口
this.ctx.fillText("存活数 : " + this.alives + " / " + Neuvol.options.population, 10, 100);
var self = this;
/***
requestAnimationFrame 比起 setTimeout、setInterval的优势主要有两点:
1、requestAnimationFrame 会把每一帧中的所有DOM操作集中起来,在一次重绘或回流中就完成,并且重绘或回流的时间间隔紧紧跟随浏览器的刷新频率,一般来说,这个频率为每秒60帧。
2、在隐藏或不可见的元素中,requestAnimationFrame将不会进行重绘或回流,这当然就意味着更少的的cpu,gpu和内存使用量。
*/
requestAnimationFrame(function () {
self.display();
});
}
}
window.onload = function () {
var sprites = {
bird: "./img/bird.png",
background: "./img/background.png",
pipetop: "./img/pipetop.png",
pipebottom: "./img/pipebottom.png"
}
var start = function () {
//神经网络-创建神经网络
Neuvol = new Neuroevolution({
population: 50,
network: [2, [2], 1],
});
game = new Game();
game.start();
game.update();
game.display();
}
loadImages(sprites, function (imgs) {
images = imgs;
start();
})
}
//https://chenxqiyu.github.io/FlappyLearning/