H5实现接金币小游戏

今日做出做出一个春节接金币红包的活动,感觉挺不错的分享给大家
这个小游戏采用hilojs实现的,详情
实现效果查看

第一步:安装插件
npm i hilojs或者yarn add hilojs
第二步:创建一个Asset.js文件
import Hilo from "hilojs";
export default Hilo.Class.create({
    Mixes: Hilo.EventMixin,
    queue: null,  // 下载类
    gold: null,   // 金币
    wood: null,   // 金币
    water: null,   // 蛋
    fireElement: null,   // 金币
    soil: null, // 红包
    person: null, // 车
    score0: null,   // -1分
    score1: null,   // +1分
    score2: null,   // +2分
    load() {
        let imgs = [

            {
                id: 'soil',//红包
                src: 'https://sunndybody.gitee.io/monthover/red.png'
            },
            {
                id: 'water',//蛋
                src: 'https://sunndybody.gitee.io/monthover/dan.png'

            },
            {
                id: 'person',//车
                src: 'https://sunndybody.gitee.io/monthover/che1.png',

            },
            {
                id: 'gold',//金币
                src: 'https://sunndybody.gitee.io/monthover/money3.png'
            },


        ];
        this.queue = new Hilo.LoadQueue();
        this.queue.add(imgs);
        this.queue.on('complete', this.onComplete.bind(this));
        this.queue.on('error', (e) => {
            console.log('加载出错', e)
        })
        this.queue.start();
    },
    onComplete() { //加载完成
        console.log('加载完成')
        this.gold = this.queue.get('gold').content;//金币
        this.water = this.queue.get('water').content;//蛋
        this.soil = this.queue.get('soil').content;//红包
        this.person = this.queue.get('person').content;
        //删除下载队列的complete事件监听
        this.queue.off('complete');
        // complete暴露
        this.fire('complete');
    }
})
第三步:创建一个game.js文件
import Hilo from "hilojs";
import Asset from './Asset.js'//定义金币红包车参数
import Gold from './gold.js'//随机生成金币红包臭蛋
import Hand from './hand.js'//汽车初始化级碰撞
const setTime = 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000;//设置初始化时间
let startTime = 0
export default class game {
    constructor(page) {
        this.page = page
        //设置的游戏时间
        this.setGameTime = setTime//设置时间
        this.gameTime = 0
        this.gameStatus = "ready"
        /*
          play 游戏开始
          ready 游戏结束
        **/ 
        // 下载队列
        this.asset = new Asset()
        // 画布对象
        this.stage = null

        // 画布信息 
        this.width = (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) * 2
        // this.height = innerHeight * 2 < 1334 ? innerHeight * 2 : 1334
        this.height = (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight) * 2
        this.scale = 0.5

        // 定时器对象
        this.ticker = null

        //金币红包臭蛋
        this.Gold = null
        //金币红包臭蛋下落速度
        this.enemySpeed = 1000//金币下落速度
        this.redSpeed = 1000//红包下落速度
        this.danSpeed = 1000//红包下落速
        //金币红包臭蛋生成速度
        this.createSpeed = 200
        //接金币红包臭蛋的车
        this.Hand = null
        //开始按钮
        this.beginBtn = null
        //分数
        this.score = 0
        //定义一个碰撞的数组
        this.crashList = []
        this.isEnd = false
        //砸中臭蛋数量
        this.danNum = 0
        //定时器
        this.timerAll = null
    }
    init() {
        this.asset.on('complete', function () {
            this.asset.off('complete')
            this.initStage()
        }.bind(this));
        this.asset.load()
    }
    initStage() {
        // console.log(this.width,this.height)
        // 舞台
        this.stage = new Hilo.Stage({
            renderType: 'canvas',
            width: this.width,
            height: this.height,
            scaleX: this.scale,
            scaleY: this.scale,
            container: this.page
        });
        this.stage.enableDOMEvent([Hilo.event.POINTER_START, Hilo.event.POINTER_MOVE, Hilo.event.POINTER_END]);

        // 启动定时器刷新页面 参数为帧率
        this.ticker = new Hilo.Ticker(60)
        // 舞台添加到定时队列中
        this.ticker.addTick(this.stage)
        // 添加动画类到定时队列
        this.ticker.addTick(Hilo.Tween);
        //启动ticker
        this.ticker.start(true);
        this.startGame();
    }

