In this lesson I create Whack A Mole.
First I get the following elements: 'holes', 'scoreBoard', 'moles' and 'startCTA'. I also initialise 'lastHole', 'timeUp = false' and 'score = 0'.
I listen for the following events:
-
moles.forEach(mole => ())
-
'startCTA'
In startGame() - First initialise the game values: 'scoreBoard.textContent = 0', 'timeUp = false', 'score = 0'. Then run peep(). Also set the duration of the game (setTimeout(() => timeUp = true, 10000)).
In peep() - First set a random 'time' that each mole will pop up for. Then choose a random 'hole' inside of 'holes'. Add a class of '.up' to that hole which pops up the mole. Check if 'time' is up, if not, run peep() again. After 'time' is up (setTimeout(() {}, time) remove the class of '.up'.
randomTime(min, max) - A function that takes in a 'min' and 'max' parameter, and returns a random value between the 'min' and 'max' bounds.
In randomHole(holes) - Gets a random DOM element using a node list 'holes'.
In bonk(e) - First I check if the event is trusted, if not exit the function (!e.isTrusted). This makes sure the clicks are genuine and are not generated by an external source. If the click is genuine, increase the 'score', remove the class of '.up' from the element, and update the 'score' in the 'scoreboard'.
See the Pen
JavaScript30 - 30 - Whack A Mole by Corey Noble (@CoreyNoble)
on CodePen.