game-engine/modules/game-objects/map.js

94 lines
2.2 KiB
JavaScript
Raw Normal View History

2024-09-13 23:30:28 -05:00
import { TILE_SIZE } from "../constants.js";
2024-09-13 21:45:59 -05:00
import { createCanvas } from "../utils.js";
2024-09-13 21:45:59 -05:00
import { GameObject } from "./game-object.js";
export class Map extends GameObject {
2024-09-14 18:38:50 -05:00
constructor({ name, imageId, elementId, selected = false, debug = false }) {
super({ debug });
2024-09-13 21:45:59 -05:00
this.name = name;
this.imageId = imageId;
this.image = document.getElementById(imageId);
2024-09-14 18:38:50 -05:00
this.imageWidth = this.image.width;
this.imageHeight = this.image.height;
2024-09-13 21:45:59 -05:00
this.selected = selected;
this.elementId = elementId;
2024-09-14 18:38:50 -05:00
this.debug = debug;
2024-09-13 21:45:59 -05:00
}
async load() {
2024-09-13 21:45:59 -05:00
const levelConfig = await fetch("/resources/" + this.name + ".json");
this.levelConfig = await levelConfig.json();
2024-09-14 18:38:50 -05:00
const layer = this.levelConfig.layers[0];
const { data, height, width } = layer;
this.width = width;
this.height = height;
this.data = data;
2024-09-13 21:45:59 -05:00
}
2024-09-13 21:45:59 -05:00
get level() {
if (this._level) {
return this._level;
2024-09-13 21:45:59 -05:00
}
2024-09-14 18:38:50 -05:00
const { ctx, canvas } = createCanvas(
this.width * TILE_SIZE,
this.height * TILE_SIZE
);
for (let row = 0; row < this.height; row++) {
for (let col = 0; col < this.width; col++) {
if (row < 0 || col < 0 || row >= this.height || col >= this.width)
continue;
2024-09-13 21:45:59 -05:00
2024-09-14 18:38:50 -05:00
if (this.debug) {
ctx.strokeRect(
col * TILE_SIZE,
row * TILE_SIZE,
TILE_SIZE,
TILE_SIZE
);
}
2024-09-13 21:45:59 -05:00
2024-09-14 18:38:50 -05:00
const tile = this.data[row * this.width + col] - 1;
2024-09-13 21:45:59 -05:00
ctx.drawImage(
2024-09-13 23:30:28 -05:00
this.image,
2024-09-14 18:38:50 -05:00
(tile * TILE_SIZE) % this.imageWidth,
Math.floor((tile * TILE_SIZE) / this.imageWidth) * TILE_SIZE,
2024-09-13 21:45:59 -05:00
TILE_SIZE,
TILE_SIZE,
col * TILE_SIZE,
row * TILE_SIZE,
TILE_SIZE,
TILE_SIZE
);
}
}
2024-09-13 23:30:28 -05:00
2024-09-13 21:45:59 -05:00
return (this._level = canvas);
}
2024-09-14 18:38:50 -05:00
onMouseClick(elementId) {
if (elementId === "debug") {
this.debug = !this.debug;
this._level = null;
}
}
2024-09-13 23:30:28 -05:00
render(ctx, sourceX, sourceY, width, height) {
2024-09-13 21:45:59 -05:00
if (!this.levelConfig || !this.selected) {
return;
}
2024-09-13 23:30:28 -05:00
ctx.drawImage(
this.level,
sourceX,
sourceY,
width,
height,
0,
0,
width,
height
);
2024-09-13 21:45:59 -05:00
}
}