Whack A Mole Game JS 30day

Whack A Mole Game JS 30day


步驟

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() 本身可以在執行功能時工作

comments powered by Disqus