    startGame() {   //开始游戏
        startTime = new Date().getTime()
        this.initZongzi();
        this.initHand()
        //this.beginBtn.removeFromParent()
        this.stage.removeChild(this.beginBtn)
        this.gameTime = this.setGameTime;
        this.score = 0;
        this.crashList = [];
        this.isEnd = false;
        this.gameStatus = "play"

        this.calcTime()
    }
    calcTime() { //游戏时间
        this.timerAll = setTimeout(() => {
            let now = new Date().getTime()
            let difference = parseInt((now - startTime) / 1000)
            if (difference % 30 == 0) {
                this.Gold.score[0] = this.Gold.score[0] + 5
                this.Gold.score[2] = this.Gold.score[2] + 5
                this.Gold.enemySpeed = this.Gold.enemySpeed + 500
                this.Gold.redSpeed = this.Gold.redSpeed + 200
                this.Gold.danSpeed = this.Gold.danSpeed + 300
            }
            // console.log(this.Gold.score, this.Gold.enemySpeed)

            if (this.gameTime > 0) {
                this.gameTime--;
                this.calcTime()
            }
        }, 1000);
    }
    clearCalcTime() {
        this.Gold.score[0] = 5
        this.Gold.score[2] = 5
        this.Gold.enemySpeed = 1000
        this.Gold.redSpeed = 1000
        this.Gold.danSpeed = 1000
        clearTimeout(this.timerAll);
    }
    gameOver() {//游戏结束调用
        this.Gold.stopCreateEnemy()

        this.gameStatus = "ready"
        this.initBeginBtn()

        //this.hand.removeChild(this.hand.score)
        this.stage.removeChild(this.Hand)
    }
    initZongzi() {//初始化金币红包
        this.Gold = new Gold({
            id: 'Award',
            height: this.height,
            width: this.width,
            enemySpeed: this.enemySpeed,
            redSpeed: this.redSpeed,
            danSpeed: this.danSpeed,
            createSpeed: this.createSpeed,
            pointerEnabled: false, // 不关闭事件绑定 无法操作舞台
            awardList: [this.asset.gold, this.asset.water, this.asset.soil],
            startTime
        }).addTo(this.stage, 2)
        //舞台更新
        this.stage.onUpdate = this.onUpdate.bind(this);
    }
    initHand() {//初始化手
        this.Hand = new Hand({
            id: 'hand',
            img: this.asset.person,
            height: this.asset.person.height,
            width: this.asset.person.width,
            x: this.width / 2 - this.asset.person.width / 4,
            y: this.height - this.asset.person.height / 2 - 40
        }).addTo(this.stage, 1);
        Hilo.util.copy(this.Hand, Hilo.drag);
        this.Hand.startDrag([0, this.height - this.asset.person.height / 2 - 40, this.width - this.asset.person.width / 2 + 10, 0]);
    }
    onUpdate() {//舞台更新
        if (this.gameStatus == 'ready') {
            return
        }
        // console.log('碰撞', this.crashList)
        let num = []
        this.crashList.forEach(e => {
            if (e == 'dan') {
                num.push(e)
            }
        })
        this.danNum = num.length
        if (num.length >= 3) {//游戏结束
            console.log('游戏结束')
            this.clearCalcTime()
            this.isEnd = true;
            this.gameOver()
            return
        }
        this.Gold.children.forEach(item => {
            if (this.Hand.checkCollision(item)) {
                // console.log('pen', item.drawable.image.src)
                if (item.drawable.image.src.indexOf("red") != -1) {
                    this.crashList.push('red')
                }
                if (item.drawable.image.src.indexOf("money3") != -1) {
                    this.crashList.push('money3')
                }
                if (item.drawable.image.src.indexOf("dan") != -1) {
                    this.crashList.push('dan')
                }
                // 碰撞了
                item.over();
                this.score += item.score || 0;
                switch (item.score) {
                    case -1:
                        this.Hand.addScore(this.asset.score0)
                        break;
                    case 1:
                        this.Hand.addScore(this.asset.score1)
                        break;
                    case 2:
                        this.Hand.addScore(this.asset.score2)
                        break;

                    default:
                        break;
                }
            }
        })
    }
    initBeginBtn() {
    }
}
第四步:创建一个gold.js文件
import Hilo from "hilojs";
import SmallAward from './SmallAward'
let Enemy = Hilo.Class.create({
    Extends: Hilo.Container,
    SmallZongziImg: null,
    timer: null, // 定时器
    awardList: [],
    enemySpeed: 0,
    redSpeed: 0,
    danSpeed: 0,
    createSpeed: 0,
    score: [5, 0, 5],
    tween: null,
    startTime: null,
    constructor: function (properties) {
        Enemy.superclass.constructor.call(this, properties);
        this.startTime = properties.startTime
        //this.onUpdate = this.onUpdate.bind(this);
        this.tween = Hilo.Tween;
        this.creatEnemy();
        this.beginCreateEnemy();
    },
    random(lower, upper) {
        return Math.floor(Math.random() * (upper - lower + 1)) + lower;
    },
    creatEnemy() { // 生成金币红包蛋 0-15秒,障碍蛋1个;15-30秒障碍蛋2个;30-45秒障碍蛋3个;45秒-60s 障碍蛋4个
        let now = new Date().getTime()
        let difference = parseInt((now - this.startTime) / 200)
        // console.log('差', difference % 15)
        let index = null;
        let differenceNow = parseInt((now - this.startTime) / 1000)
        // console.log('秒数', differenceNow, difference)
        if (0 <= differenceNow && differenceNow <= 60) {
            if (difference == 0) {
                index = 0
                this.createGold(index, this.enemySpeed)
            } else if (difference % 70 == 0) {//0-15秒,障碍蛋1个
                index = 1
                this.createGold(index, this.danSpeed)
            } else if (difference % 147 == 0 || difference % 154 == 0) {//15-30秒障碍蛋2个(150-155)
                index = 1
                this.createGold(index, this.danSpeed)
            } else if (difference % 222 == 0 || difference % 226 == 0 || difference % 235 == 0) {//30-45秒障碍蛋3个(225-230)
                index = 1
                this.createGold(index, this.danSpeed)
            } else if (difference % 296 == 0 || difference % 302 == 0 || difference % 307 == 0 || difference % 311 == 0) {//60秒,障碍蛋4个
                index = 1
                this.createGold(index, this.danSpeed)
            } else {
                let number = this.random(0, 100);
                if (number < 40) {  //0为金币2位红包1为蛋
                    index = 0
                    this.createGold(index, this.enemySpeed)
                } else if (number <= 100) {
                    index = 2
                    this.createGold(index, this.redSpeed)
                }

            }
            // console.log('index',index)
        } else {
            let nowmiao = difference - 300
            if (nowmiao % 70 == 0 || nowmiao % 75 == 0 || nowmiao % 78 == 0 || nowmiao % 85 == 0) {//0-15秒,障碍蛋4个
                index = 1
                this.createGold(index, this.danSpeed)
            } else {
                let number = this.random(0, 100);
                if (number < 40) {  //0为金币2位红包1为蛋
                    index = 0
                    this.createGold(index, this.enemySpeed)
                } else if (number <= 100) {
                    index = 2
                    this.createGold(index, this.redSpeed)
                }

            }
            // console.log('index2',nowmiao,index)
        }
    },
    createGold(index, enemySpeed) {
        let hold = undefined
        if (this.awardList[index].width && this.awardList[index].height) {
            hold = new SmallAward({
                image: this.awardList[index],
                rect: [0, 0, this.awardList[index].width, this.awardList[index].height],
                width: this.awardList[index].width / 2,
                height: this.awardList[index].height / 2,
                // scaleX: 0.5,
                // scaleY: 0.5,
            }).addTo(this);
        }
        let widthScreen = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth
        let heightScreen = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight

        hold.x = 0.45 * widthScreen;
        hold.y = 0.4 * heightScreen;
        // hold.y = 600 * Math.random();
        // hold.x = this.random(0, (this.width - this.zongziList[0].width / 2));

        hold.score = this.score[index]

        this.tween.to(hold, {
            x: this.random(0, (this.width - this.awardList[0].width / 2)),
            y: this.height
        }, {
            duration: 1400 / enemySpeed * 1000,
            loop: false,
            onComplete: () => {
                hold.removeFromParent()
            }
        });
    },
    beginCreateEnemy() {//开始生成
        this.timer = setInterval(() => {
            this.creatEnemy();
        }, this.createSpeed);
    },
    stopCreateEnemy() {//停止生成并全部移除
        clearInterval(this.timer)
        this.removeAllChildren()
    },
    checkCollision(enemy) {//碰撞检测
        for (var i = 0, len = this.children.length; i < len; i++) {
            if (enemy.hitTestObject(this.children[i], true)) {
                return true;
            }
        }
        return false;
    }
})

