JavaScript implements H5 gold coin function (example code)

JavaScript implements H5 gold coin function (example code)

Today I made a Spring Festival gold coin red envelope activity, which I feel is pretty good. I share it with you. This small game is implemented using hilojs. Details

Step 1: Install the plugin

npm i hilojs or yarn add hilojs

Step 2: Create an Asset.js file

import Hilo from "hilojs";
export default Hilo.Class.create({
 Mixes: Hilo.EventMixin,
 queue: null, // Download class gold: null, // Gold coin wood: null, // Gold coin water: null, // Egg fireElement: null, // Gold coin soil: null, // Red envelope person: null, // Car score0: null, // 
 score1: null, // 
 score2: null, // 
 load() {
 let imgs = [
  {
  id: 'soil', //red envelope src: require('../../../assets/image/red.png')
  },
  {
  id: 'water', //egg src: require('../../../assets/image/dan.png')
  },
  {
  id: 'gold', //gold src: require('../../../assets/image/money3.png')
  },
  {
  id: 'person', // car 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('Loading error', e)
 })
 this.queue.start();
 },
 onComplete() { //Loading completed console.log('Loading completed')
 this.gold = this.queue.get('gold').content;//Gold coinsthis.water = this.queue.get('water').content;//Eggsthis.soil = this.queue.get('soil').content;//Red envelopethis.person = this.queue.get('person').content;
 //Delete the complete event listener of the download queue this.queue.off('complete');
 // complete exposes this.fire('complete');
 }
})

Step 3: Create a game.js file

import Hilo from "hilojs";
import Asset from './Asset' //Define parameters of the gold coin red envelope car import Gold from './gold' //Randomly generate gold coin red envelope stinky eggs import Hand from './hand' //Car initialization level collision let startTime = 0
export default class game {
 constructor(page) {
 this.page = page
 //Set the game time this.gameTime = 0
 this.gameStatus = "ready"
 /*
  play game starts ready game ends**/
 // Download queue this.asset = new Asset()
 //Canvas object this.stage = null

 // Canvas information 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

 // Timer object this.ticker = null

 //Gold coin red envelope stinky egg this.Gold = null
 //Gold coin, red envelope, stinky egg falling speedthis.enemySpeed ​​= 1000//Gold coin falling speedthis.redSpeed ​​= 1000//Red envelope falling speedthis.danSpeed ​​= 1000//Red envelope falling speed//Gold coin, red envelope, stinky egg generation speedthis.createSpeed ​​= 200
 //The car that receives the gold coin, red envelope and stinky egg this.hand = null
 //Start button this.beginBtn = null
 //score this.score = 0
 //Define a collision array this.crashList = []
 this.isEnd = false
 //Number of rotten eggs hit this.danNum = 0
 //Timer 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)
 // Stage 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]);

 // Start the timer to refresh the page. The parameter is the frame rate this.ticker = new Hilo.Ticker(60)
 // The stage is added to the timing queue this.ticker.addTick(this.stage)
 // Add the animation class to the timing queue this.ticker.addTick(Hilo.Tween);
 //Start ticker
 this.ticker.start(true);
 this.startGame();
 }

 startGame() { //Start the game 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() { //Game time 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() { // Call this.Gold.stopCreateEnemy() when the game ends

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

 //this.hand.removeChild(this.hand.score)
 this.stage.removeChild(this.hand)
 }
 initZongzi() {//Initialize the gold coin red envelope 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, // The stage cannot be operated without closing event bindingSmallGoldList: [this.asset.gold, this.asset.water, this.asset.soil],
  startTime
 }).addTo(this.stage, 2)
 //Stage update this.stage.onUpdate = this.onUpdate.bind(this);
 }
 initHand() {//Initialize the hand 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() {//Stage update if (this.gameStatus == 'ready') {
  return
 }
 // console.log('collision', this.crashList)
 let num = []
 this.crashList.forEach(e => {
  if (e == 'dan') {
  num.push(e)
  }
 })
 this.danNum = num.length
 if (num.length >= 3) {//Game over console.log('Game over')
  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')
  }
  // Collision 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() {
 }
}

Step 4: Create a gold.js file

