-
Notifications
You must be signed in to change notification settings - Fork 3
/
Engine.ts
114 lines (80 loc) · 2.75 KB
/
Engine.ts
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
import { MainWindow } from "./Game/_exports";
import { GameSoundPlayer } from "./Game/_exports";
import { SoundLoader, Keyboard, GameContext } from "./Core/_exports";
declare var loadState: any;
declare var controlPanel: any;
export class Engine {
private static _pnrg: number = 0;
private static _credits: number = 0;
private static readonly soundLoader = new SoundLoader(
(assetName: string, percentage: number) => { loadState.assetLoaded(assetName, percentage); });
private static gameSoundPlayer: GameSoundPlayer;
private _dateLoopLastRun: number;
private _mainWindow: MainWindow;
constructor() {
const canvasElement = <HTMLCanvasElement>document.getElementById("gameContainer");
const canvasContext = <CanvasRenderingContext2D>canvasElement.getContext("2d");
canvasContext.scale(3, 3);
this._dateLoopLastRun = window.performance.now();
window.requestAnimationFrame(() => this.loadLoop());
}
loadLoop = () => {
if (loadState.__finishedLoading === false) {
window.requestAnimationFrame(() => this.loadLoop());
return;
}
this._dateLoopLastRun = window.performance.now();
this._mainWindow = new MainWindow();
window.requestAnimationFrame(() => this.mainGameLoop());
Engine.showControlPanel();
}
static get pnrg(): number {
return Engine._pnrg;
}
static resetPnrg() {
Engine._pnrg =0;
}
static get gameSounds(): GameSoundPlayer {
if (Engine.gameSoundPlayer === undefined) {
Engine.gameSoundPlayer = new GameSoundPlayer(Engine.soundLoader);
}
return Engine.gameSoundPlayer;
}
mainGameLoop = () => {
window.requestAnimationFrame(() => this.mainGameLoop());
this.update();
this.draw();
}
static showControlPanel() {
controlPanel.show();
controlPanel.updateWithCredits(this._credits);
}
static useCredits(amount: number) {
if (this._credits - amount < 0) {
throw new Error("Not enough credits!");
}
controlPanel.hide();
this._credits -= amount;
}
static get credits() {
return this._credits;
}
static coinInserted() {
++this._credits;
Engine.gameSounds.coinInsterted();
controlPanel.updateWithCredits(this._credits);
}
update(): void {
if (GameContext.keyboard.isKeyDown(Keyboard.p)) {
return;
}
++Engine._pnrg;
const now = window.performance.now();
const elapsed = now - this._dateLoopLastRun;
this._dateLoopLastRun = now;
this._mainWindow.update(elapsed);
}
draw(): void {
this._mainWindow.draw();
}
}