export default Enemy
第五步:创建一个hand.js文件
import Hilo from "hilojs";
let Che = Hilo.Class.create({
    Extends: Hilo.Container,

    // 图
    img: null,
    //车
    bowl: null,
    //分数
    score: null,

    constructor: function (properties) {
        Che.superclass.constructor.call(this, properties)
        this.initHand()
    },
    initHand() {  //初始化背景
        this.hand = new Hilo.Bitmap({
            id: 'hand',
            image: this.img,
            rect: [0, 0, this.img.width, this.img.height],
            width: this.img.width / 2,
            height: this.img.height / 2,
            // scaleX: 0.5,
            // scaleY: 0.5,
        }).addTo(this);
    },
    addScore(image) { //加分
        // console.log('分',image)
        if (this.img.width && image.width) {
            this.score = new Hilo.Bitmap({
                id: 'score',
                image: image,
                rect: [0, 0, image?.width || 0, image?.height || 0],
                x: (this.img.width - image.width) / 2,
                y: -image.height
            }).addTo(this);
        }

        if (this.img.width && image.width) {
            Hilo.Tween.to(this.score, {
                x: (this.img.width - image.width / 2) / 2,
                y: -2 * image.height,
                alpha: 0,
                width: image.width / 2,
                height: image.height / 2
            }, {
                duration: 600,
                //delay: 100,
                ease: Hilo.Ease.Quad.EaseIn,
                onComplete: () => {

                }
            });
        }

    },

    // 碰撞检测
    checkCollision(enemy) {
        // console.log('can',enemy,this.hand)
        if (enemy.hitTestObject(this.hand, true)) {
            return true;
        }
        return false;
    }
})

