BlueGit

timfa frameworkv3

Files

frameworkv3 / framework / engine / game.js

game.js

primary scene flag
timfa Tim · pushed by timfa · 4 years ago
33c5def3 History
game.js 2.7 KiB Download Raw
1class Game
2{
3 activeScenes = [];
4 previousStep = 0; //used for calculating deltaTime
5
6 images = {};
7
8 constructor()
9 {
10 this.previousStep = 0;
11 this.activeScenes = [];
12 this.update = this.update.bind(this);
13 }
14
15 startGame() {
16 this.update();
17 GameInput.g_init();
18 }
19
20 preloadImagesThenStart(imageData, onComplete)
21 {
22 const cont = async () => {
23 await this.preloadImages(
24 imageData
25 );
26
27 this.startGame();
28 onComplete && onComplete();
29 }
30
31 cont.apply();
32 }
33
34 setPrimaryScene(scene)
35 {
36 if(this.activeScenes.contains(scene))
37 {
38 for(let i = 0; i < this.activeScenes.length; i++)
39 this.activeScenes[i].g_primary = false;
40
41 scene.g_primary = true;
42 }
43 }
44
45 async preloadImages(imagesData) {
46 const promises = [];
47 const context = this;
48 console.log(imagesData);
49
50 for(var imageData of imagesData) {
51 if(context.images[imageData.name]) {
52 console.warn("Image '" + imageData.name + "' is already loaded! (overwriting anyway)");
53 }
54
55 promises.push(new Promise(resolve => {
56 var img = new Image();
57 var imageContext = {name: imageData.name, subImgTotal: imageData.subImgTotal, perRow: imageData.perRow, loop: imageData.loop, chain: imageData.chain};
58
59 img.onload = function() {
60
61 var finalImage = new image(img, imageContext.subImgTotal, imageContext.perRow);
62
63 context.images[imageContext.name] = finalImage;
64
65 resolve();
66 };
67
68 img.src = imageData.url;
69 img.setAttribute("style","display:none");
70 }));
71 }
72 await Promise.all(promises);
73
74 console.log("all images loaded");
75
76 return this.images;
77 }
78
79 loadScene(scene)
80 {
81 if(this.activeScenes.length == 0)
82 scene.g_primary = true;
83
84 this.activeScenes.push(scene);
85 scene.game = this;
86 scene.onLoad();
87 }
88
89 update()
90 {
91 this.previousStep = this.previousStep || 0;
92 let stepTime = Date.now();
93 let stepTimeCurr = (stepTime - this.previousStep) * 0.001;
94 stepTimeCurr = Math.min(stepTimeCurr, 0.1);
95 if(isNaN(stepTimeCurr))
96 stepTimeCurr = 0;
97
98 GameInput.g_updateKeys();
99
100 for(let i = 0; i < this.activeScenes.length; i++)
101 {
102 this.activeScenes[i].update(stepTimeCurr);
103 this.activeScenes[i].draw();
104 }
105
106 this.previousStep = stepTime;
107
108 requestAnimationFrame(this.update);
109 }
110}