game-engine/index.js

76 lines
1.8 KiB
JavaScript
Raw Normal View History

2024-09-13 21:45:59 -05:00
import { GAME_HEIGHT, GAME_WIDTH } from "./modules/constants.js";
import {
Camera,
CanvasResizer,
Debug,
GameObject,
MapManagement,
} from "./modules/game-objects/index.js";
2024-09-13 21:45:59 -05:00
const maps = [
{
name: "overworld",
imageId: "overworld",
elementId: "level1",
selected: true,
},
{ name: "ocean", imageId: "overworld", elementId: "level2" },
];
2024-09-13 21:45:59 -05:00
const clicableObjects = ["debug", "level1", "level2"];
2024-09-13 21:45:59 -05:00
class Game extends GameObject {
constructor({ canvas }) {
super();
2024-09-13 16:14:53 -05:00
2024-09-13 21:45:59 -05:00
const canvasResizer = new CanvasResizer({
canvas: canvas,
width: GAME_WIDTH,
height: GAME_HEIGHT,
percentage: 0.9,
});
2024-09-13 23:30:28 -05:00
const camera = new Camera({
mapManagement: new MapManagement({ maps: maps }),
});
2024-09-13 21:45:59 -05:00
const debug = new Debug({ debug: false });
2024-09-13 23:30:28 -05:00
this.gameObjects = [canvasResizer, camera, debug];
2024-09-13 16:14:53 -05:00
2024-09-13 21:45:59 -05:00
this.canvas = canvas;
this.ctx = this.canvas.getContext("2d");
this.lastTime = 0;
2024-09-13 21:45:59 -05:00
clicableObjects.forEach((elementId) => {
document.getElementById(elementId).addEventListener("click", () => {
this.onMouseClick(elementId);
});
2024-09-13 23:30:28 -05:00
document.addEventListener("keydown", (event) => {
this.onKeyPressed(event.key);
});
document.addEventListener("keyup", (event) => {
this.onKeyReleased(event.key);
});
2024-09-13 21:45:59 -05:00
});
}
clear(ctx) {
ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
loop(time) {
const delta = (time - this.lastTime) / 1000;
this.lastTime = time;
this.update(delta);
this.clear(this.ctx);
this.render(this.ctx);
requestAnimationFrame(this.loop.bind(this));
}
}
async function run() {
2024-09-13 21:45:59 -05:00
const game = new Game({ canvas: document.getElementById("game") });
await game.load();
game.loop(0);
}
run();