game-engine/index.js

72 lines
2 KiB
JavaScript
Raw Normal View History

2024-07-14 02:24:26 -05:00
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,
2024-07-14 10:30:49 -05:00
percentage: 0.9,
2024-07-14 02:24:26 -05:00
});
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) {
2024-07-14 10:30:49 -05:00
ctx.strokeRect(col * TILE_SIZE, row * TILE_SIZE, TILE_SIZE, TILE_SIZE);
2024-07-14 02:24:26 -05:00
}
2024-07-14 10:30:49 -05:00
const tile = data[row * cols + col];
2024-07-14 02:24:26 -05:00
ctx.drawImage(
levelImage,
((tile - 1) * TILE_SIZE) % levelImage.width,
2024-07-14 10:30:49 -05:00
Math.floor(((tile - 1) * TILE_SIZE) / levelImage.width) * TILE_SIZE,
2024-07-14 02:24:26 -05:00
TILE_SIZE,
TILE_SIZE,
col * TILE_SIZE,
row * TILE_SIZE,
TILE_SIZE,
TILE_SIZE
2024-07-14 10:30:49 -05:00
);
2024-07-14 02:24:26 -05:00
}
}
}
async function run() {
2024-07-14 10:30:49 -05:00
await canvasResizer.load();
2024-07-14 02:24:26 -05:00
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 () => {
2024-07-14 10:30:49 -05:00
selectedLevel = { levelName: "overworld", imageName: "overworld" };
2024-07-14 02:24:26 -05:00
await drawLevel(selectedLevel);
});
const level2Button = document.getElementById("level2");
level2Button.addEventListener("click", async () => {
2024-07-14 10:30:49 -05:00
selectedLevel = { levelName: "ocean", imageName: "overworld" };
2024-07-14 02:24:26 -05:00
await drawLevel(selectedLevel);
});
await drawLevel(selectedLevel);
}
run();