JavaScript で H5 ゴールド コイン関数を実装する (サンプル コード)

JavaScript で H5 ゴールド コイン関数を実装する (サンプル コード)

今日は春節の金貨の赤い封筒のアクティビティを作りました。なかなか良い出来だと思います。皆さんと共有します。この小さなゲームは hilojs を使用して実装されています。詳細

ステップ1: プラグインをインストールする

npm i hilojs または yarn add hilojs

ステップ2: Asset.jsファイルを作成する

「hilojs」からHiloをインポートします。
デフォルトのHilo.Class.createをエクスポートします({
 ミックス: Hilo.EventMixin、
 queue: null, // クラスをダウンロード gold: null, // 金貨 wood: null, // 金貨 water: null, // 卵 fireElement: null, // 金貨 dirt: null, // 赤い封筒 person: null, // 車 score0: null, // 
 スコア1: null, // 
 スコア2: null, // 
 負荷() {
 imgs = [ とする
  {
  id: 'soil'、//赤い封筒 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', // 車 src: require('../../../assets/image/che1.png')
  }
 ];
 Hilo の LoadQueue を新規作成します。
 this.queue.add(画像);
 this.queue.on('complete', this.onComplete.bind(this));
 this.queue.on('エラー', (e) => {
  console.log('読み込みエラー', e)
 })
 キューを開始します。
 },
 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;
 //ダウンロード キューの完了イベント リスナーを削除します。this.queue.off('complete');
 // 完了すると this.fire('complete'); が公開されます。
 }
})

ステップ3: game.jsファイルを作成する

「hilojs」からHiloをインポートします。
import Asset from './Asset' //金貨の赤い封筒の車のパラメータを定義します import Gold from './gold' //金貨の赤い封筒の臭い卵をランダムに生成します import Hand from './hand' //車の初期化レベルの衝突 let startTime = 0
デフォルトクラスゲームをエクスポートする {
 コンストラクタ(ページ) {
 this.page = ページ
 //ゲーム時間を設定する this.gameTime = 0
 this.gameStatus = "準備完了"
 /*
  プレイゲーム開始、準備完了、ゲーム終了**/
 // ダウンロードキュー this.asset = new Asset()
 //Canvas オブジェクト 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
 スケール = 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
 }
 初期化() {
 this.asset.on('complete', 関数() {
  this.asset.off('完了')
  this.initStage()
 }.bind(これを));
 this.asset.load()
 }
 初期化ステージ() {
 // コンソールログ(this.width,this.height)
 // ステージ this.stage = new Hilo.Stage({
  レンダリングタイプ: 'キャンバス',
  幅: this.width,
  高さ: this.height、
  スケールX: this.scale、
  スケールY: this.scale、
  コンテナ: 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);
 //ティッカーを開始
 this.ticker.start(true);
 ゲームを開始します。
 }

 startGame() { //ゲームを開始する startTime = new Date().getTime()
 this.initZongzi();
 この.initHand()
 //this.beginBtn.removeFromParent()
 this.stage.removeChild(this.beginBtn)
 this.gameTime = this.setGameTime;
 this.スコア = 0;
 this.crashList = [];
 this.isEnd = false;
 this.gameStatus = "プレイ"

 this.calcTime()
 }
 calcTime() { //ゲーム時間 this.timerAll = setTimeout(() => {
  now = new Date().getTime() とします。
  差をparseInt((現在 - 開始時刻) / 1000)とします。
  (差 % 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);
 }
 クリア計算時間() {
 this.Gold.score[0] = 5
 this.Gold.score[2] = 5
 this.Gold.enemySpeed ​​= 1000
 this.Gold.redスピード = 1000
 this.Gold.danSpeed ​​= 1000
 タイムアウトをクリアします(this.timerAll);
 }
 gameOver() { // ゲームが終了したら this.Gold.stopCreateEnemy() を呼び出す

 this.gameStatus = "準備完了"
 this.initBeginBtn()

 //this.hand.removeChild(this.hand.score)
 this.stage.removeChild(this.hand)
 }
 initZongzi() 金貨の赤い封筒を初期化します this.Gold = new Gold({
  id: 'ゴールド',
  高さ: this.height、
  幅: this.width,
  敵のスピード: this.enemySpeed、
  redSpeed: this.redSpeed、
  danSpeed: this.danSpeed、
  作成スピード: this.createSpeed、
  pointEnabled: false, // イベントを閉じないとステージを操作できませんbindingSmallGoldList: [this.asset.gold, this.asset.water, this.asset.soil],
  開始時間
 }).addTo(this.stage, 2)
 //ステージ更新 this.stage.onUpdate = this.onUpdate.bind(this);
 }
 initHand(){//手を初期化する this.hand = new Hand({
  id: '手',
  img: this.asset.person,
  高さ: this.asset.person.height、
  幅: 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') {
  戻る
 }
 // console.log('衝突', this.crashList)
 num = [] とします
 this.crashList.forEach(e => {
  e == 'dan'の場合{
  num.push(e)
  }
 })
 this.danNum = 数値.長さ
 if (num.length >= 3){//ゲームオーバー console.log('ゲームオーバー')
  this.clearCalcTime()
  this.isEnd = true;
  this.gameOver()
  戻る
 }
 this.Gold.children.forEach(item => {
  if (this.hand.checkCollision(item)) {
  
  (item.drawable.image.src.indexOf("赤") != -1) の場合 {
   this.crashList.push('赤')
  }
  (item.drawable.image.src.indexOf("money3") != -1) の場合 {
   this.crashList.push('money3')
  }
  (item.drawable.image.src.indexOf("dan​​") != -1) の場合 {
   this.crashList.push('dan')
  }
  // 衝突 item.over();
  this.score += item.score || 0;
  スイッチ (item.score) {
   ケース-1:
   this.hand.addScore(this.asset.score0)
   壊す;
   ケース1:
   this.hand.addScore(this.asset.score1)
   壊す;
   ケース2:
   this.hand.addScore(this.asset.score2)
   壊す;

   デフォルト:
   壊す;
  }
  }
 })
 }
 initBeginBtn() {
 }
}

