iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 17
0
自我挑戰組

重新開始的Vue.js 30day系列 第 18

從頭開始的Javascript 入門 -實作demo Whack A Mole Game Day16

Whack A Mole Game 30day


決定以30js 裡面範例 來做一個實作demo 打地鼠遊戲

demo

https://codepen.io/chiakilalala/pen/MvvLpB

步驟

function randomTime(min, max) {
  return Math.round(Math.random() * (max - min) + min);
}

//隨機老鼠上洞的時間

2 隨機決定哪個洞有老鼠跳來跳去

function randomHole(holes) {
  const idx = Math.floor(Math.random() * holes.length);
  //亂數洞
  const hole = holes[idx];
  if (hole === lastHole) {
    console.log("Ah that is the same one bud");
    return randomHole(holes);
  }

  lastHole = hole;
  return hole;
}

3.因為要避免亂數洞裏同時出現老鼠兩次

if (hole === lastHole) {
  console.log("Ah that is the same one bud");
  return randomHole(holes);
}

lastHole = hole;

4.設定時間到了 就要移除讓老鼠從洞跳到上面的動作

function peep() {
  const time = randomTime(200, 1000);
  const hole = randomHole(holes);
  hole.classList.add('up');

  setTimeout(() => {
    hole.classList.remove('up');
    if(!timeUp) peep();
  }, time);
}

5.做一個開始按鈕

<button onClick="startGame()">START</button>
function startGame() {
  scoreBoard.textContent = 0;
  timeUp = false; // in case page reload 
  score = 0;
  peep();

  setTimeout(() => timeUp = true, 10000);
}
//定義遊戲時間動作是10sec 設定時間 timeUp = true

The bonk(e) function

function bonk(e) {
  if(!e.isTrusted) return; // cheater
  score ++;
  this.classList.remove('up');
  scoreBoard.textContent = score;
}

moles.forEach(mole => mole.addEventListener('click', bonk));

//e.isTrusted 這個特性是當我們沒點到洞產生的js屬性 他是點擊產生的


javascript

Math.round() 四捨五入
Math.random() 隨機產生0與1 不包含之間的數值
Math.floor() 向下取整數 或小於 等於指定數值的整數
Math.ceil() 向上取整數 或大於 等於指定數值的整數
亂數介紹
setTimeout() 本身可以在執行功能時工作


上一篇
從頭開始的Javascript 入門 -Constructor 建構式 ES6 Day15
下一篇
從頭開始的Javascript 入門 -Speech Detection Day17
系列文
重新開始的Vue.js 30day21
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言