VUE+Canvas实现财神爷接元宝小游戏

之前的canvas小游戏系列欢迎大家戳:

《VUE实现一个Flappy Bird~~~》

《猜单词游戏》

《VUE+Canvas 实现桌面弹球消砖块小游戏》

《VUE+Canvas实现雷霆战机打字类小游戏》

如标题,这个游戏大家也玩过,随处可见,左右方向键控制财神移动,接住从天而降的金元宝等,时间一到,则游戏结束。先来看一下效果:

相比于之前的雷霆战机要打出四处飞的子弹,这次元素的运动轨迹就很单一了,垂直方向的珠宝和水平移动的财神爷,类似于之前的代码,这里就说一下关键步骤点吧:

1、键盘控制水平移动的财神爷

这个很简单,同理于《VUE+Canvas 实现桌面弹球消砖块小游戏》滑块的控制:

drawCaishen() {
      let _this = this;
      _this.ctx.save();
      _this.ctx.drawImage(
        _this.caishenImg,
        _this.caishen.x,
        _this.caishen.y,
        120,
        120
      );
      _this.ctx.restore();
},
moveCaishen() {
      this.caishen.x += this.caishen.dx;
      if (this.caishen.x > this.clientWidth - 120) {
        this.caishen.x = this.clientWidth - 120;
      } else if (this.caishen.x < 0) {
        this.caishen.x = 0;
      }
}

2、从天而降的珠宝

这个也很简单,但要注意的是,珠宝的初始x值不能随机取0~clientWidth了,因为这样很容易造成珠宝堆积在一起,影响了游戏的可玩性,所以珠宝最好是分散在不同的轨道上,这里我们把画布宽度分为5条轨道,初始珠宝的时候,我们就把珠宝分散在轨道上,并且y值随机在一定高度造成参差。而后新生成的珠宝都依据轨道分布来生成,避免珠宝挤在一起。

generateTreasure() {
      let _this = this;
      if (_this.treasureArr.length < MaxNum) {
        let random = Math.floor(Math.random() * TreasureNames.length);
        let channel = _this.getRandomArbitrary(1, 5);
        _this.treasureArr.push({
          x: _this.channelWidth * (1 / 2 + (channel - 1)) - 30,
          y: 0,
          name: TreasureNames[random],
          speed: _this.getRandomArbitrary(2, 4)
        });
      }
},
filterTreasure(item) {
      let _this = this;
      if (
        item.x <= _this.caishen.x + 110 &&
        item.x >= _this.caishen.x &&
        item.y > _this.caishen.y
      ) {
        // 判断和财神的触碰范围
        _this.score += _this.treasureObj[item.name].score;
        return false;
      }
      if (item.y >= _this.clientHeight) {
        return false;
      }
      return true;
},
drawTreasure() {
      let _this = this;
      _this.treasureArr = _this.treasureArr.filter(_this.filterTreasure);
      _this.treasureArr.forEach(item => {
        _this.ctx.drawImage(
          _this.treasureObj[item.name].src,
          item.x,
          item.y,
          60,
          60
        );
        item.y += item.speed;
      });
},
getRandomArbitrary(min, max) {
      return Math.random() * (max - min) + min;
}

这里用filter函数过滤掉应该消失的珠宝,如果用for+splice+i--的方法会造成抖动。

然后给予每个珠宝随机的运动速度,当珠宝进入财神爷的图片范围时则累加相应分数。

3、倒计时圆环

设置倒计时30s,那么在requestAnimationFrame的回调里计算当前时间与上次时间戳毫秒差值是否大于1000,实现秒的计算,然后取另一时间戳累加progress,实现圆环的平滑移动。

drawCountDown() {
      // 画进度环
      let _this = this;
      _this.progress += Date.now() - _this.timeTag2;
      _this.timeTag2 = Date.now();
      _this.ctx.beginPath();
      _this.ctx.moveTo(50, 50);
      _this.ctx.arc(
        50,
        50,
        40,
        Math.PI * 1.5,
        Math.PI * (1.5 + 2 * (_this.progress / (countDownInit * 1000))),
        false
      );
      _this.ctx.closePath();
      _this.ctx.fillStyle = "yellow";
      _this.ctx.fill();

      // 画内填充圆
      _this.ctx.beginPath();
      _this.ctx.arc(50, 50, 30, 0, Math.PI * 2);
      _this.ctx.closePath();
      _this.ctx.fillStyle = "#fff";
      _this.ctx.fill();

      // 填充文字
      _this.ctx.font = "bold 16px Microsoft YaHei";
      _this.ctx.fillStyle = "#333";
      _this.ctx.textAlign = "center";
      _this.ctx.textBaseline = "middle";
      _this.ctx.moveTo(50, 50);
      _this.ctx.fillText(_this.countDown + "s", 50, 50);
    }
