game-engine/index.js

71 lines
2 KiB
JavaScript

import { CanvasResizer } from "./modules/canvas-resizer.js";
import { getLevel } from "./modules/utils.js";
const TILE_SIZE = 16;
const canvasResizer = new CanvasResizer({
canvas: document.getElementById("game"),
width: 320,
height: 240,
percentage: 0.9,
});
const cols = canvasResizer.width / TILE_SIZE;
const rows = canvasResizer.height / TILE_SIZE;
const ctx = canvasResizer.canvas.getContext("2d");
let debug = false;
async function drawLevel({ levelName, imageName }) {
const levelImage = document.getElementById(imageName);
const level = await getLevel(levelName);
const layer = level.layers[0];
const data = layer.data;
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
if (debug) {
ctx.strokeRect(col * TILE_SIZE, row * TILE_SIZE, TILE_SIZE, TILE_SIZE);
}
const tile = data[row * cols + col];
ctx.drawImage(
levelImage,
((tile - 1) * TILE_SIZE) % levelImage.width,
Math.floor(((tile - 1) * TILE_SIZE) / levelImage.width) * TILE_SIZE,
TILE_SIZE,
TILE_SIZE,
col * TILE_SIZE,
row * TILE_SIZE,
TILE_SIZE,
TILE_SIZE
);
}
}
}
async function run() {
await canvasResizer.load();
let selectedLevel = { levelName: "overworld", imageName: "overworld" };
const debugButton = document.getElementById("debug");
debugButton.addEventListener("click", async () => {
debug = !debug;
await drawLevel(selectedLevel);
});
const level1Button = document.getElementById("level1");
level1Button.addEventListener("click", async () => {
selectedLevel = { levelName: "overworld", imageName: "overworld" };
await drawLevel(selectedLevel);
});
const level2Button = document.getElementById("level2");
level2Button.addEventListener("click", async () => {
selectedLevel = { levelName: "ocean", imageName: "overworld" };
await drawLevel(selectedLevel);
});
await drawLevel(selectedLevel);
}
run();