BlueGit

timfa frameworkv3

Files

frameworkv3 / framework / engine / game.js

game.js

9dbbce66 History
game.js 2.3 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)
21 {
22 const cont = async () => {
23 await game.preloadImages(
24 imageData
25 );
26
27 game.startGame();
28 }
29
30 cont.apply();
31 }
32
33 async preloadImages(imagesData) {
34 const promises = [];
35 const context = this;
36 console.log(imagesData);
37
38 for(var imageData of imagesData) {
39 if(context.images[imageData.name]) {
40 console.warn("Image '" + imageData.name + "' is already loaded! (overwriting anyway)");
41 }
42
43 promises.push(new Promise(resolve => {
44 var img = new Image();
45 var imageContext = {name: imageData.name, subImgTotal: imageData.subImgTotal, perRow: imageData.perRow};
46
47 img.onload = function() {
48
49 var finalImage = new image(img, imageContext.subImgTotal, imageContext.perRow);
50
51 context.images[imageContext.name] = finalImage;
52
53 resolve();
54 };
55
56 img.src = imageData.url;
57 img.setAttribute("style","display:none");
58 }));
59 }
60 await Promise.all(promises);
61
62 console.log("all images loaded");
63
64 return this.images;
65 }
66
67 loadScene(scene)
68 {
69 this.activeScenes.push(scene);
70 scene.game = this;
71 scene.onLoad();
72 }
73
74 update()
75 {
76 this.previousStep = this.previousStep || 0;
77 let stepTime = Date.now();
78 let stepTimeCurr = (stepTime - this.previousStep) * 0.001;
79 stepTimeCurr = Math.min(stepTimeCurr, 0.1);
80 if(isNaN(stepTimeCurr))
81 stepTimeCurr = 0;
82
83 GameInput.g_updateKeys();
84
85 for(let i = 0; i < this.activeScenes.length; i++)
86 {
87 this.activeScenes[i].update(stepTimeCurr);
88 this.activeScenes[i].draw();
89 }
90
91 this.previousStep = stepTime;
92
93 requestAnimationFrame(this.update);
94 }
95}