生成成对水管 PipePareProducer

实现思路:

  • 这个类主要用于生成成对的水管对,所以核心属性有下面

    • 存放水管对的数组pairs

    • 生成水管对的计时器timer

    • 生成水管对的间隔tick

  • 需要注意的是,需要提供暂停生成和重新生成的方法,配合游戏操作暂停游戏和重新开始游戏

    • 重新开始的时候,需要将页面上所有生成水管 dom 全部移除掉

实现代码

点击 展开/收起 jsx 代码
/**
 * @description 生成 成对水管类
 */

import PipePare from './PipePare';

class PipePareProducer {
  constructor(speed, gameDom) {
    this.speed = speed;
    this.gameDom = gameDom;

    this.pairs = [];
    this.timer = null;
    this.tick = 2000;
  }

  startProduce() {
    if (this.timer) {
      return;
    }
    this.timer = setInterval(() => {
      this.pairs.push(new PipePare(this.speed, this.gameDom));
    }, this.tick);
  }

  stopProducer() {
    clearInterval(this.timer);
    this.timer = null;
  }

  initProducer() {
    clearInterval(this.timer);
    this.timer = null;
    this.pairs = [];
    // remove页面上所有的 pipe 类
    const pipes = document.querySelectorAll('.pipe');
    // 遍历并移除每个元素
    pipes.forEach((pipe) => {
      pipe.remove();
    });
  }
}

export default PipePareProducer;