import { Theme } from "../Theme.js" class Tile { constructor(scene, position, type) { this.scene = scene this.tileSize = 64 this.position = position this.type = type this.offset = {x: 0, y: 0} this.baseColor = Object.values(Theme.Colors.TileColors)[this.type] this.currentColor = this.baseColor this.isHovered = false } setOffset(offset){ this.offset = offset } draw(ctx) { ctx.fillStyle = this.currentColor ctx.save() ctx.translate(this.offset.x, this.offset.y) ctx.beginPath() ctx.roundRect(this.position.x * (Tile.Size + Tile.PADDING), this.position.y * (Tile.Size + Tile.PADDING), Tile.Size, Tile.Size, 8) ctx.fill() if(this.isHovered) { ctx.strokeStyle = Theme.Colors.ivory ctx.lineWidth = 4; ctx.beginPath() ctx.roundRect(this.position.x * (Tile.Size + Tile.PADDING), this.position.y * (Tile.Size + Tile.PADDING), Tile.Size, Tile.Size, 8) ctx.stroke() } ctx.restore() } setTileSize(newSize) { if(Tile.Size != newSize) { Tile.Size = newSize } } onInputMove(position, isDown) { this.currentColor = this.baseColor if(this.isColliding(position)) { this.isHovered = true document.body.style.cursor = "pointer" if(isDown) { this.scene.trackSelectedTile(this) this.wasClickedOn = true } } else { this.isHovered = false } } onInputDown(position) { if(this.isColliding(position)) { this.scene.trackSelectedTile(this) this.wasClickedOn = true } } onInputUp(position) { if(this.isColliding(position)) { this.wasClickedOn = false } else if(this.wasClickedOn) { this.wasClickedOn = false } } isColliding(position) { let top = this.offset.y + this.position.y * (Tile.Size + Tile.PADDING) let left = this.offset.x + this.position.x * (Tile.Size + Tile.PADDING) let bottom = top + Tile.Size let right = left + Tile.Size return position.x > left && position.x < right && position.y > top && position.y < bottom } onResize(canvasBounds, boardSize) { let narrowest = canvasBounds.width let isVertical = true if (canvasBounds.width > canvasBounds.height) { narrowest = canvasBounds.height isVertical = false } this.setTileSize(Math.min(64, Math.max(40, Math.floor((narrowest - boardSize.x * 4) / boardSize.x)))) const offset = { x: -3.5 * (Tile.PADDING + Tile.Size), y: -10 * (Tile.PADDING + Tile.Size) + canvasBounds.height / 2 } if(!isVertical) { offset.x = 3.5 * (Tile.PADDING + Tile.Size) - canvasBounds.width / 2 offset.y = -3.5 * (Tile.PADDING + Tile.Size) } this.setOffset(offset) } onRemove() { this.scene.removeTile(this) } } Tile.PADDING = 4 Tile.Size = 64 export default Tile