-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtools.js
115 lines (93 loc) · 2.75 KB
/
tools.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
// Inheritance tool.
function extend(Child, Parent) {
var F = function () {};
F.prototype = Parent.prototype;
Child.prototype = new F();
}
function random(from, to) {
return Math.floor(Math.random() * (to - from + 1)) + from;
}
// Global event subscriber.
function on(key, onDown, onUp) {
on.keys[key] = {
listeners: [onDown, onUp],
isPressed: false
};
}
// Listeners (one key - one listener).
on.keys = {};
// Global event unsubscriber (clears all events at once).
function off() {
on.keys = {};
}
window.addEventListener('keydown', function (e) {
if (e.code in on.keys && !on.keys[e.code].isPressed) {
on.keys[e.code].listeners[0] && on.keys[e.code].listeners[0]();
on.keys[e.code].isPressed = true;
}
});
window.addEventListener('keyup', function (e) {
if (e.code in on.keys) {
on.keys[e.code].listeners[1] && on.keys[e.code].listeners[1]();
on.keys[e.code].isPressed = false;
}
});
function haveCollision(a, b) {
var bottom = (a.y <= b.y && a.y + a.h >= b.y),
top = (a.y >= b.y && a.y <= b.y + b.h),
right = (a.x <= b.x && a.x + a.w >= b.x),
left = (a.x >= b.x && a.x <= b.x + b.w);
return (bottom && right ||
bottom && left ||
top && right ||
top && left);
}
var getUniqueID = (function () {
var count = 0;
return function () {
// We are guaranteed to not have a zero id.
return ++count;
};
})();
// Creation of a virtual canvas.
function createCanvas(w, h) {
var c = document.createElement('canvas');
c.width = w;
c.height = h;
return c;
}
// Disable smoothing while scaling a given canvas context.
function disableCanvasSmoothness(context) {
context.mozImageSmoothingEnabled = false;
context.msImageSmoothingEnabled = false;
context.imageSmoothingEnabled = false;
}
// Loading animation sprites before the start of the game.
function loadImages(sprites, callback) {
function load() {
var key = keys.pop(),
dataString = sprites[key].sprite,
image = new Image();
image.onload = function () {
sprites[key].sprite = this; // image
keys.length ? load() : callback();
};
image.src = 'data:' + IMAGE_TYPE + ';base64,R0lGODlh' + dataString;
}
var keys = Object.keys(sprites);
load();
}
// A helper to iterate pixels in an ImageData object.
function iterateImageData(imageData, callback) {
function changePoint(r, g, b) {
data[i] = r;
data[i + 1] = g;
data[i + 2] = b;
}
var data = imageData.data,
len = data.length,
i;
for (i = 0; i < len; i += 4) {
callback(data[i], data[i + 1], data[i + 2], changePoint);
}
}