ステップ4: gold.jsファイルを作成する

「hilojs」からHiloをインポートします。
'./SmallGold' から SmallGold をインポートします
Enemy = Hilo.Class.create({
 拡張: Hilo.Container、
 
 タイマー: null, // timerSmallGoldList: [],
 敵の速度: 0,
 赤スピード: 0,
 速度: 0,
 作成速度: 0,
 スコア: [5, 0, 5],
 トゥイーン: null、
 開始時間: null、
 コンストラクタ: 関数 (プロパティ) {
 Enemy.superclass.constructor.call(this, properties);
 this.startTime = プロパティ.startTime
 
 Hilo のインスタンスを初期化します。
 敵を作成します。
 これを開始して敵を作成します。
 },
 
 敵を作成します(){ 
 now = new Date().getTime() とします。
 差をparseInt((now - this.startTime) / 200)とします。
 
 インデックスを null にします。
 差を今とします = parseInt((now - this.startTime) / 1000)
 
 (0 <= 差現在 && 差現在 <= 60)の場合{
  差が 0 の場合
  インデックス = 0
  this.createGold(インデックス、this.enemySpeed)
  } else if (difference % 70 == 0){//0-15 秒、1 障害物卵インデックス = 1
  this.createGold(インデックス、this.danSpeed)
  } else if (difference % 147 == 0 || Difference % 154 == 0){//15-30 秒障害物卵 2 (150-155)
  インデックス = 1
  this.createGold(インデックス、this.danSpeed)
  } else if (差 % 222 == 0 || 差 % 226 == 0 || 差 % 235 == 0){//30-45 秒 障害物卵 3 (225-230)
  インデックス = 1
  this.createGold(インデックス、this.danSpeed)
  } else if (difference % 296 == 0 || Difference % 302 == 0 || Difference % 307 == 0 || Difference % 311 == 0) { // 60 秒、障害物卵 4 個 index = 1
  this.createGold(インデックス、this.danSpeed)
  } それ以外 {
  数値 = this.random(0, 100);
  if (number < 40) { //0 は金貨、2 桁は赤い封筒、1 は卵、インデックス = 0
   this.createGold(インデックス、this.enemySpeed)
  } それ以外の場合 (数値 <= 100) {
   インデックス = 2
   this.createGold(インデックス、this.redSpeed)
  }

  }
  
 } それ以外 {
  nowmiao = 差 - 300
  if (nowmiao % 70 == 0 || nowmiao % 75 == 0 || nowmiao % 78 == 0 || nowmiao % 85 == 0) { // 0-15 秒、障害物卵 4 個 index = 1
  this.createGold(インデックス、this.danSpeed)
  } それ以外 {
  数値 = this.random(0, 100);
  if (number < 40) { //0 は金貨、2 桁は赤い封筒、1 は卵、インデックス = 0
   this.createGold(インデックス、this.enemySpeed)
  } それ以外の場合 (数値 <= 100) {
   インデックス = 2
   this.createGold(インデックス、this.redSpeed)
  }

  }
  
 }
 },
 createGold(インデックス、敵のスピード) {
 保留 = 未定義
 (this.SmallGoldList[index].width && this.SmallGoldList[index].height) の場合 {
  ホールド = 新しい SmallGold({
  画像: this.SmallGoldList[index],
  矩形: [0, 0, this.SmallGoldList[index].width, this.zongziList[index].height],
  幅: this.SmallGoldList[index].width / 2,
  高さ: this.SmallGoldList[index].height / 2,
  // スケールX: 0.5,
  // スケールY: 0.5,
  }).addTo(これ);
 }
 widthScreen = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth とします
 heightScreen = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight とします

 ホールドx = 0.45 * 幅スクリーン;
 ホールドy = 0.4 * 高さスクリーン;
 

 hold.score = this.score[インデックス]

 this.tween.to(hold, {
  x: this.random(0, (this.width - this.SmallGoldList[0].width / 2)),
  y: この高さ
 }, {
  持続時間: 1400 / 敵の速度 * 1000、
  ループ: false、
  完了時: () => {
  保持します。親から削除します。
  }
 });
 },
 ランダム(下限, 上限) {
 Math.floor(Math.random() * (upper - lower + 1)) + lower を返します。
 },
 beginCreateEnemy() { //生成を開始する this.timer = setInterval(() => {
  敵を作成します。
 }, this.createSpeed);
 },
 stopCreateEnemy(){//生成を停止し、すべて削除します。clearInterval(this.timer)
 this.removeAllChildren()
 },
 checkCollision(enemy) { //衝突検出 for (var i = 0, len = this.children.length; i < len; i++) {
  敵のヒットテストオブジェクトがthis.children[i]、trueの場合) {
  true を返します。
  }
 }
 false を返します。
 }
})

