Block.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import { GRID_GAP } from '../constants.js';
  2. import { getColor } from '../utils/color.js';
  3. /**
  4. * Block - 方块实体
  5. * 带有数字标记,被小球碰撞时数字减少,归零时消除
  6. */
  7. export class Block {
  8. /**
  9. * @param {number} gridX - 网格列位置 (0-6)
  10. * @param {number} gridY - 网格行位置 (0-N)
  11. * @param {number} count - 方块数字(剩余生命值)
  12. * @param {number} size - 方块边长(像素)
  13. */
  14. constructor(gridX, gridY, count, size) {
  15. this.gridX = gridX;
  16. this.gridY = gridY;
  17. this.count = count;
  18. this.size = size;
  19. this.destroyed = false;
  20. }
  21. /**
  22. * 被小球击中,count 减 1
  23. * count <= 0 时标记为已消除
  24. * @returns {boolean} 是否被消除
  25. */
  26. hit() {
  27. this.count -= 1;
  28. this._hitTime = performance.now();
  29. if (this.count <= 0) {
  30. this.destroyed = true;
  31. }
  32. return this.destroyed;
  33. }
  34. /**
  35. * 将网格坐标转为像素坐标的碰撞矩形
  36. * @returns {{ x: number, y: number, width: number, height: number }}
  37. */
  38. getRect() {
  39. return {
  40. x: this.gridX * (this.size + GRID_GAP) + GRID_GAP,
  41. y: this.gridY * (this.size + GRID_GAP) + GRID_GAP,
  42. width: this.size,
  43. height: this.size
  44. };
  45. }
  46. /**
  47. * 根据 count 计算当前颜色
  48. * @returns {string} 十六进制颜色字符串
  49. */
  50. getColor() {
  51. return getColor(this.count);
  52. }
  53. /**
  54. * 判断方块是否已被消除
  55. * @returns {boolean}
  56. */
  57. isDestroyed() {
  58. return this.count <= 0;
  59. }
  60. /**
  61. * 回合结束时方块向下移动一行
  62. */
  63. moveDown() {
  64. this.gridY += 1;
  65. }
  66. }