Day30 of #100DaysOfCode

Kushagra Kesav
2 min readMar 8, 2022

--

#CodeTogether Day 30/100

Hii folks 🙌

Today I completed the 30th the last video of JavaScript30!

Project 30: Whack A Mole Game

Source: https://javascript30.com

Learnings:

Today we are going to learn the last lesson of this JS30 series and we have been tasked to make a Whack A Mole Game! It was fun to build as we have been given the HTML and CSS already.

So, we started implementing the JavaScript inside the <script> tag.

First, we named a few variables as follows:

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

We then have to randomize the time each mole stuck its head out.

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

And randomize which hole the mole stuck its head out of.

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;
}

Get the mole SVG image to peep out of the hole by toggling a CSS class and linking it to the random hole and time.

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

A function to re-set the game.

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

Finally, we set up an event listener and function to score when the user clicked on the mole.

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

That’s all. I just completed all the 30 lessons in 30 days. Super happy and enthusiastic to hop on the next learning path. Stay tuned!

That is all for Day30 ✅

Thanks for reading, See you tomorrow!

--

--