デフォルトの敵をエクスポート

ステップ5: hand.jsファイルを作成する

「hilojs」からHiloをインポートします。
手 = Hilo.Class.create({
 拡張: Hilo.Container、

 // 画像img: null,
 //車のボウル: null,
 //スコア: null、

 コンストラクタ(プロパティ) {
 hand.superclass.constructor.call(this, properties)
 この.initHand()
 },
 initHand() { //背景を初期化 this.hand = new Hilo.Bitmap({
  id: '手',
  画像: this.img,
  矩形: [0, 0, this.img.width, this.img.height],
  幅: this.img.width / 2,
  高さ: this.img.height / 2,
  // スケールX: 0.5,
  // スケールY: 0.5,
 }).addTo(これ);
 },
 addScore(image) { //ポイントを追加 if (this.img.width && image.width) {
  this.score = 新しいHilo.Bitmap({
  id: 'スコア',
  画像: 画像、
  矩形: [0, 0, 画像?.幅 || 0, 画像?.高さ || 0],
  x: (this.img.width - image.width) / 2,
  y: -画像の高さ
  }).addTo(これ);
 }

 if (this.img.width && image.width) {
  Hilo.Tween.to(this.score, {
  x: (this.img.width - image.width / 2) / 2、
  y: -2 * 画像の高さ、
  アルファ: 0,
  幅: image.width / 2,
  高さ: image.height / 2
  }, {
  期間: 600、
  //遅延: 100,
  イージー: Hilo.Ease.Quad.EaseIn、
  完了時: () => {

  }
  });
 }

 },
 // 衝突検出 checkCollision(enemy) {
 敵のヒットテストオブジェクトがthis.handの場合、trueになります。
  true を返します。
 }
 false を返します。
 }
})

デフォルトのハンドをエクスポート

ステップ6: SmallGold.jsファイルを作成する

「hilojs」からHiloをインポートします。
SmallGold = Hilo.Class.create({
 拡張: Hilo.Bitmap、
 コンストラクタ: 関数 (プロパティ) {
 SmallGold.superclass.constructor.call(this, properties);
 this.onUpdate = this.onUpdate.bind(this);
 },
 以上(){
 親から削除します。
 },
 更新() {
 (this.parent.height < this.y)の場合{
 親から削除します。
 戻る
 }
 }
 })
 
エクスポートデフォルト SmallGold

私はこれをvueで使用しています

<テンプレート>
 <div class="fix">
 <div class="hilo">
 <div ref="hilo" class="canvas"></div>
 <img src="../../assets/image/youton3.png" alt="" class="tong" />
 
 <div class="スコア">
 <div class="left">
  <img :src="headimgurl" alt="" class="headimgurl" />
  <div class="p1">
  <p class="p2">プレイヤー: {{ nickname }}</p>
  <p class="p3">
  スコア: {{ score }}
  <span
  ><画像
   src="../../assets/image/dan21.png"
   代替案=""
   クラス="danNum"
  />x{{ danNum }}</span
  >
  </p>
  </div>
 </div>
 </div>
 </div>
 </div>
