Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- SLGFW.Game = class {
- /**
- * @type {SLGFW.Scene}
- * @public
- */
- currentScene;
- /**
- * @type {number}
- * @public
- */
- lastTick;
- /**
- *
- * @param {object} config
- * @param {number|string} [config.backgroundColor="black"]
- * @param {HTMLCanvasElement} [config.canvas=undefined]
- * @param {SLGFW.Scene} [config.scene=undefined]
- */
- constructor(config) {
- config = config ? config : {
- backgroundColor: "black",
- canvas: undefined,
- scene: undefined
- };
- SLGFW.current_game = this;
- // Canvas stuff
- if (config.canvas) {
- this.canvas = config.canvas;
- } else {
- this.canvas = document.createElement("canvas");
- this.canvas.width = 640;
- this.canvas.height = 480;
- document.body.appendChild(this.canvas);
- }
- this.ctx = this.canvas.getContext("2d");
- // Set Background Color
- this.setBackgroundColor(config.backgroundColor);
- if (config.scene) {
- this.switchScene(config.scene);
- } else {
- throw new Error("You must have a scene to start in!")
- }
- }
- /**
- * @param {SLGFW.Scene} scene
- * @public
- */
- switchScene(scene) {
- this.currentScene = new scene();
- this.lastTick = Date.now();
- this.tick(this.lastTick, this.currentScene);
- }
- /**
- * @public
- */
- tick(lastTick, scene) {
- const now = Date.now();
- const dt = (now - lastTick) / 1000;
- scene.update(dt);
- scene.draw();
- requestAnimationFrame(this.tick);
- }
- /**
- * @param {number|string} backgroundColor
- * @public
- */
- setBackgroundColor(backgroundColor = "black") {
- switch (typeof backgroundColor) {
- case "string":
- this.canvas.style.backgroundColor = backgroundColor;
- break;
- case "number":
- backgroundColor = SLGFW.clamp(backgroundColor, 0, 16777215);
- const stringBG = backgroundColor.toString(16);
- this.canvas.style.backgroundColor = "#" + stringBG;
- break;
- default:
- break;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement