DEV Community

Arhan Khan
Arhan Khan

Posted on

Build a Whack-a-Mole Game with JavaScript

Whack-a-Mole is a 30-second reaction game: moles pop out of holes at random, and you click them before they disappear. It is a great beginner project because it teaches setInterval, random selection, event delegation, and a simple game loop — with a result you can actually play.

The board is a 3x3 grid of holes. Each hole is a div, and a mole is a second div inside it that slides up when active. CSS handles the look — the mole is hidden below the hole's edge with overflow hidden, and an "up" class moves it into view with a transition.

The game loop is two timers. One timer picks a random hole every 700ms and shows a mole there; a second timer counts the game down from 30 seconds. When time runs out, both timers stop and the final score is shown:

const holes = document.querySelectorAll(".hole");
const moles = document.querySelectorAll(".mole");
let score = 0;
let timeLeft = 30;
let gameTimer;

function randomHole() {
  const index = Math.floor(Math.random() * holes.length);
  return holes[index];
}

function showMole() {
  const hole = randomHole();
  const mole = hole.querySelector(".mole");
  mole.classList.add("up");
  setTimeout(() => mole.classList.remove("up"), 800);
}

function startGame() {
  score = 0;
  timeLeft = 30;
  document.getElementById("score").textContent = score;
  gameTimer = setInterval(() => {
    showMole();
    timeLeft--;
    document.getElementById("time").textContent = timeLeft;
    if (timeLeft <= 0) endGame();
  }, 700);
}

function endGame() {
  clearInterval(gameTimer);
  alert(`Time's up! Your score: ${score}`);
}
Enter fullscreen mode Exit fullscreen mode

Scoring uses event delegation on the board. A click on a mole adds a point and hides it immediately, so fast players cannot farm the same mole twice:

document.getElementById("board").addEventListener("click", (e) => {
  if (!e.target.classList.contains("mole")) return;
  if (!e.target.classList.contains("up")) return;
  score++;
  document.getElementById("score").textContent = score;
  e.target.classList.remove("up");
});
Enter fullscreen mode Exit fullscreen mode

The check for the "up" class matters: without it, a player could click a mole that is already sliding down and still score. Small guards like this are what separate a game that feels fair from one that feels broken.

Ways to extend it: make moles appear faster as the score rises, add a golden mole worth five points that appears rarely, add a bomb mole that subtracts points, or store the best score in localStorage. The random-spawn-and-expire pattern is the same one behind reaction trainers and notification systems, so it is worth learning properly.

Top comments (0)