-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresources.ts
85 lines (73 loc) · 2.68 KB
/
resources.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
// handler for resources
enum ImageResource {
PLAYER = "img/player.png",
ROCKETLAUNCHER = "img/rocketlauncher.png",
BALLOON = "img/balloon.png",
BIRD = "img/bird.png",
UFO = "img/ufo.png",
CURSOR = "img/cursor.png",
ROCKET = "img/rocket.png",
EXPLOSION = "img/explosion.png",
SPARK = "img/spark.png",
PUFF = "img/puff.png"
}
enum AudioResource {
BGM = "audio/heavy-trailer-2-by-sascha-ende-from-filmmusic-io.mp3",
SHOOT = "audio/shoot.ogg",
EXPLOSION = "audio/explosion.ogg",
}
class Preloader {
private finishedFunc: () => void = () => {}
private finished = false
private numLoading = 0
private numFinished = 0
private resources = Array();
private preloadDiv: HTMLElement;
private preloadBarDiv: HTMLElement;
private gameDiv: HTMLElement;
startLoading() {
console.log("Preloading")
this.preloadDiv = document.getElementById("preloader");
this.preloadBarDiv = document.getElementById("preloader_bar");
this.gameDiv = document.getElementById("game");
for(let resource in ImageResource) {
let resourceUrl = ImageResource[resource];
console.log("Loading " + resourceUrl)
this.numLoading++
let image = new Image()
image.src = resourceUrl
image.onload = this.resourceFinished.bind(this)
image.onerror = this.resourceFinished.bind(this)
this.resources.push(image)
}
for(let resource in AudioResource) {
let resourceUrl = AudioResource[resource];
console.log("Loading " + resourceUrl)
this.numLoading++
let audio = new Audio(resourceUrl)
audio.oncanplaythrough = this.resourceFinished.bind(this)
audio.onerror = this.resourceFinished.bind(this)
}
}
private resourceFinished() {
this.numFinished++
this.preloadBarDiv.style.width = (this.numFinished / this.numLoading * 100).toString() + "%"
if (this.numFinished === this.numLoading) {
let headline = document.getElementById("preloader_headline") as HTMLSpanElement
headline.textContent = "Click to start"
document.onclick = () => {
document.onclick = () => {}
this.preloadDiv.style.display = "none"
this.gameDiv.style.display = "block"
this.finished = true;
if (this.finishedFunc) {
this.finishedFunc()
this.finishedFunc = null
}
}
}
}
onFinish(func: () => void) {
this.finishedFunc = func;
}
}