JavaScript实现H5接金币功能(实例代码)

 更新时间:2021年2月23日 00:00  点击:2610

今日做出做出一个春节接金币红包的活动,感觉挺不错的分享给大家
这个小游戏采用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() { 
 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>

最后效果

Inked14991c2b2aa5fad93d3ebf6a51a933c3_LI

到此这篇关于JavaScript实现H5接金币功能(实例代码)的文章就介绍到这了,更多相关JavaScript接金币内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

[!--infotagslink--]

相关文章

  • 使用PHP+JavaScript将HTML页面转换为图片的实例分享

    这篇文章主要介绍了使用PHP+JavaScript将HTML元素转换为图片的实例分享,文后结果的截图只能体现出替换的字体,也不能说将静态页面转为图片可以加快加载,只是这种做法比较interesting XD需要的朋友可以参考下...2016-04-19
  • C#和JavaScript实现交互的方法

    最近做一个小项目不可避免的需要前端脚本与后台进行交互。由于是在asp.net中实现,故问题演化成asp.net中jiavascript与后台c#如何进行交互。...2020-06-25
  • 关于JavaScript中name的意义冲突示例介绍

    在昨天的《Javascript权威指南》学习笔记之十:ECMAScript 5 增强的对象模型一文中,对于一段代码的调试出现了一个奇怪现象,现将源代码贴在下面: 复制代码 代码如下: <script type="text/javascript"> function Person(){}...2014-05-31
  • javascript自定义的addClass()方法

    复制代码 代码如下: //element:需要添加新样式的元素,value:新的样式 function addClass(element, value ){ if (!element.className){ element.className = value; }else { newClassName = element.className; newClas...2014-05-31
  • JavaScript中的this关键字使用方法总结

    在javascritp中,不一定只有对象方法的上下文中才有this, 全局函数调用和其他的几种不同的上下文中也有this指代。 它可以是全局对象、当前对象或者任意对象,这完全取决于函数的调用方式。JavaScript 中函数的调用有以下...2015-03-15
  • JavaScript中逗号运算符介绍及使用示例

    有一道js面试题,题目是这样的:下列代码的执行结果是什么,为什么? 复制代码 代码如下: var i, j, k; for (i=0, j=0; i<10, j<6; i++, j++) { k = i+j; } document.write(k); 答案是显示10,这道题主要考察JavaScript的逗...2015-03-15
  • javascript的事件触发器介绍的实现

    事件触发器从字面意思上可以很好的理解,就是用来触发事件的,但是有些没有用过的朋友可能就会迷惑了,事件不是通常都由用户在页面上的实际操作来触发的吗?这个观点不完全正确,因为有些事件必须由程序来实现,如自定义事件,jQue...2014-06-07
  • 详解javascript数组去重问题

    首先,我想到的是另建一个结果数组,用来存储原始数组中不重复的数据。遍历原始数组依次跟结果数组中的元素进行比较,检测是否重复。于是乎,我写出了如下代码A: Array.prototype.clearRepetitionA = function(){ var resul...2015-11-08
  • ActiveX控件与Javascript之间的交互示例

    1、ActiveX向Javascript传参 复制代码 代码如下: <script language="javascript" for="objectname" event="fun1(arg)"> fun2(arg); </script> objectname为ActiveX控件名,通过<object>标签里的id属性设定,如下; 复制...2014-06-07
  • JavaScript获取浏览器信息的方法

    Window有navigator对象让我们得知浏览器的全部信息.我们可以利用一系列的API函数得知浏览器的信息.JavaScript代码如下:function message(){ txt = "<p>浏览器代码名: " + navigator.appCodeName + "</p>";txt+= "<p>...2015-11-24
  • Javascript类型转换的规则实例解析

    这篇文章主要介绍了Javascript类型转换的规则实例解析,涉及到javascript类型转换相关知识,对本文感兴趣的朋友一起学习吧...2016-02-27
  • 详解JavaScript操作HTML DOM的基本方式

    通过 HTML DOM,可访问 JavaScript HTML 文档的所有元素。 HTML DOM (文档对象模型) 当网页被加载时,浏览器会创建页面的文档对象模型(Document Object Model)。 HTML DOM 模型被构造为对象的树: 通过可编程的对象模型,Java...2015-10-23
  • 跟我学习javascript的最新标准ES6

    虽然ES6都还没真正发布,但已经有用ES6重写的程序了,各种关于ES789的提议已经开始了,这你敢信。潮流不是我等大众所能追赶的。潮流虽然太快,但我们不停下学习的步伐,就不会被潮流丢下的,下面来领略下ES6中新特性,一堵新生代JS...2015-11-24
  • javascript设计模式之解释器模式详解

    神马是“解释器模式”?先翻开《GOF》看看Definition:给定一个语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子。在开篇之前还是要科普几个概念: 抽象语法树: 解释器模式并未解释如...2014-06-07
  • JavaScript操作URL的相关内容集锦

    ---恢复内容开始---1.location.href.....(1)self.loction.href="http://www.cnblogs.com/url" window.location.href="http://www.cnblogs.com/url" 以上两个用法相同均为在当前页面打开URL页面 (2)this.locati...2015-10-30
  • javascript实现tab切换的四种方法

    tab切换在网页中很常见,故最近总结了4种实现方法。 首先,写出tab的框架,加上最简单的样式,代码如下: <!DOCTYPE html> <html> <head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><style> *{ pa...2015-11-08
  • 基于JavaScript如何实现私有成员的语法特征及私有成员的实现方式

    前言在面向对象的编程范式中,封装都是必不可少的一个概念,而在诸如 Java,C++等传统的面向对象的语言中, 私有成员是实现封装的一个重要途径。但在 JavaScript 中,确没有在语法特性上对私有成员提供支持, 这也使得开发人员使...2015-10-30
  • javascript实现数独解法

    生生把写过的java版改成javascript版,第一次写,很不专业,见谅。唉,我是有多闲。复制代码 代码如下: var Sudoku = { init: function (str) { this.blank = []; this.fixed = []; this.cell =...2015-03-15
  • javascript中slice(),splice(),split(),substring(),substr()使用方法

    1.slice();Array和String对象都有在Array中 slice(i,[j])i为开始截取的索引值,负数代表从末尾算起的索引值,-1为倒数第一个元素 j为结束的索引值,缺省时则获取从i到末尾的所有元素参数返回: 返回索引值从i到j的数组,原数组...2015-03-15
  • JavaScript预解析,对象详解

    这篇文章主要介绍了JavaScript预解析,对象的的相关资料,小编觉得这篇文章写的还不错,需要的朋友可以参考下,希望能够给你带来帮助...2021-11-10