export default Che
第六步:创建一个SmallAward.js文件
import Hilo from "hilojs";
let SmallAward = Hilo.Class.create({
    Extends: Hilo.Bitmap,
    constructor: function (properties) {
      SmallAward.superclass.constructor.call(this, properties);
      this.onUpdate = this.onUpdate.bind(this);
    },
    over(){
      this.removeFromParent();
    },
    onUpdate() {
      if (this.parent.height < this.y) {
        this.removeFromParent();
        return
      }
    }
  })
   
  export default SmallAward

我这是在vue中使用

  <template>
  <div class="fix">
    <div class="hilo">
      <div ref="hilo" class="canvas"></div>
      <img src="../../assets/image/hezi_120.png" alt="" class="tong" />
      <div class="score">
        <div class="left">
          <img src="../../assets/image/head.jpg" alt="" class="headimgurl" />
          <div class="p1">
            <p class="p3">
              得分:{{ score }}
              <span
                ><img
                  src="../../assets/image/dan21.png"
                  alt=""
                  class="danNum"
                />
                &nbsp; x{{ danNum }}</span
              >
            </p>
            <P class="pp">
              3个黑蛋游戏结束
            </P>
          </div>
        </div>
        <!-- 时间:{{ gameTime }} -->
      </div>
    </div>
  </div>