</テンプレート>

<スクリプト>
「./js/game」からゲームをインポートします。
エクスポートデフォルト{
 名前:「ゲーム」、

 データ() {
 戻る {
 ゲーム: 新しいゲーム()、
 
 };
 },
 計算: {
 スコア() {
 // ゲームスコア return this.game.score;
 },
 ダン番号() {
 //衝突した黒い卵の数 return this.game.danNum;
 },
 
 },
 時計:
 "ゲーム終了": {
 ハンドラ(新しい名前) {
 // コンソールログ(新しい名前);
 if (新しい名前) {
  this.goTo();
 }
 },
 即時: true、
 },
 },
 マウント() {
 this.$nextTick(() => {
 this.game.page = this.$refs.hilo;
 このゲームを初期化します。
 });
 
 },
 破棄する前に() {
 ゲームオーバー();
 },
 破棄された() {},
 メソッド: {
 移動(){}
 },
};
</スクリプト>

最終的な効果

インク14991c2b2aa5fad93d3ebf6a51a933c3_LI

H5ゴールドコイン機能のJavaScript実装(サンプルコード)に関するこの記事はこれで終わりです。JavaScriptゴールドコインに関するより関連性の高いコンテンツについては、123WORDPRESS.COMの過去の記事を検索するか、以下の関連記事を引き続き閲覧してください。今後とも123WORDPRESS.COMを応援していただければ幸いです。

以下もご興味があるかもしれません:
  • JavaScript+HTML5 キャンバスで虫眼鏡効果の完全な例を実現
  • JavaScript + HTML5 キャンバス描画時計機能の例
  • JS+HTML5 Canvasでシンプルな書き込みボード機能を実現する例

<<:  Docker 実行時にユーザーとグループを管理する方法

>>:  Dockerボリューム権限管理の詳細な説明

推薦する

Nginx 転送ソケットポート設定の詳細な説明

Nginx によるソケット ポート転送の一般的なシナリオ: オンライン学習アプリケーションでは、通常...

Hyper-V インストール CentOS 8 の問題の分析

CentOS 8 がリリースされてから随分経ちました。Linux 仮想マシンをいじっている人間として...

Vueのドラッグ可能なコンポーネントであるVue Smooth DnDの使用方法の詳細な説明

目次紹介とデモAPI: コンテナ財産ライフサイクルコールバックイベントAPI: ドラッグ可能実際の戦...

MySQLテーブルパーティショニングプログラムを変更する方法

MySQLテーブルパーティショニングプログラムを変更する方法1. サブテーブルの実装の原則は次のとお...

純粋な CSS で「テキストオーバーフローの切り捨てと省略」を実装するいくつかの方法

私たちの日常的な開発作業では、テキストのオーバーフロー、切り捨て、省略は、考慮する必要がある非常に一...

MySQLの比較演算子正規表現マッチングREGEXPの使用の詳細な説明

1. データを初期化する `test_01` が存在する場合はテーブルを削除します。 テーブル「te...

要素 el-button ボタンコンポーネントの使用の詳細な説明

1. 背景ボタンは非常によく使われており、Element のボタン機能は非常に包括的です。この記事で...

Nginxサービス500:内部サーバーエラーの原因の1つ

500 (内部サーバー エラー) サーバーでエラーが発生したため、要求を完了できませんでした。 50...

HTML に埋め込まれた Flash HTML ウェブページ コードに Flash ファイルを埋め込むソリューション (パート 2)

上の記事で、SWFObject V1.5 の使い方の紹介は一旦終了です。これから、SWFObject...

Linux でログインタイムアウト後に非アクティブなユーザーを自動的にログアウトする

方法1: .bashrcまたは.bash_profileファイルを変更するこれは、ホーム ディレクト...

MySQL 8の新機能ROLEの詳しい説明

MySQL ROLE はどのような問題を解決しますか?プロフェッショナルな資質を持ち、権限管理に細心...

CSS で 2 つの固定列と 1 つの適応列を実装するいくつかの方法

この記事では、CSS で 2 つの固定列と 1 つのアダプティブ列を実装するいくつかの方法を紹介し、...

ウェブページの読みやすさを向上させるいくつかの方法

1. 対照的な色を使用します。ここでのコントラストとは、テキストの色と背景色のコントラストを指します...

MySQL でストアド プロシージャを作成し、ループでレコードを追加する方法

この記事では、例を使用して、MySQL でストアド プロシージャを作成し、ループでレコードを追加する...

vscode で console.log を書く 2 つの簡単な方法の詳細な説明

(I) 方法 1: 事前にスクリプト タグ内に直接定義します。この HTML ファイルにのみ適用され...