2024-09-13 21:45:59 -05:00
|
|
|
import { COLS, ROWS, 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 {
|
|
|
|
constructor({ name, imageId, elementId, selected = false }) {
|
|
|
|
super();
|
|
|
|
this.name = name;
|
|
|
|
this.imageId = imageId;
|
|
|
|
this.image = document.getElementById(imageId);
|
2024-09-13 21:45:59 -05:00
|
|
|
this.width = this.image.width;
|
2024-09-13 21:45:59 -05:00
|
|
|
this.selected = selected;
|
|
|
|
this.elementId = elementId;
|
|
|
|
}
|
|
|
|
|
|
|
|
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-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-13 21:45:59 -05:00
|
|
|
|
|
|
|
const { ctx, canvas } = createCanvas(COLS * TILE_SIZE, ROWS * TILE_SIZE);
|
|
|
|
|
|
|
|
const image = this.image;
|
|
|
|
const width = this.width;
|
|
|
|
const level = this.levelConfig;
|
2024-09-13 21:45:59 -05:00
|
|
|
const layer = level.layers[0];
|
|
|
|
const data = layer.data;
|
|
|
|
|
|
|
|
for (let row = 0; row < ROWS; row++) {
|
|
|
|
for (let col = 0; col < COLS; col++) {
|
|
|
|
const tile = data[row * COLS + col] - 1;
|
|
|
|
ctx.drawImage(
|
2024-09-13 21:45:59 -05:00
|
|
|
image,
|
|
|
|
(tile * TILE_SIZE) % width,
|
|
|
|
Math.floor((tile * TILE_SIZE) / width) * 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 21:45:59 -05:00
|
|
|
return (this._level = canvas);
|
|
|
|
}
|
|
|
|
|
|
|
|
render(ctx) {
|
|
|
|
if (!this.levelConfig || !this.selected) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
ctx.drawImage(this.level, 0, 0);
|
2024-09-13 21:45:59 -05:00
|
|
|
}
|
|
|
|
}
|