</template>

<script>
import Game from "./js/game";
// import { Toast } from "vant";
import pageTrack from "../../utils/track";

export default {
  name: "Home",
  mixins: [pageTrack],
  data() {
    return {
      game: new Game(),
      headimgurl: "",
      nickname: "",
    };
  },
  created() {},
  computed: {
    score() {
      //游戏分数
      return this.game.score;
    },
    danNum() {
      //游戏分数
      return this.game.danNum;
    },
    gameTime() {
      //游戏时间
      return this.game.gameTime;
    },
  },
  watch: {
    "game.isEnd": {
      handler(newName) {
        // console.log(newName);
        if (newName) {
          this.goTo();
        }
      },
      immediate: true,
    },
  },
  mounted() {
    let that = this;
    this.$nextTick(() => {
      that.game.page = this.$refs.hilo;
      that.game.init();
    });
  },
  beforeDestroy() {
    this.game.gameOver();
  },
  destroyed() {},
  methods: {
    goTo() {
      console.log("分数", this.score);
    },
    musicBtn() {},
  },
};
</script>
<style lang="scss" scope>
.hilo {
  width: 100%;
  height: 100vh;
  background-color: #130d20;
  background-image: url("../../assets/image/gamebj.png");
  background-repeat: no-repeat;
  background-size: 100% auto;
  background-position: bottom center;
  position: relative;
  overflow: hidden;
  .canvas {
    canvas {
      position: absolute !important;
      width: 100% !important;
      height: 99vh !important;
    }
  }
  .tong1 {
    position: absolute;
    width: 3rem;
    height: 1rem;
    top: 27vh;
    left: 43vw;
  }
  .tong {
    position: absolute;
    width: 5rem;
    height: 5rem;
    top: 15vh;
    left: 40vw;
    -webkit-animation: spin 3s linear 3s 5 alternate;
    animation: spin 3s linear infinite;
    transform-origin: 50% bottom;
  }
  @-webkit-keyframes spin {
    100% {
      -webkit-transform: rotate(0deg);
    }
    80% {
      -webkit-transform: rotate(-40deg);
    }
    70% {
      -webkit-transform: rotate(-30deg);
    }
    60% {
      -webkit-transform: rotate(-20deg);
    }
    50% {
      -webkit-transform: rotate(-10deg);
    }
    0% {
      -webkit-transform: rotate(0deg);
    }
  }

  @keyframes spin {
    100% {
      -webkit-transform: rotate(0deg);
    }
    80% {
      -webkit-transform: rotate(-40deg);
    }
    70% {
      -webkit-transform: rotate(-30deg);
    }
    60% {
      -webkit-transform: rotate(-20deg);
    }
    50% {
      -webkit-transform: rotate(-10deg);
    }
    0% {
      -webkit-transform: rotate(0deg);
    }
  }
  .score {
    position: absolute;
    top: 5vh;
    width: 100%;
    display: flex;
    justify-content: space-between;
    padding: 0 70px;
    box-sizing: border-box;
    .musicBtn {
      width: 0.8rem;
      height: 0.8rem;
      background: url("../../assets/image/music.png") no-repeat top center;
      background-size: 100% 100%;
    }

    @keyframes rotate {
      0% {
        -webkit-transform: rotate(0deg);
      }
      25% {
        -webkit-transform: rotate(90deg);
      }
      50% {
        -webkit-transform: rotate(180deg);
      }
      75% {
        -webkit-transform: rotate(270deg);
      }
      100% {
        -webkit-transform: rotate(360deg);
      }
    }
    .left {
      display: flex;
      color: #fff;
      .headimgurl {
        width: 50px;
        height: 50px;
        margin-right: 0.3rem;
        border-radius: 50%;
      }

      .p1 {
        display: flex;
        flex-direction: column;
        justify-content: center;
        .p3 {
          font-size: 30px;
          line-height: 50px;
          display: flex;
          span {
            box-sizing: border-box;
            display: flex;
            margin-left: 20px;
            justify-content: center;
            align-items: center;
            .danNum {
              width: 40px;
              height: 40px;
            }
          }
        }
        .pp{
          color:rgb(126, 137, 126);
          line-height: 30px;
          font-size: 15px;
        }
      }
    }
  }
}
</style>
  • 5
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
### 回答1: 德佟H5是一种基于HTML5和CSS3技术的移动开发框架,它可以实现跨平台、跨终端的应用程序开发。而在德佟H5中,连蓝牙打印机是一项非常重要的功能,它可以提高用户的工作效率,方便快捷。下来我们将详细介绍德佟H5实现蓝牙打印的过程。 首先,我们需要了解蓝牙打印机的工作原理。蓝牙打印需要依靠蓝牙协议进行通信,通过蓝牙打印机与设备之间的配对,将数据传输到打印机中,实现打印功能。 在德佟H5中,我们可以通过引入相关的蓝牙插件,来实现蓝牙打印功能。具体实现步骤如下: 1. 在页面中引入蓝牙插件,并初始化蓝牙连参数。 2. 蓝牙配对成功之后,获取打印机的MAC地址,并将其保存到本地。 3. 打印数据时,先判断本地是否保存了打印机MAC地址,若有,则直使用此MAC地址进行打印。 4. 将需要打印的数据转换为打印机可读的格式,通过蓝牙协议传输到打印机中。 需要注意的是,在实现蓝牙打印的过程中,还需考虑到蓝牙连的稳定性,以及不同型号的打印机之间可能存在的兼容性问题。因此,在实际应用中,还需进行多次测试和优化,确保蓝牙打印功能实现的准确性和稳定性。 总之,德佟H5实现蓝牙打印功能是一项技术含量颇高的任务,但只要掌握了相关的技术原理和实现方法,就能够轻松地实现蓝牙打印功能,提高工作效率,提升用户体验。 ### 回答2: 德佟是一家专注于打印机和扫描仪开发的厂商,他们的H5实现蓝牙打印功能可以帮助用户方便快捷地进行无线打印。 H5是HTML5的简称,它是一种用于开发Web应用的技术。德佟的H5实现蓝牙打印功能主要是通过Web蓝牙技术实现的。Web蓝牙技术可以让Web应用程序通过蓝牙口与设备通信,实现设备控制和数据交换。 德佟的H5实现蓝牙打印功能主要包括以下步骤: 1.用户打开打印机的H5页面,点击连蓝牙打印机按钮。 2.应用程序会扫描附近的蓝牙设备,并列出可选设备列表。用户选择需要连的打印机设备。 3.应用程序与打印机设备建立蓝牙连,发送打印任务。 4.打印机收到打印任务后,开始进行打印操作。 通过德佟的H5实现蓝牙打印功能可以帮助用户快速实现打印操作,提高工作效率。同时,它也可以避免使用传统打印机时需要繁琐的纸张预置和连线设置操作,并且避免了受连线长度限制的问题,非常方便实用。 ### 回答3: 德佟科技是一家专注于打印应用开发的公司,旗下的德佟云打印服务、德佟打印SDK等都是业内知名的产品。德佟的H5实现蓝牙打印,是将H5技术与蓝牙打印技术结合在一起,使得用户可以通过H5页面实现蓝牙打印功能。 具体来说,德佟的H5实现蓝牙打印的原理是通过JavaScript调用蓝牙打印SDK,SDK通过与蓝牙打印机建立蓝牙连,从而实现H5页面向蓝牙打印机发送打印指令的功能。德佟的蓝牙打印SDK支持多种蓝牙打印机品牌和型号,适用于各种场景下的打印需求,且API简单易用,方便开发者在页面中实现蓝牙打印功能。 德佟的H5实现蓝牙打印,可以广泛应用于餐饮、物流、医疗等各种行业。比如,在餐饮行业中,用户可以通过手机进行点餐,然后将订单通过蓝牙连打印机打印出来,提高了订单的准确性和工作效率。总之,德佟的H5实现蓝牙打印为用户提供了一种方便快捷的打印解决方案,帮助用户实现高效的业务流程和操作。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值