1
0
Fork 0
tsgames/src/games/zombies/tile.ts

111 lines
3.1 KiB
TypeScript

import Entity from "./entity";
import type Item from "./item";
import { ItemType } from "./item";
export enum TileType {
NORMAL,
START,
DOOR,
LOCKED_DOOR,
DOORWAY,
END,
}
export default class Tile extends Entity {
public connections: Tile[] = [];
public items: Item[] = [];
public isOpen = false;
constructor(position: [number, number], size: number, public type: TileType = TileType.NORMAL) {
super(position, [size, size]);
}
protected draw(ctx: CanvasRenderingContext2D) {
ctx.font = '0.3px Arial';
if (this.hovered) {
ctx.fillStyle = `rgba(255, 255, 255, 0.2)`;
ctx.fillRect(0, 0, 1, 1);
// ctx.lineWidth = 1 / this.width;
// ctx.strokeStyle = 'red';
// for (const tile of this.connections) {
// const center = [
// 0.5 + (tile.centerX - this.centerX) / this.width,
// 0.5 + (tile.centerY - this.centerY) / this.height,
// ];
// ctx.beginPath();
// ctx.moveTo(0.5, 0.5);
// ctx.lineTo(center[0], center[1]);
// ctx.stroke();
// }
}
if (this.items.length > 0) {
if (this.isOpen) {
const item = this.enemy ?? this.items[0];
ctx.drawImage(item.type, 0.1, 0.1, 0.8, 0.8);
if (this.items.length > 1) {
ctx.fillStyle = 'black';
ctx.fillText('💀', 0.8, 0.2);
}
} else {
ctx.fillStyle = 'white';
ctx.fillRect(0.1, 0.1, 0.8, 0.8);
ctx.fillStyle = 'black';
ctx.fillText('❓', 0.5, 0.5);
}
}
if (this.type === TileType.LOCKED_DOOR) {
const doorway = this.connections.find(t => t.type === TileType.DOORWAY);
let x = 0.5;
let y = 0.5;
if (doorway) {
x += (Number(this.left < doorway.left) - Number(doorway.left < this.left)) * 0.5;
y += (Number(this.top < doorway.top) - Number(doorway.top < this.top)) * 0.5;
}
ctx.drawImage(ItemType.ITEM_PLANKS, x - 0.2, y - 0.2, 0.4, 0.4);
}
}
get enemy() {
return this.items.find(i => i.isEnemy);
}
get activeConnections() {
if (this.type === TileType.LOCKED_DOOR) {
return this.connections.filter(t => t.type !== TileType.DOORWAY);
}
if (this.type === TileType.DOORWAY) {
return this.connections.filter(t => t.type !== TileType.LOCKED_DOOR);
}
return this.connections;
}
public open() {
this.isOpen = true;
}
public removeItem(item: Item | null | undefined): boolean {
if (!item) {
return false;
}
const itemIndex = this.items.findIndex(i => i === item);
if (itemIndex >= 0) {
this.items.splice(itemIndex, 1);
return true;
}
return false;
}
public killEnemy() {
this.removeItem(this.enemy);
}
}