关于粽子的一个小游戏!

625 阅读1分钟

我正在参加「初夏创意投稿大赛」详情请看:初夏创意投稿大赛

演示

合成大粽子

实现思路

游戏规则

按下任意键,即开始游戏

每按下一次任意键,一行停止滚动

三次之后,游戏结束!

合成下面图片即为成功!

粽子

素材

通过将原始图片三等分,得到每一行的图片。

image-20220606155857548

图片是如何滚动

这里的图片其实是背景图片!使用@-webkit-keyframes来编写background-position的位置,因为有三个粽子,并且需要计算合成的结果。所以一共有三个background-position的动画。每次的动画位置,都只滚动背景图片的33%。这里我们滚动的方向移动有两个,从左往右,从右往左!每次的滚动位置,我们都用变量的进行保存!

@-webkit-keyframes ltr-transition-0 {
  0% {
    background-position: 0vw;
  }
  100% {
    background-position: 33.3333vw;
  }
}

无限滚动

实现思路:使用setInterval来定时修改图片的滚动动画!初始状态下,每个图片都会预设状态和滚动的方向。每个图片共有三个动画位置,每次切换图片位置会有一个记录值,这个值可以用来计算最后的合成分数!

   startInterval() {
      this.inter = setInterval(() => {
        if (
          this.curRow.isRunning &&
          (this.curRow.direction == "ltr" || this.curRow.direction == "rtl")
        ) {
          let value =
            this.curRow.direction == "ltr"
              ? this.curRow.value < 2
                ? this.curRow.value + 1
                : 0
              : this.curRow.value > 0
              ? this.curRow.value - 1
              : 2;

          this.animStyle = {
            "animation-name": `${this.curRow.direction}-transition-${this.curRow.value}`,
            "animation-duration": `${this.curRow.speed}ms`,
          };
          this.curRow.value = value;
        }
      }, 100);
    },

停止

这里的每一行都是调用组件,传一个初始状态,初始状态包括:当前的位置,动画的方向!页面加载完成之后开始调用调用每个图片的无限滚动事件。然后监听keypress事件,当用户按下任意键,根据用户按的次数,来切换当前所在的行,并调用当前行的暂停无限滚动事件!调用子组件的暂停事件 使用的是this.$refs.Row1,当所有行都停止之后,弹出对话框,显示游戏结果。

   window.addEventListener("keypress", () => {
    
        if(this.activeRowIndex===3){
         this.diaShow = true
        }
      if (this.activeRowIndex <= 3) {
        let curRow = this.$refs[`Row${this.activeRowIndex}`];
        console.log(curRow);
        curRow.clearRowInterval();
        this.activeRowIndex++;
      
      } else {
        this.activeRowIndex = 1;
      }
    });
  },

继续游戏

继续游戏的思路是:直接恢复子组件的setInterval!

试玩地址

coder-syl.github.io/