|
| 1 | +<!DOCTYPE html> |
| 2 | +<html lang="en"> |
| 3 | +<head> |
| 4 | + <meta charset="UTF-8"> |
| 5 | + <title>Whack A Mole!</title> |
| 6 | + <link href='https://fonts.googleapis.com/css?family=Amatic+SC:400,700' rel='stylesheet' type='text/css'> |
| 7 | + <link rel="stylesheet" href="style.css"> |
| 8 | +</head> |
| 9 | +<body> |
| 10 | + |
| 11 | + <h1>Whack-a-mole! <span class="score">0</span></h1> |
| 12 | + <button onClick="startGame()">Start!</button> |
| 13 | + |
| 14 | + <div class="game"> |
| 15 | + <div class="hole hole1"> |
| 16 | + <div class="mole"></div> |
| 17 | + </div> |
| 18 | + <div class="hole hole2"> |
| 19 | + <div class="mole"></div> |
| 20 | + </div> |
| 21 | + <div class="hole hole3"> |
| 22 | + <div class="mole"></div> |
| 23 | + </div> |
| 24 | + <div class="hole hole4"> |
| 25 | + <div class="mole"></div> |
| 26 | + </div> |
| 27 | + <div class="hole hole5"> |
| 28 | + <div class="mole"></div> |
| 29 | + </div> |
| 30 | + <div class="hole hole6"> |
| 31 | + <div class="mole"></div> |
| 32 | + </div> |
| 33 | + </div> |
| 34 | + |
| 35 | +<script> |
| 36 | + const holes = document.querySelectorAll('.hole'); |
| 37 | + const scoreBoard = document.querySelector('.score'); |
| 38 | + const moles = document.querySelectorAll('.mole'); |
| 39 | + let lastHole; |
| 40 | + let timeUp = false; |
| 41 | + let score = 0; |
| 42 | + |
| 43 | + function randomTime(min, max) { |
| 44 | + return Math.round(Math.random() * (max - min) + min); |
| 45 | + } |
| 46 | + |
| 47 | + function randomHole(holes) { |
| 48 | + const idx = Math.floor(Math.random() * holes.length); |
| 49 | + const hole = holes[idx]; |
| 50 | + if (hole === lastHole) { |
| 51 | + console.log('Ah nah thats the same one bud'); |
| 52 | + return randomHole(holes); |
| 53 | + } |
| 54 | + lastHole = hole; |
| 55 | + return hole; |
| 56 | + } |
| 57 | + |
| 58 | + function peep() { |
| 59 | + const time = randomTime(200, 1000); |
| 60 | + const hole = randomHole(holes); |
| 61 | + hole.classList.add('up'); |
| 62 | + setTimeout(() => { |
| 63 | + hole.classList.remove('up'); |
| 64 | + if (!timeUp) peep(); |
| 65 | + }, time); |
| 66 | + } |
| 67 | + |
| 68 | + function startGame() { |
| 69 | + scoreBoard.textContent = 0; |
| 70 | + timeUp = false; |
| 71 | + score = 0; |
| 72 | + peep(); |
| 73 | + setTimeout(() => timeUp = true, 10000) |
| 74 | + } |
| 75 | + |
| 76 | + function bonk(e) { |
| 77 | + if(!e.isTrusted) return; // cheater! |
| 78 | + score++; |
| 79 | + this.parentNode.classList.remove('up'); |
| 80 | + scoreBoard.textContent = score; |
| 81 | + } |
| 82 | + |
| 83 | + moles.forEach(mole => mole.addEventListener('click', bonk)); |
| 84 | + |
| 85 | +</script> |
| 86 | +</body> |
| 87 | +</html> |
0 commit comments