-
Notifications
You must be signed in to change notification settings - Fork 0
/
engine.js
67 lines (60 loc) · 1.83 KB
/
engine.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
import { Game } from "./game.js"
import { Controls } from "./controls.js";
import { LoadingScreen } from "./loading-screen.js"
export class Engine {
constructor(fps, canvas){
this.canvas = canvas
this.ctx = canvas.getContext("2d")
this.fps = fps;
this.game = null;
this.controls = null;
this.time = null;
this.loadingScreen = null;
this.accumulated_time = null;
this.animationFrameRequest = null;
this.running = false;
this.handleRun = this.handleRun.bind(this);
this.run = this.run.bind(this);
this.handleLoadingScreenRun = this.handleLoadingScreenRun.bind(this);
}
handleRun(){
if (this.game.gameOver) {
this.stop();
this.running = false;
} else {
this.running = true;
this.run();
}
}
handleLoadingScreenRun(){
this.loadingScreen.draw();
this.animationFrameRequest = window.requestAnimationFrame(this.handleLoadingScreenRun)
}
restartGame(){
this.stop();
this.game = new Game(this.canvas)
this.controls = new Controls(this.game)
this.game.playSound = true;
this.game.populateZombies(this.game.zombieCount);
this.game.display.initializeLives();
}
run(){
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
this.game.render()
this.animationFrameRequest = window.requestAnimationFrame(this.handleRun)
}
start(type){
this.accumulated_time = this.fps;
this.time = window.performance.now();
if (type === "loading-screen"){
this.loadingScreen = new LoadingScreen(this.canvas)
this.animation_frame_request = window.requestAnimationFrame(this.handleLoadingScreenRun);
} else {
this.loadingScreen = null;
this.animationFrameRequest = window.requestAnimationFrame(this.handleRun)
}
}
stop(){
window.cancelAnimationFrame(this.animationFrameRequest)
}
}