JavaScript實現(xiàn)H5接金幣功能(實例代碼)
今日做出做出一個春節(jié)接金幣紅包的活動,感覺挺不錯的分享給大家
這個小游戲采用hilojs實現(xiàn)的,詳情
第一步:安裝插件
npm i hilojs或者yarn add hilojs
第二步:創(chuàng)建一個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事件監(jiān)聽
this.queue.off('complete');
// complete暴露
this.fire('complete');
}
})
第三步:創(chuàng)建一個game.js文件
import Hilo from "hilojs";
import Asset from './Asset'//定義金幣紅包車參數(shù)
import Gold from './gold'//隨機生成金幣紅包臭蛋
import Hand from './hand'//汽車初始化級碰撞
let startTime = 0
export default class game {
constructor(page) {
this.page = page
//設(shè)置的游戲時間
this.gameTime = 0
this.gameStatus = "ready"
/*
play 游戲開始
ready 游戲結(jié)束
**/
// 下載隊列
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
//分?jǐn)?shù)
this.score = 0
//定義一個碰撞的數(shù)組
this.crashList = []
this.isEnd = false
//砸中臭蛋數(shù)量
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]);
// 啟動定時器刷新頁面 參數(shù)為幀率
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() {//游戲結(jié)束調(diào)用
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, // 不關(guān)閉事件綁定 無法操作舞臺
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) {//游戲結(jié)束
console.log('游戲結(jié)束')
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() {
}
}
第四步:創(chuàng)建一個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
第五步:創(chuàng)建一個hand.js文件
import Hilo from "hilojs";
let hand = Hilo.Class.create({
Extends: Hilo.Container,
// 圖
img: null,
//車
bowl: null,
//分?jǐn)?shù)
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
第六步:創(chuàng)建一個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() {
//游戲分?jǐn)?shù)
return this.game.score;
},
danNum() {
//黑蛋碰撞個數(shù)
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>
最后效果

到此這篇關(guān)于JavaScript實現(xiàn)H5接金幣功能(實例代碼)的文章就介紹到這了,更多相關(guān)JavaScript接金幣內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Bootstrap時間選擇器datetimepicker和daterangepicker使用實例解析
這篇文章主要為大家詳細(xì)解析了Bootstrap時間選擇器datetimepicker和daterangepicker使用實例,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-09-09
JavaScript?顯示一個倒計時廣告牌的實現(xiàn)示例
本文主要介紹了JavaScript?顯示一個倒計時廣告牌的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-04-04
JS中Generator函數(shù)與async函數(shù)用法介紹
javascript中經(jīng)常會用到異步編程,在ES6之后我們使用的?Generator函數(shù)、async函數(shù)、promise都是我們異步編程的一大助力,這里我們主要講解Generator、async函數(shù),并且簡介他們之間的一些聯(lián)系,本篇文章會帶著一些簡易案例,方便大家理解使用2023-06-06
JS實現(xiàn)斐波那契數(shù)列的五種方式(小結(jié))
這篇文章主要介紹了JS實現(xiàn)斐波那契數(shù)列的五種方式(小結(jié)),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
利用Print.js實現(xiàn)打印pdf、HTML及圖片(可設(shè)置樣式可分頁)
在我們需要在頁面中打印某個區(qū)域的內(nèi)容或者生成pdf的時候,我們可以直接用printJs庫,這篇文章主要給大家介紹了關(guān)于利用Print.js實現(xiàn)打印pdf、HTML及圖片的相關(guān)資料,可設(shè)置樣式可分頁,需要的朋友可以參考下2024-05-05
抓取JavaScript動態(tài)加載的內(nèi)容的方法總結(jié)
JavaScript動態(tài)加載的內(nèi)容常見于現(xiàn)代Web應(yīng)用中,用于增強用戶體驗和減少初始頁面加載時間,然而,這些動態(tài)加載的內(nèi)容對于傳統(tǒng)的網(wǎng)頁抓取工具來說往往是不可見的,本文主要介紹了有JavaScript動態(tài)加載的內(nèi)容如何抓取,需要的朋友可以參考下2024-09-09

