BlueGit

timfa frameworkv3

Files

frameworkv3 / framework / engine / game.js

game.js

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