forked from KeithKarnage/jsBSP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
103 lines (72 loc) · 2.13 KB
/
main.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
(function(){
// CANVAS ELEMENT
var canvas = document.createElement("canvas");
// SET TO FILL WINDOW
canvas.width = window.innerWidth ;
canvas.height = window.innerHeight;
// APPEND TO DOCUMENT
document.body.appendChild(canvas);
// GET THE DRAWING CONTEXT
var draw = canvas.getContext("2d");
// MAIN STATE MACHINE
var LOADING = 0;
var PLAY = 1;
var gameState = LOADING;
// THE GAME
var game = null;
var tileSize = 16;
// INTERVAL FOR MAIN RUN LOOP
var tick = setInterval(update,1000/60);
// ARRAY OF ASSETS TO LOAD
var assetsToLoad = [];
// HOW MANY ASSETS HAVE LOADED
var assetsLoaded = 0;
// CREATE IMAGE
var sprites = new Image();
// CALL loadHandler WHEN LOADED
sprites.onload = loadHandler;
// FILE PATH FOR THE IMAGE
sprites.src = "sprites.png";
// PUSH IT TO assetsToLoad
assetsToLoad.push(sprites);
// CALLED FOR EVERY ASSET LOADED
function loadHandler() {
// COUNT HOW MANY ASSETS HAVE LOADED
assetsLoaded++;
// IF IT IS AS MANY AS WE ARE SUPPOSED TO LOAD
if(assetsLoaded === assetsToLoad.length) {
console.log(assetsLoaded + " asset[s] loaded");
// PLAY BALL!
gameState = PLAY;
}
}
// MAIN RUN LOOP
function update() {
// STATE MACHINE SWITCH
switch(gameState){
// LOADING OF ASSETS AT BEGINNING OF GAME
case LOADING:
console.log("loading");
break;
// WHEN WE ARE PLAYING A LEVEL
case PLAY:
play();
break;
}
// RENDER LAST
render();
}
function play() {
if(game === null) game = new Game.Game({ground:sprites,player:sprites},tileSize);
}
// RENDER FUNCTION
function render() {
// CLEAR THE BACKGROUND
draw.clearRect(0,0,canvas.width,canvas.height);
switch(gameState) {
case PLAY:
if(game) game.render(draw);
break;
}
}
})();