import Hilo from "hilojs";
import SmallGold from './SmallGold'
let Enemy = Hilo.Class.create({
 Extends: Hilo.Container,
 
 timer: null, // timerSmallGoldList: [],
 enemySpeed: 0,
 redSpeed: 0,
 Speed: 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.createEnemy();
 this.beginCreateEnemy();
 },
 
 createEnemy() { 
 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 seconds, 1 obstacle egg index = 1
  this.createGold(index, this.danSpeed)
  } else if (difference % 147 == 0 || difference % 154 == 0) {//15-30 seconds obstacle eggs 2 (150-155)
  index = 1
  this.createGold(index, this.danSpeed)
  } else if (difference % 222 == 0 || difference % 226 == 0 || difference % 235 == 0) {//30-45 seconds obstacle eggs 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 seconds, 4 obstacle eggs index = 1
  this.createGold(index, this.danSpeed)
  } else {
  let number = this.random(0, 100);
  if (number < 40) { //0 is a gold coin, 2 digits for a red envelope, 1 is an egg, 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 seconds, 4 obstacle eggs index = 1
  this.createGold(index, this.danSpeed)
  } else {
  let number = this.random(0, 100);
  if (number < 40) { //0 is a gold coin, 2 digits for a red envelope, 1 is an egg, 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() { //Start generating this.timer = setInterval(() => {
  this.createEnemy();
 }, this.createSpeed);
 },
 stopCreateEnemy() {//Stop generating and remove all clearInterval(this.timer)
 this.removeAllChildren()
 },
 checkCollision(enemy) { //Collision detection 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

Step 5: Create a hand.js file

import Hilo from "hilojs";
let hand = Hilo.Class.create({
 Extends: Hilo.Container,

 // Image img: null,
 //Car bowl: null,
 //score: null,

 constructor(properties) {
 hand.superclass.constructor.call(this, properties)
 this.initHand()
 },
 initHand() { //Initialize background 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) { //Add points 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: () => {

  }
  });
 }

 },
 // Collision detection checkCollision(enemy) {
 if (enemy.hitTestObject(this.hand, true)) {
  return true;
 }
 return false;
 }
})

export default hand

Step 6: Create a SmallGold.js file

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

I am using this in 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">Player: {{ nickname }}</p>
  <p class="p3">
  Score: {{ 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() {
 //Game score return this.game.score;
 },
 danNum() {
 //The number of black eggs collided 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>

Final effect

Inked14991c2b2aa5fad93d3ebf6a51a933c3_LI

This is the end of this article about JavaScript implementation of H5 gold coin function (example code). For more relevant JavaScript gold coin content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JavaScript+HTML5 canvas to achieve a complete example of magnifying glass effect
  • JavaScript + HTML5 canvas drawing clock function example
  • JS+HTML5 Canvas to achieve a simple writing board function example

<<:  Explain MySQL's binlog log and how to use binlog log to recover data

>>:  How to manage users and groups when running Docker

Recommend

js implements a simple English-Chinese dictionary

This article shares the specific code of js to im...

Detailed explanation of Vue development Sort component code

Table of contents <template> <ul class=&...

Detailed explanation of GaussDB for MySQL performance optimization

Table of contents background Inspiration comes fr...

Three useful codes to make visitors remember your website

Three useful codes to help visitors remember your...

How to modify the root user password in mysql 8.0.16 winx64 and Linux

Please handle basic operations such as connecting...

In-depth understanding of Vue's method of generating QR codes using vue-qr

Table of contents npm download step (1) Import (2...

Mysql5.7.14 Linux version password forgotten perfect solution

In the /etc/my.conf file, add the following line ...

Examples of 4 methods for inserting large amounts of data in MySQL

Preface This article mainly introduces 4 methods ...

How to implement paging query in MySQL

SQL paging query:background In the company's ...

Problems and solutions when replacing Oracle with MySQL

Table of contents Migration Tools Application tra...

About using Alibaba's iconfont vector icon in Vue

There are many import methods on the Internet, an...

CSS3 mouse hover transition zoom effect

The following is a picture mouse hover zoom effec...

How to use CSS to center a box horizontally and vertically (8 methods)

Original code: center.html : <!DOCTYPE html>...