-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGameScene.js
111 lines (92 loc) · 2.77 KB
/
GameScene.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
class GameScene {
/**
* @type {HTMLElement}
*/
_element = null;
/**
* @type {Spawner[]}
*/
_spawners = null;
/**
* @type {Object.<string,GameElement>}
*/
_elements = {};
/**
* @type {MutationObserver}
*/
_mutationObserver = {};
_spawnerTimers = {};
/**
* @param {HTMLElement} element
*/
constructor(element, { spawners = [] } = {}) {
this._element = element;
this._spawners = spawners;
this._element.addEventListener("contextmenu", e => e.preventDefault());
this.setupSpawners();
this.setupMutationObserver();
}
get width() {
return this._element.offsetWidth;
}
get height() {
return this._element.offsetHeight;
}
/**
* @param {GameElement} element
*/
elementIsInScene(element) {
const isInX = element.x >= 0 && element.x + element.width <= this.width;
const isInY = element.y >= 0 && element.y + element.height <= this.height;
return isInX && isInY;
}
setupSpawners() {
this._spawners.forEach(spawner => {
const spawnLoop = () => {
this._spawnerTimers[spawner.id] = setTimeout(() => {
spawner.spawnInto(this);
spawnLoop();
}, spawner.frequency());
};
spawnLoop();
});
}
destroy() {
Object.values(this._spawnerTimers).forEach(timer => clearTimeout(timer));
this._spawners = [];
this._mutationObserver.disconnect();
}
setupMutationObserver() {
this._mutationObserver = new MutationObserver(mutations => {
mutations.forEach(mutation => {
if (mutation.type !== "childList") {
return;
}
if (mutation.addedNodes.length) {
mutation.addedNodes.forEach(node => {
if (node.nodeType !== Node.TEXT_NODE) {
this._elements[node.dataset.gameElementId] = new GameElement(node);
}
});
}
if (mutation.removedNodes.length) {
mutation.removedNodes.forEach(node => {
if (node.nodeType !== Node.TEXT_NODE) {
delete this._elements[node.dataset.gameElementId];
}
});
}
});
});
this._mutationObserver.observe(this._element, { childList: true, subtree: true });
}
/**
* @param {GameElement} element
*/
renderGameElement(element) {
this._element.append(element._element);
}
getElement(id) {
return this._elements[id];
}
}