(function animloop() {
        _this.ctx.clearRect(0, 0, _this.clientWidth, _this.clientHeight);
        _this.loop();
        animationId = window.requestAnimationFrame(animloop);
        if (_this.countDown === 0) {
          _this.gameOver = true;
          window.cancelAnimationFrame(animationId);
        }
        if (Date.now() - _this.timeTag >= 1000) {
          _this.countDown--;
          _this.timeTag = Date.now();
        }
})();

至此,一个非常简单的财神爷接元宝的小游戏就完成了,当然可以为了增加难度,设置不间断地丢炸弹这一环节,原理同珠宝的运动是一样的。

下面还是附上全部代码,供大家参考学习:

<template>
  <div class="caishen">
    <canvas id="caishen" width="1200" height="750"></canvas>
    <div class="container" v-if="gameOver">
      <div class="dialog">
        <p class="once-again">恭喜!</p>
        <p class="once-again">本回合夺宝:{{ score }}分</p>
      </div>
    </div>
  </div>
</template>

<script>
const TreasureNames = [
  "yuanbao",
  "tongqian",
  "jintiao",
  "shuijin_red",
  "shuijin_blue",
  "fudai"
];
let animationId = null;
let countDownInit = 0;
const MaxNum = 5;
export default {
  name: "CaiShen",
  data() {
    return {
      score: 0,
      ctx: null,
      caishenImg: null,
      clientWidth: 0,
      clientHeight: 0,
      channelWidth: 0,
      caishen: {
        x: 0,
        y: 0,
        speed: 8,
        dx: 0
      },
      progress: 0,
      countDown: 30,
      timeTag: Date.now(),
      timeTag2: Date.now(),
      treasureArr: [],
      gameOver: false,
      treasureObj: {
        yuanbao: {
          score: 5,
          src: null
        },
        tongqian: {
          score: 2,
          src: null
        },
        jintiao: {
          score: 10,
          src: null
        },
        shuijin_red: {
          score: 20,
          src: null
        },
        shuijin_blue: {
          score: 15,
          src: null
        },
        fudai: {
          score: 8,
          src: null
        }
      }
    };
  },
  mounted() {
    let _this = this;
    let container = document.getElementById("caishen");
    _this.ctx = container.getContext("2d");
    _this.clientWidth = container.width;
    _this.clientHeight = container.height;
    _this.channelWidth = Math.floor(_this.clientWidth / 5);
    _this.caishenImg = new Image();
    _this.caishenImg.src = require("@/assets/img/caishen/财神爷.png");

    _this.initTreasures();
    countDownInit = _this.countDown;
    _this.caishen.x = _this.clientWidth / 2 - 60;
    _this.caishen.y = _this.clientHeight - 120;
    document.onkeydown = function(e) {
      let key = window.event.keyCode;
      if (key === 37) {
        // 左键
        _this.caishen.dx = -_this.caishen.speed;
      } else if (key === 39) {
        // 右键
        _this.caishen.dx = _this.caishen.speed;
      }
    };
    document.onkeyup = function(e) {
      _this.caishen.dx = 0;
    };
    _this.caishenImg.onload = function() {
      (function animloop() {
        _this.ctx.clearRect(0, 0, _this.clientWidth, _this.clientHeight);
        _this.loop();
        animationId = window.requestAnimationFrame(animloop);
        if (_this.countDown === 0) {
          _this.gameOver = true;
          window.cancelAnimationFrame(animationId);
        }
        if (Date.now() - _this.timeTag >= 1000) {
          _this.countDown--;
          _this.timeTag = Date.now();
        }
      })();
    };
  },
  methods: {
    initTreasures() {
      let _this = this;
      Object.keys(_this.treasureObj).forEach(key => {
        _this.treasureObj[key].src = new Image();
        _this.treasureObj[
          key
        ].src.src = require(`@/assets/img/caishen/${key}.png`);
      });
      for (let i = 0; i < MaxNum; i++) {
        let random = Math.floor(Math.random() * TreasureNames.length);
        _this.treasureArr.push({
          x: _this.channelWidth * (1 / 2 + i) - 30,
          y: _this.getRandomArbitrary(0, 20),
          name: TreasureNames[random],
          speed: _this.getRandomArbitrary(2, 4)
        });
      }
    },
    loop() {
      let _this = this;
      _this.drawCountDown();
      _this.drawCaishen();
      _this.moveCaishen();
      _this.generateTreasure();
      _this.drawTreasure();
      _this.drawScore();
    },
    drawCaishen() {
      let _this = this;
      _this.ctx.save();
      _this.ctx.drawImage(
        _this.caishenImg,
        _this.caishen.x,
        _this.caishen.y,
        120,
        120
      );
      _this.ctx.restore();
    },
    moveCaishen() {
      this.caishen.x += this.caishen.dx;
      if (this.caishen.x > this.clientWidth - 120) {
        this.caishen.x = this.clientWidth - 120;
      } else if (this.caishen.x < 0) {
        this.caishen.x = 0;
      }
    },
    drawScore() {
      let _this = this;
      _this.ctx.beginPath();
      _this.ctx.fillStyle = "#fff";
      _this.ctx.textAlign = "center";
      _this.ctx.textBaseline = "middle";
      _this.ctx.fillText(_this.score + "分", 30, _this.clientHeight - 10);
      _this.ctx.closePath();
    },
    drawCountDown() {
      // 画进度环
      let _this = this;
      _this.progress += Date.now() - _this.timeTag2;
      _this.timeTag2 = Date.now();
      _this.ctx.beginPath();
      _this.ctx.moveTo(50, 50);
      _this.ctx.arc(
        50,
        50,
        40,
        Math.PI * 1.5,
        Math.PI * (1.5 + 2 * (_this.progress / (countDownInit * 1000))),
        false
      );
      _this.ctx.closePath();
      _this.ctx.fillStyle = "yellow";
      _this.ctx.fill();

      // 画内填充圆
      _this.ctx.beginPath();
      _this.ctx.arc(50, 50, 30, 0, Math.PI * 2);
      _this.ctx.closePath();
      _this.ctx.fillStyle = "#fff";
      _this.ctx.fill();

      // 填充文字
      _this.ctx.font = "bold 16px Microsoft YaHei";
      _this.ctx.fillStyle = "#333";
      _this.ctx.textAlign = "center";
      _this.ctx.textBaseline = "middle";
      _this.ctx.moveTo(50, 50);
      _this.ctx.fillText(_this.countDown + "s", 50, 50);
    },
    filterTreasure(item) {
      let _this = this;
      if (
        item.x <= _this.caishen.x + 110 &&
        item.x >= _this.caishen.x &&
        item.y > _this.caishen.y
      ) {
        // 判断和财神的触碰范围
        _this.score += _this.treasureObj[item.name].score;
        return false;
      }
      if (item.y >= _this.clientHeight) {
        return false;
      }
      return true;
    },
    drawTreasure() {
      let _this = this;
      _this.treasureArr = _this.treasureArr.filter(_this.filterTreasure);
      _this.treasureArr.forEach(item => {
        _this.ctx.drawImage(
          _this.treasureObj[item.name].src,
          item.x,
          item.y,
          60,
          60
        );
        item.y += item.speed;
      });
    },
    getRandomArbitrary(min, max) {
      return Math.random() * (max - min) + min;
    },
    generateTreasure() {
      let _this = this;
      if (_this.treasureArr.length < MaxNum) {
        let random = Math.floor(Math.random() * TreasureNames.length);
        let channel = _this.getRandomArbitrary(1, 5);
        _this.treasureArr.push({
          x: _this.channelWidth * (1 / 2 + (channel - 1)) - 30,
          y: 0,
          name: TreasureNames[random],
          speed: _this.getRandomArbitrary(2, 4)
        });
      }
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
#caishen {
  background-color: #b00600;
  background-image: url("~assets/img/caishen/brick-wall.png");
}
.container {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.3);
  text-align: center;
  font-size: 0;
  white-space: nowrap;
  overflow: auto;
}
.container:after {
  content: "";
  display: inline-block;
  height: 100%;
  vertical-align: middle;
}
.dialog {
  width: 400px;
  height: 300px;
  background: rgba(255, 255, 255, 0.5);
  box-shadow: 3px 3px 6px 3px rgba(0, 0, 0, 0.3);
  display: inline-block;
  vertical-align: middle;
  text-align: left;
  font-size: 28px;
  color: #fff;
  font-weight: 600;
  border-radius: 10px;
  white-space: normal;
  text-align: center;
  .once-again-btn {
    background: #1f9a9a;
    border: none;
    color: #fff;
  }
}
</style>

到此这篇关于VUE+Canvas实现财神爷接元宝小游戏的文章就介绍到这了,更多相关vue接元宝游戏内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • jQuery+vue.js实现的九宫格拼图游戏完整实例【附源码下载】

    本文实例讲述了jQuery+vue.js实现的九宫格拼图游戏.分享给大家供大家参考,具体如下: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> * { margin: 0; padding: 0; } /*#piclist { width: 600p

  • 使用vue编写一个点击数字计时小游戏

    使用vue编写一个点击数字计时小游戏,列入你在文本框中输入3,点击开始会生成一个3行3列的表格,表格数据为1-9随机排列,这时候从1开始点击,按顺序点到9,当按正确顺序点击完毕,会提示所用的时间,如果顺序没有按对,会提示游戏结束. 1.首先下载vue源码,下载地址http://cn.vuejs.org 2.jquery是在面向dom操作,而vue是面向数据操作的,所以使用vue最好不要去操作dom,尽量发挥出vue的独到之处,(如果使用过angularjs可能更容易理解) 3.建立一个普通的ht

  • 基于Vue.js实现数字拼图游戏

    先来看看效果图: 功能分析 当然玩归玩,作为一名Vue爱好者,我们理应深入游戏内部,一探代码的实现.接下来我们就先来分析一下要完成这样的一个游戏,主要需要实现哪些功能.下面我就直接将此实例的功能点罗列在下了: 1.随机生成1~15的数字格子,每一个数字都必须出现且仅出现一次 2.点击一个数字方块后,如其上下左右有一处为空,则两者交换位置 3.格子每移动一步,我们都需要校验其是否闯关成功 4.点击重置游戏按钮后需对拼图进行重新排序 以上便是本实例的主要功能点,可见游戏功能并不复杂,我们只需一个个攻

  • vue实现2048小游戏功能思路详解

    试玩地址 项目地址 使用方法: git clone npm i npm run dev 实现思路如下: 用vue-cli搭建项目,对这个项目可能有点笨重,但是也懒的再搭一个 4X4的方格用一个二维数组存放,绑定好后只关心这个二维数组,其他事交给vue 监听键盘事件 2048的核心部分就是移动合并的算法,因为是一个4X4的矩阵,所以只要实现左移的算法,其他方向的移动只需要将矩阵旋转,移动合并,再旋转回来,渲染dom即可 绑定不同数值的样式 分值计算,以及用localstorage存放最高分 关键实

  • VUE+Canvas实现财神爷接元宝小游戏

    之前的canvas小游戏系列欢迎大家戳: <VUE实现一个Flappy Bird~~~> <猜单词游戏> <VUE+Canvas 实现桌面弹球消砖块小游戏> <VUE+Canvas实现雷霆战机打字类小游戏> 如标题,这个游戏大家也玩过,随处可见,左右方向键控制财神移动,接住从天而降的金元宝等,时间一到,则游戏结束.先来看一下效果: 相比于之前的雷霆战机要打出四处飞的子弹,这次元素的运动轨迹就很单一了,垂直方向的珠宝和水平移动的财神爷,类似于之前的代码,这里就

  • 利用Vue.js制作一个拼图华容道小游戏

    目录 游戏介绍 核心思路 核心代码 html games 类 生成随机图片数量 移动图片 键盘事件 拼图完成 结语 游戏介绍 先看看界面 这是一个拼图游戏,可以自选难度和自选闯关图片 游戏开始后根据不同难度,生成与所选主图 对应的 不同张数的 随机顺序的小图,然后只要把乱序的小图片还原成完整的图片就闯关成功 游戏区域有一个空白位置,可以用鼠标点击空白位相邻的图片完成替换,也就是移动,也可以用键盘上下左右操作 游戏好玩,可不要贪杯哦,学习也不能落下,不管什么游戏都一样 这个虽然用到的技术很一般很简

  • vue+canvas实现拼图小游戏

    利用 vue+canvas 实现拼图小游戏,供大家参考,具体内容如下 思路步骤 一个拼图拼盘和一个原图参照 对原图的切割以及随机排序 通过W/A/D/S或上下左右进行移动 难度的自主选择 对拼图是否完成的判定 JS实现部分 数据分析 row:拼图的总行数:column:拼图的总列数. (用来设置拼图难度,也是每个拼图块宽高的设置规则) pic[{x,y,row,column,index}]:小拼图的集合,其内元素为小拼图的数据结构. (x.y:拼图块在canvas的绘制规则,初始化后不会进行改变

  • 如何用VUE和Canvas实现雷霆战机打字类小游戏

    今天就来实现一个雷霆战机打字游戏,玩法很简单,每一个"敌人"都是一些英文单词,键盘正确打出单词的字母,飞机就会发射一个个子弹消灭"敌人",每次需要击毙当前"敌人"后才能击毙下一个,一个比手速和单词熟练度的游戏. 首先来看看最终效果图: emmmmmmmmmmmmm,界面UI做的很简单,先实现基本功能,再考虑高大上的UI吧. 首先依旧是来分析界面组成: (1)固定在画面底部中间的飞机: (2)从画面上方随机产生的敌人(单词): (3)从飞机头部发射

  • VUE+Canvas 实现桌面弹球消砖块小游戏的示例代码

    大家都玩过弹球消砖块游戏,左右键控制最底端的一个小木板平移,接住掉落的小球,将球弹起后消除画面上方的一堆砖块. 那么用VUE+Canvas如何来实现呢?实现思路很简单,首先来拆分一下要画在画布上的内容: (1)用键盘左右按键控制平移的木板: (2)在画布内四处弹跳的小球: (3)固定在画面上方,并且被球碰撞后就消失的一堆砖块. 将上述三种对象,用requestAnimationFrame()函数平移运动起来,再结合各种碰撞检查,就可以得到最终的结果. 先看看最终的效果: 一.左右平移的木板 最底

  • js H5 canvas投篮小游戏

    本文实例为大家分享了H5 canvas投篮小游戏实现代码,供大家参考,具体内容如下 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body onload="init(19,'mylegend',820,500,main,LEvent.INIT)"> <div

  • 使用vue.js编写蓝色拼图小游戏

    之前在网上看到<蓝色拼图>这款小游戏,作者是用jquery写的.于是便考虑能不能用vue.js优雅简单的编写出来呢? Later equals never!说干就干.首先理解游戏的规则:第一关为1*1的方块,第二关为2*2以此类推 该图为第三关3*3的方块.点击一个小方块,该方块和它相邻的方块的的颜色会从黄色变为蓝色,全部变为蓝色就过关了. 现在规则清楚了,开动吧! /*style*/ .game_bg{ background: #333; width: 600px; height: 600p

  • js+canvas实现简单扫雷小游戏

    扫雷小游戏作为windows自带的一个小游戏,受到很多人的喜爱,今天我们就来尝试使用h5的canvas结合js来实现这个小游戏. 要写游戏,首先要明确游戏的规则,扫雷游戏是一个用鼠标操作的游戏,通过点击方块,根据方块的数字推算雷的位置,标记出所有的雷,打开所有的方块,即游戏成功,若点错雷的位置或标记雷错误,则游戏失败. 具体的游戏操作如下 1.可以通过鼠标左键打开隐藏的方块,打开后若不是雷,则会向四个方向扩展 2.可以通过鼠标右键点击未打开的方块来标记雷,第二次点击取消标记 3.可以通过鼠标右键

  • 阿望教你用vue写扫雷小游戏

    前言 话说阿望还在大学时,某一天寝室突然停网了,于是和室友两人不约而同地打开了扫雷,比相同难度下谁更快找出全部的雷,玩得不亦乐乎,就这样,扫雷伴我们度过了断网的一周,是整整一周啊,不用上课的那种,可想而知我们是有多无聊了. 这两天临近过年了,该放假的已经放假了,不该放假的已经请假了,公交不打挤了,地铁口不堵了,公司也去了大半部分的人了,就留阿望这种不得不留下来值班的人守着空荡荡的办公室了,于是,多年前那种无所事事的断网心态再次袭来,于是,想玩扫雷的心再次蹦跶出来,于是,点开了电脑的附件,于是,发

随机推荐