This repository has been archived by the owner on Jan 18, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 76
/
common.js
120 lines (94 loc) · 2.47 KB
/
common.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
//
// Asset loader
//
var Loader = {
images: {}
};
Loader.loadImage = function (key, src) {
var img = new Image();
var d = new Promise(function (resolve, reject) {
img.onload = function () {
this.images[key] = img;
resolve(img);
}.bind(this);
img.onerror = function () {
reject('Could not load image: ' + src);
};
}.bind(this));
img.src = src;
return d;
};
Loader.getImage = function (key) {
return (key in this.images) ? this.images[key] : null;
};
//
// Keyboard handler
//
var Keyboard = {};
Keyboard.LEFT = 37;
Keyboard.RIGHT = 39;
Keyboard.UP = 38;
Keyboard.DOWN = 40;
Keyboard._keys = {};
Keyboard.listenForEvents = function (keys) {
window.addEventListener('keydown', this._onKeyDown.bind(this));
window.addEventListener('keyup', this._onKeyUp.bind(this));
keys.forEach(function (key) {
this._keys[key] = false;
}.bind(this));
}
Keyboard._onKeyDown = function (event) {
var keyCode = event.keyCode;
if (keyCode in this._keys) {
event.preventDefault();
this._keys[keyCode] = true;
}
};
Keyboard._onKeyUp = function (event) {
var keyCode = event.keyCode;
if (keyCode in this._keys) {
event.preventDefault();
this._keys[keyCode] = false;
}
};
Keyboard.isDown = function (keyCode) {
if (!keyCode in this._keys) {
throw new Error('Keycode ' + keyCode + ' is not being listened to');
}
return this._keys[keyCode];
};
//
// Game object
//
var Game = {};
Game.run = function (context) {
this.ctx = context;
this._previousElapsed = 0;
var p = this.load();
Promise.all(p).then(function (loaded) {
this.init();
window.requestAnimationFrame(this.tick);
}.bind(this));
};
Game.tick = function (elapsed) {
window.requestAnimationFrame(this.tick);
// clear previous frame
this.ctx.clearRect(0, 0, 512, 512);
// compute delta time in seconds -- also cap it
var delta = (elapsed - this._previousElapsed) / 1000.0;
delta = Math.min(delta, 0.25); // maximum delta of 250 ms
this._previousElapsed = elapsed;
this.update(delta);
this.render();
}.bind(Game);
// override these methods to create the demo
Game.init = function () {};
Game.update = function (delta) {};
Game.render = function () {};
//
// start up function
//
window.onload = function () {
var context = document.getElementById('demo').getContext('2d');
Game.run(context);
};