JavaScript实现H5接金币功能

Alone 等级 762 0 0
标签: Javascript

今日做出做出一个春节接金币红包的活动,感觉挺不错的分享给大家 这个小游戏采用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,   // 
    score1: null,   // 
    score2: null,   // 
    load() {
        let imgs = [
            {
                id: 'soil',//红包
                src: require('../../../assets/image/red.png')
            },
            {
                id: 'water',//蛋
                src: require('../../../assets/image/dan.png')
            },
            {
                id: 'gold',//金币
                src: require('../../../assets/image/money3.png')
            },
            {
                id: 'person',//车
                src: require('../../../assets/image/che1.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'//定义金币红包车参数
import Gold from './gold'//随机生成金币红包臭蛋
import Hand from './hand'//汽车初始化级碰撞
let startTime = 0
export default class game {
    constructor(page) {
        this.page = page
        //设置的游戏时间

        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
            }

            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: 'gold',
            height: this.height,
            width: this.width,
            enemySpeed: this.enemySpeed,
            redSpeed: this.redSpeed,
            danSpeed: this.danSpeed,
            createSpeed: this.createSpeed,
            pointerEnabled: false, // 不关闭事件绑定 无法操作舞台
            SmallGoldList: [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)) {

                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 SmallGold from './SmallGold'
let Enemy = Hilo.Class.create({
    Extends: Hilo.Container,

    timer: null, // 定时器
    SmallGoldList: [],
    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.tween = Hilo.Tween;
        this.creatEnemy();
        this.beginCreateEnemy();
    },

    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)

        let index = null;
        let differenceNow = parseInt((now - this.startTime) / 1000)

        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)
                }

            }

        } 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)
                }

            }

        }
    },
    createGold(index, enemySpeed) {
        let hold = undefined
        if (this.SmallGoldList[index].width && this.SmallGoldList[index].height) {
            hold = new SmallGold({
                image: this.SmallGoldList[index],
                rect: [0, 0, this.SmallGoldList[index].width, this.zongziList[index].height],
                width: this.SmallGoldList[index].width / 2,
                height: this.SmallGoldList[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.score = this.score[index]

        this.tween.to(hold, {
            x: this.random(0, (this.width - this.SmallGoldList[0].width / 2)),
            y: this.height
        }, {
            duration: 1400 / enemySpeed * 1000,
            loop: false,
            onComplete: () => {
                hold.removeFromParent()
            }
        });
    },
     random(lower, upper) {
        return Math.floor(Math.random() * (upper - lower + 1)) + lower;
    },
    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 hand = Hilo.Class.create({
    Extends: Hilo.Container,

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

    constructor(properties) {
        hand.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) { //加分
        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) {
       if (enemy.hitTestObject(this.hand, true)) {
            return true;
        }
        return false;
    }
})

export default hand
第六步:创建一个SmallGold.js文件
import Hilo from "hilojs";
let SmallGold= Hilo.Class.create({
    Extends: Hilo.Bitmap,
    constructor: function (properties) {
      SmallGold.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 SmallGold

我这是在vue中使用

  <template>
  <div class="fix">
    <div class="hilo">
      <div ref="hilo" class="canvas"></div>
      <img src="../../assets/image/youton3.png" alt="" class="tong" />

      <div class="score">
        <div class="left">
          <img :src="headimgurl" alt="" class="headimgurl" />
          <div class="p1">
            <p class="p2">玩家:{{ nickname }}</p>
            <p class="p3">
              得分:{{ score }}
              <span
                ><img
                  src="../../assets/image/dan21.png"
                  alt=""
                  class="danNum"
                />x{{ danNum }}</span
              >
            </p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Game from "./js/game";
export default {
  name: "game",

  data() {
    return {
      game: new Game(),

    };
  },
  computed: {
    score() {
      //游戏分数
      return this.game.score;
    },
    danNum() {
      //黑蛋碰撞个数
      return this.game.danNum;
    },

  },
  watch: {
    "game.isEnd": {
      handler(newName) {
        // console.log(newName);
        if (newName) {
          this.goTo();
        }
      },
      immediate: true,
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.game.page = this.$refs.hilo;
      this.game.init();
    });

  },
  beforeDestroy() {
    this.game.gameOver();
  },
  destroyed() {},
  methods: {
      goTo(){}
  },
};
</script>

最后效果

JavaScript实现H5接金币功能

收藏
评论区

相关推荐

教你用200行代码写一个爱豆拼拼乐H5小游戏(附源码)
前言 本文将带大家一步步实现一个H5拼图小游戏,考虑到H5游戏的轻量级和代码体积,我没有使用react或vue这些框架,而采用我自己写的dom库和原生javascript来实现业务功能,具体库代码可见我的文章如何用不到200行代码写一款属于自己的js类库(https://juejin.im/post/6844903880707293198),构建工具我采
What the f*ck JavaScript?
What the fck JavaScript? 一个有趣和棘手的 JavaScript 示例列表。 JavaScript 是一种很好的语言。
JavaScript实现H5接金币功能
今日做出做出一个春节接金币红包的活动,感觉挺不错的分享给大家 这个小游戏采用hilojs实现的,详情(https://hiloteam.github.io/Hilo/docs/apizh/index.html) 第一步:安装插件 npm i hilojs或者yarn add hilojs 第二步:创建一个Asset.js文件 language i
js-Answers一
JavaScript的组成 JavaScript 由以下三部分组成: 1. ECMAScript(核心):JavaScript 语言基础 2. DOM(文档对象模型):规定了访问HTML和XML的接口 3. BOM(浏览器对象模型):提供了浏览器窗口之间进行交互的对象和方法 JS的基本数据类型和引用数据类型
javascript实践教程-01-javascript介绍
本节目标1. 了解javascript是什么。2. 了解javascript能干什么。 内容摘要本篇介绍了javascript是什么,为什么要用javascript,ECMAScript标准是什么等。阅读时间大约510分钟。 javascript是什么?javascript是世界上最流行的脚本语言,因为你在电脑、手机、平板上浏览的所有的网页,以及无数基于HT
JS动态加载JS
1、直接document.write <script language="javascript"> document.write("<script src='test.js'><\\/script>"); </script> 2、动态改变已有script的src属性 <script src='' id="s1"></script> <
JS导出页面为PDF文件,该如何操作?来看一眼就明白啦!
废话不多说,直接上代码。 1.资源文件或依赖 <script type="text/javascript" src="https://my.oschina.net//u/4265132/blog/4054317/js/canvg2.js"></script><script type="text/javascript" src="https://m
JS的另类写法(书签栏工具原型)
<script type="text/javascript"> javascript : void (function(version) { var scriptTag = document.createElement('script'); scriptTag.type = 'text/javascript';
Android原生和H5交互;Android和H5混合开发;WebView点击H5界面跳转到Android原生界面。
当时业务的需求是这样的,H5有一个活动商品列表的界面,IOS和Android共用这一个界面,点击商品可以跳转到Android原生的商品详情界面并传递商品ID;  大概就是**点击H5界面跳转到Android原生界面**; 好了,需求已经分析完毕了,Android只需要获取H5的点击事件和传递的参数; 来,上代码: /启用支持javascript
JavaScript 非常重要的几个概念
JavaScript是一门比较复杂的语言。如果你是一名JavaScript开发人员,不管处于什么样的水平,都有必要了解JavaScript的基本概念。小编最近的工作涉及到JavaScript,于是本文就介绍了几个非常重要的 JavaScript 概念,但绝对不是说JavaScript 开发人员只需要知道这些就可以了。 01-变量赋值(值与引用) Java
JavaScript基础之创建对象
![](https://oscimg.oschina.net/oscnet/361b5f13-d45b-403e-bff3-9a63013a7644.png)JavaScript对象的创建 ![](https://oscimg.oschina.net/oscnet/c5d755a1-2cca-4c62-8dba-372da7d7ab3b.jpg) 在Ja
JavaScript基础系列
![JavaScript基础系列](https://oscimg.oschina.net/oscnet/c1dc2f84f95d13105d79ba82a648f0c5eab.png) > JavaScript基础系列 ![image.png](https://oscimg.oschina.net/oscnet/e16bf4232aab0acb21c56
JavaScript的 基本数据类型
**第一:Javascript对象是** **第二:Javascript中** **第三:Javascript的对象是数据;** **第四:JavaScript 中的对象可以简单理解成"名称:值"对(name:value)。名称(name):"名称"部分是一个 JavaScript 字符串** **参考----------https://www
Node.js简介及如何学习Node.js
本文介绍Node.js的诞生史以及如何学习Node.js。 Node.js简史 --------- 从Node.js的命名上可以看到,Node.js的官方开发语言是JavaScript。之所以选择使用JavaScript,显然与JavaScript的开发人员多有关。总所周知,JavaScript是伴随着互联网的发展而火爆起来的,JavaScript也是前
阿里巴巴前端练习生学习笔记
字符串引擎和Javascript引擎的区别:是否对于DOM进行全部改变? 相关资料链接• Wiki MVC • Wiki MVVM • Mustach • Handlebars • React • Angular • Vue • Bootstrap • Ant Design • Fusion Des

热门文章

最新文章