Tile2.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import { Point } from "../../spatial/Point.js"
  2. import { Theme } from "../Theme.js"
  3. import Board from "./Board.js"
  4. class Tile2 {
  5. constructor(board, x, y, tileType) {
  6. this.board = board
  7. this.scale = 1
  8. this.type = tileType
  9. this.position = new Point(x, y)
  10. this.isHovered = false
  11. this.isSelected = false
  12. this.baseColor = Object.values(Theme.Colors.TileColors)[this.type]
  13. this.currentColor = this.baseColor
  14. }
  15. draw(ctx) {
  16. ctx.fillStyle = this.currentColor
  17. ctx.save()
  18. ctx.translate(
  19. this.position.x * (Board.TILE_PADDING + Board.TILE_SIZE) + (Board.TILE_PADDING + Board.TILE_SIZE) / 2,
  20. this.position.y * (Board.TILE_PADDING + Board.TILE_SIZE) + (Board.TILE_PADDING + Board.TILE_SIZE) / 2)
  21. ctx.save()
  22. ctx.scale(this.scale, this.scale)
  23. ctx.beginPath()
  24. ctx.roundRect(-Board.TILE_SIZE / 2, -Board.TILE_SIZE / 2, Board.TILE_SIZE, Board.TILE_SIZE, 8)
  25. ctx.fill()
  26. if (this.isHovered || this.isSelected) {
  27. ctx.strokeStyle = Theme.Colors.ivory
  28. ctx.lineWidth = 4;
  29. ctx.beginPath()
  30. ctx.roundRect(-Board.TILE_SIZE / 2, -Board.TILE_SIZE / 2, Board.TILE_SIZE, Board.TILE_SIZE, 8)
  31. ctx.stroke()
  32. }
  33. ctx.restore()
  34. ctx.restore()
  35. }
  36. update(delta) {
  37. }
  38. onInputMove(position, isDown) {
  39. this.currentColor = this.baseColor
  40. if (this.isColliding(position)) {
  41. if(!this.isHovered) {
  42. this.onTileEnter()
  43. }
  44. document.body.style.cursor = "pointer"
  45. if (isDown) {
  46. this.board.selectTile(this)
  47. }
  48. } else {
  49. if(this.isHovered) {
  50. this.onTileLeave()
  51. }
  52. }
  53. }
  54. onTileEnter() {
  55. this.isHovered = true
  56. }
  57. onTileLeave() {
  58. this.isHovered = false
  59. }
  60. onInputDown(position) {
  61. if (this.isColliding(position)) {
  62. this.board.selectTile(this)
  63. }
  64. }
  65. onInputUp(position) {
  66. // if (this.isSelected && this.isColliding(position)) {
  67. // this.board.deselectTile(this)
  68. // }
  69. }
  70. isColliding(position) {
  71. let top = this.position.y * (Board.TILE_SIZE + Board.TILE_PADDING)
  72. let left = this.position.x * (Board.TILE_SIZE + Board.TILE_PADDING)
  73. let bottom = top + Board.TILE_SIZE
  74. let right = left + Board.TILE_SIZE
  75. return position.x > left && position.x < right && position.y > top && position.y < bottom
  76. }
  77. }
  78. export default Tile2