68 lines
1.7 KiB
TypeScript
68 lines
1.7 KiB
TypeScript
/**
|
|
* Class representing a grid-based tile map for the game level.
|
|
*/
|
|
export class TileMap {
|
|
cols: number;
|
|
rows: number;
|
|
tileSize: number;
|
|
tiles: number[];
|
|
|
|
/**
|
|
* @param cols - Number of columns
|
|
* @param rows - Number of rows
|
|
* @param tileSize - Size of each tile in pixels
|
|
*/
|
|
constructor(cols: number, rows: number, tileSize: number) {
|
|
this.cols = cols;
|
|
this.rows = rows;
|
|
this.tileSize = tileSize;
|
|
this.tiles = new Array(cols * rows).fill(0);
|
|
}
|
|
|
|
/**
|
|
* Set the value of a specific tile.
|
|
* @param col - Tile column
|
|
* @param row - Tile row
|
|
* @param value - Tile type value
|
|
*/
|
|
setTile(col: number, row: number, value: number): void {
|
|
if (this.isValid(col, row)) {
|
|
this.tiles[row * this.cols + col] = value;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get the type value of a tile. Treats out-of-bounds as solid.
|
|
* @param col - Tile column
|
|
* @param row - Tile row
|
|
* @returns The tile type value
|
|
*/
|
|
getTile(col: number, row: number): number {
|
|
if (this.isValid(col, row)) {
|
|
return this.tiles[row * this.cols + col];
|
|
}
|
|
return 1;
|
|
}
|
|
|
|
/**
|
|
* Check if a tile coordinate is within the map boundaries.
|
|
* @param col - Tile column
|
|
* @param row - Tile row
|
|
* @returns True if coordinates are valid
|
|
*/
|
|
isValid(col: number, row: number): boolean {
|
|
return col >= 0 && col < this.cols && row >= 0 && row < this.rows;
|
|
}
|
|
|
|
/**
|
|
* Check if a world position (x, y) collides with a solid tile.
|
|
* @param x - World X coordinate
|
|
* @param y - World Y coordinate
|
|
* @returns True if the position is solid
|
|
*/
|
|
isSolid(x: number, y: number): boolean {
|
|
const col = Math.floor(x / this.tileSize);
|
|
const row = Math.floor(y / this.tileSize);
|
|
return this.getTile(col, row) !== 0;
|
|
}
|
|
}
|