Repository navigation
Expand file tree
/
Copy pathobstacles.js
More file actions
67 lines (54 loc) · 1.44 KB
/
Copy pathobstacles.js
File metadata and controls
67 lines (54 loc) · 1.44 KB
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 { canvas } from "./canvas.js";
import { getRandom } from "./libs.js";
import { Obstacle } from "./obstacle.js";
import { state } from "./state.js";
class Obstacles {
#list;
#maxObstaclesCount = 30;
init() {
this.#fill();
canvas.addDrawFunction(this.#draw.bind(this));
state.onGameStateChange(() => {
if (state.isPreparation) {
this.#fill();
}
});
}
#fill() {
this.#list = new Set();
for (let index = 0; index < this.#maxObstaclesCount; index++) {
this.#appendNewObstacle(Array.from(this.#list.keys())[index - 1]);
}
}
#draw() {
this.#list.forEach((obstacle) => {
obstacle.draw();
});
}
#appendNewObstacle(prevObstacle) {
const gap = getRandom(100, 170);
const position = (() => {
if (!prevObstacle) return canvas.sizes.width / 5;
return prevObstacle.getRightEdgePosition() + gap;
})();
const obstacle = new Obstacle({
onOutOfBounds: () => {
this.#list.delete(obstacle);
this.#appendNewObstacle(
Array.from(this.#list.keys())[this.#list.size - 1]
);
},
position,
});
this.#list.add(obstacle);
}
isObjectCollidesWithObstacles({ x, y, width, height }) {
for (const obstacle of this.#list.values()) {
if (obstacle.isObjectCollidesWithObstacle({ x, y, width, height })) {
return true;
}
}
return false;
}
}
export const obstacles = new Obstacles();