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

97 lines
2.3 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-17 23:16:36 -05:00
constructor({ name, imageId, elementId, layer = 0, selected = false }) {
super();
2024-09-13 21:45:59 -05:00
this.name = name;
this.imageId = imageId;
2024-09-14 23:19:41 -05:00
this.layer = layer;
2024-09-13 21:45:59 -05:00
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;
}
async load() {
2024-09-14 23:19:41 -05:00
const response = await fetch(`/resources/${this.name}.json`, {
cache: "force-cache",
});
this.levelConfig = await response.json();
const layer = this.levelConfig.layers[this.layer];
const { data, height, width } = layer ?? {};
2024-09-14 18:38:50 -05:00
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
}
if (!this.width || !this.height) {
return null;
}
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-17 23:16:36 -05:00
const tile = this.data[row * this.width + col] - 1;
if (this.debug && tile > -1) {
2024-09-14 18:38:50 -05:00
ctx.strokeRect(
col * TILE_SIZE,
row * TILE_SIZE,
TILE_SIZE,
TILE_SIZE
);
}
2024-09-13 21:45:59 -05:00
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) {
2024-09-17 23:16:36 -05:00
super.onMouseClick(elementId);
if (elementId === "debug") this._level = null;
2024-09-14 18:38:50 -05:00
}
2024-09-13 23:30:28 -05:00
render(ctx, sourceX, sourceY, width, height) {
if (!this.levelConfig || !this.selected || !this.level) {
2024-09-13 21:45:59 -05:00
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
}
}