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 {
|
|
|
|
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 23:30:28 -05:00
|
|
|
const levelConfig = this.levelConfig;
|
|
|
|
const layer = levelConfig.layers[0];
|
|
|
|
const { data, height, width } = layer;
|
|
|
|
const { ctx, canvas } = createCanvas(width * TILE_SIZE, height * TILE_SIZE);
|
2024-09-13 21:45:59 -05:00
|
|
|
|
2024-09-13 23:30:28 -05:00
|
|
|
for (let row = 0; row < height; row++) {
|
|
|
|
for (let col = 0; col < width; col++) {
|
|
|
|
if (row < 0 || col < 0 || row >= height || col >= width) continue;
|
2024-09-13 21:45:59 -05:00
|
|
|
|
2024-09-13 23:30:28 -05:00
|
|
|
const tile = data[row * width + col] - 1;
|
2024-09-13 21:45:59 -05:00
|
|
|
ctx.drawImage(
|
2024-09-13 23:30:28 -05:00
|
|
|
this.image,
|
|
|
|
(tile * TILE_SIZE) % this.width,
|
|
|
|
Math.floor((tile * TILE_SIZE) / this.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 23:30:28 -05:00
|
|
|
|
2024-09-13 21:45:59 -05:00
|
|
|
return (this._level = canvas);
|
|
|
|
}
|
|
|
|
|
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
|
|
|
}
|
|
|
|
}
|