0
Modern Web

## Step1

``````const holes = document.querySelectorAll('.hole');
const scoreBoard = document.querySelector('.score');
const moles = document.querySelectorAll('.mole');
let lastHole;

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

function randomHole(holes) {
const idx = Math.floor(Math.random() * holes.length);
const hole = holes[idx];
if (hole === lastHole) {
console.log('Ah nah thats the same one bud');
return randomHole(holes);
}
lastHole = hole;
return hole;
}
``````

### `Math.random()`

`Math.random()`函式會隨機回傳一個介於0~1的浮點數

## Step2

``````let timeUp = false;

function peep() {
const time = randomTime(200, 1000);
const hole = randomHole(holes);
setTimeout(() => {
hole.classList.remove('up');
if (!timeUp) peep();
}, time);
}
``````

``````.mole {
background: url('mole.svg') bottom center no-repeat;
background-size: 60%;
position: absolute;
top: 100%;
width: 100%;
height: 100%;
transition:all 0.4s;
}

.hole.up .mole {
top: 0;
}
``````

CSS這邊有一個`top`屬性，這個屬性會影響元素的垂直位置

## Step3

``````let score = 0;

function startGame() {
scoreBoard.textContent = 0;
timeUp = false;
score = 0;
peep();
setTimeout(() => timeUp = true, 10000)
}
``````

``````<button onClick="startGame()">Start!</button>
``````

## Step4

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

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