AI Valley Logo
THE AI VALLEYK12 Coding & Robotics
Back to Blog
Build a Whack-a-Mole Game: JavaScript Tutorial for Kids | AI Valley Zirakpur
Bhavesh Bansal
April 5, 2026
10 min read

Build a Whack-a-Mole Game: JavaScript Tutorial for Kids

Welcome to another exciting hands-on project from AI Valley, Zirakpur! Whether you're joining us from Chandigarh, Mohali, or Panchkula, this is exactly the kind of fun project our students build in our weekend coding classes. As the leading institute for coding in Zirakpur and the Tricity area, we believe the best way to learn programming is by building something incredibly fun. Today, you are going to become a real web developer by creating your very own interactive browser game from scratch.

🎯 What You'll Build

We are going to build a classic Whack-a-Mole game! A cute virtual hamster will pop up randomly across a 3x3 grid. Your goal is to "whack" (click) the hamster as fast as you can before the 30-second timer runs out. By the end of this tutorial, you will have a fully functioning game that you can play and share with your friends.

📋 Prerequisites & Materials

  • A Text Editor: We highly recommend Visual Studio Code (VS Code). It is free, colorful, and used by professional developers.
  • A Web Browser: Google Chrome, Firefox, or Safari to run and test your game.
  • Basic Typing Skills: No prior coding experience is required, though a basic understanding of using a keyboard will help.
  • Three Blank Files: Create a folder on your computer named Whack-a-Mole. Inside it, create three empty files: index.html, style.css, and app.js.
  • Step 1: Setting Up the Game Board (HTML)

    HTML (HyperText Markup Language) is the skeleton of our game. It tells the browser what elements exist on our page, like text, images, and boxes.
    A screenshot of a code editor showing the basic HTML5 boilerplate structure with a heading, score, timer, and a grid container

    A screenshot of a code editor showing the basic HTML5 boilerplate structure with a heading, score, timer, and a grid container

    html
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Whack-a-Mole Game by AI Valley</title>
      <link rel="stylesheet" href="style.css">
    </head>
    <body>
    
      <h1>Whack-a-Mole! 🐹</h1>
      
      <h2>Score: <span id="score">0</span></h2>
      <h2>Time Left: <span id="time-left">30</span></h2>
    
      <div class="grid">
        <div class="square" id="1"></div>
        <div class="square" id="2"></div>
        <div class="square" id="3"></div>
        <div class="square" id="4"></div>
        <div class="square" id="5"></div>
        <div class="square" id="6"></div>
        <div class="square" id="7"></div>
        <div class="square" id="8"></div>
        <div class="square" id="9"></div>
      </div>
    
      <script src="app.js"></script>
    </body>
    </html>
    

    What this code does: We created a main container called grid and placed 9 square boxes inside it. These squares will be the holes where our mole hides. We also added tags with specific IDs so we can update the score and timer later. Notice how we linked our CSS file in the and our JS file at the end of the .

    Expected Output: If you open index.html in your browser now, you will just see the text "Whack-a-Mole!", "Score: 0", and "Time Left: 30". The grid is invisible because we haven't styled it yet!

    Step 2: Styling the Grid to Look Like a Game (CSS)

    CSS (Cascading Style Sheets) is the paint and decorations. We will use CSS to align our 9 squares into a neat 3x3 grid and make everything look like a proper arcade game.
    A web browser displaying a neat 3x3 grid of empty white squares with thick black borders centered on a light-colored background

    A web browser displaying a neat 3x3 grid of empty white squares with thick black borders centered on a light-colored background

    css
    body {
      font-family: Arial, sans-serif;
      text-align: center;
      background-color: #f4f4f9;
    }
    
    h1 {
      color: #ff4500;
    }
    
    .grid {
      display: grid;
      grid-template-columns: repeat(3, 150px);
      grid-template-rows: repeat(3, 150px);
      gap: 10px;
      justify-content: center;
      margin-top: 20px;
    }
    
    .square {
      width: 150px;
      height: 150px;
      background-color: #8b4513; /* SaddleBrown color to look like dirt */
      border: 4px solid #3e2723;
      border-radius: 10px;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 80px;
      cursor: pointer;
    }
    
    .square:hover {
      background-color: #a0522d;
    }
    

    What this code does: We use display: grid; to instantly arrange our squares into 3 columns and 3 rows, each exactly 150 pixels wide and tall. We gave the squares a nice dirt-brown background color (#8b4513) and made the text size huge (font-size: 80px) so our emoji mole will be nice and big.

    Expected Output: Refresh your browser! You should now see a beautiful 3x3 brown grid beneath your title and score.

    Step 3: Waking Up the JavaScript (Selecting Elements)

    Now comes the magic! JavaScript is the brain of our website. First, we need to grab the HTML elements we created so our code can control them.
    A close-up of a code editor showing JavaScript <code style=querySelector and querySelectorAll commands storing HTML elements into variables" style="max-width: 100%; border-radius: 0.75rem; box-shadow: 0 8px 30px rgba(0,0,0,0.4); border: 1px solid rgba(255,255,255,0.1);" />

    A close-up of a code editor showing JavaScript querySelector and querySelectorAll commands storing HTML elements into variables

    javascript
    // Select all our HTML elements
    const squares = document.querySelectorAll('.square');
    const timeLeftElement = document.querySelector('#time-left');
    const scoreElement = document.querySelector('#score');
    
    // Create variables to track game data
    let result = 0;
    let hitPosition;
    let currentTime = 30;
    let timerId = null;
    

    What this code does: document.querySelectorAll('.square') grabs all 9 of our grid boxes and stores them in an array called squares. We also set up variables to keep track of the player's result (score), where the mole currently is (hitPosition), and how much time is left (currentTime).

    Expected Output: Nothing will change on your screen yet, but your game is secretly preparing its memory in the background!

    Step 4: Making the Mole Move Randomly

    We need a function to pick one random square and place our hamster emoji (🐹) inside it. Then we need to make it move continuously.
    The browser game showing the 3x3 grid with a cute hamster emoji appearing inside the top-right square

    The browser game showing the 3x3 grid with a cute hamster emoji appearing inside the top-right square

    javascript
    function randomSquare() {
      // First, clean all squares (remove the mole from the old spot)
      squares.forEach(square => {
        square.innerHTML = '';
      });
    
      // Pick a random number between 0 and 8
      let randomPosition = Math.floor(Math.random() * 9);
      let randomSquare = squares[randomPosition];
    
      // Put the mole in the random square
      randomSquare.innerHTML = '🐹';
      
      // Remember where the mole is so we can check if the player clicks it
      hitPosition = randomSquare.id;
    }
    
    // Move the mole every 800 milliseconds (less than a second)
    function moveMole() {
      timerId = setInterval(randomSquare, 800);
    }
    
    moveMole();
    

    What this code does: Math.random() * 9 generates a random number. Math.floor() rounds it down to a whole number from 0 to 8. We use this to select one of our 9 squares. setInterval is a powerful JavaScript tool that tells the browser to run our randomSquare function repeatedly every 800 milliseconds.

    Expected Output: Refresh the page! You will see a hamster emoji randomly jumping from square to square every second.

    Step 5: Whacking the Mole to Score Points

    Our mole is moving, but clicking it does nothing. Let's add "Event Listeners" to detect when a player successfully clicks on the mole.
    The browser game showing the score updated to 1, and an explosion emoji (💥) appearing exactly where the user clicked the hamster

    The browser game showing the score updated to 1, and an explosion emoji (💥) appearing exactly where the user clicked the hamster

    javascript
    squares.forEach(square => {
      square.addEventListener('mousedown', () => {
        // Check if the clicked square's ID matches where the mole currently is
        if (square.id == hitPosition) {
          result++; // Add 1 to the score
          scoreElement.textContent = result; // Update the HTML text
          hitPosition = null; // Clear the hit position
          square.innerHTML = '💥'; // Show an explosion emoji!
        }
      });
    });
    

    What this code does: We attach an addEventListener to every single square. When the mouse button goes down (mousedown), it checks if that square is the current hitPosition. If it is, boom! The score goes up, the text on the screen updates, and we briefly show a collision emoji.

    Expected Output: Try playing the game now! Click the hamster. Your score should increase, and the hamster will briefly turn into an explosion until the next random movement.

    Step 6: Creating the Countdown Timer & Game Over

    A game needs an ending! Let's make the 30-second timer count down to zero and stop the game.
    A browser alert box popping up over the game screen that says 'GAME OVER! Your final score is 15' with the timer at 0

    A browser alert box popping up over the game screen that says 'GAME OVER! Your final score is 15' with the timer at 0

    javascript
    function countDown() {
      // Decrease time by 1
      currentTime--;
      timeLeftElement.textContent = currentTime;
    
      // Check if time has run out
      if (currentTime === 0) {
        clearInterval(countDownTimerId); // Stop the timer
        clearInterval(timerId); // Stop the mole from moving
        alert('GAME OVER! Your final score is ' + result);
      }
    }
    
    // Run the countdown function every 1000 milliseconds (1 full second)
    let countDownTimerId = setInterval(countDown, 1000);
    

    What this code does: The countDown function subtracts 1 from currentTime and updates the screen. We use setInterval to run it every 1 second. Once currentTime hits exactly 0, we use clearInterval to stop the clocks and trigger an alert() popup to announce the final score.

    Expected Output: The "Time Left" number will drop by 1 every second. At 0, the mole stops moving, and a popup window announces your final score!

    🎉 Final Result

    Congratulations! You have just built a complete, interactive, logic-based web game from absolute scratch. You learned how HTML builds structure, CSS adds beautiful styling, and JavaScript handles logic, timers, and user clicks.

    🚀 Challenge: Take It Further

    Want to make your game even better? Try these three challenges:
  • Increase the Difficulty: Go into app.js and change the mole movement interval from 800 to 500 milliseconds to make the mole super fast!
  • Add a Reset Button: Create a button in your HTML that resets currentTime to 30 and result to 0 when clicked.
  • Custom Graphics: Instead of emojis, use CSS background-image to put your own custom images (like a real mole or an alien) into the squares.
  • 🏫 Learn More at AI Valley, Zirakpur

    Did you enjoy this project? This is exactly how we teach at AI Valley — the top-rated coding institute in Zirakpur serving students across the entire Tricity area. We offer the best web development classes in Chandigarh, Mohali, Panchkula, and Zirakpur, focusing on 100% practical, hands-on coding. Whether you're looking for coding for kids programs, JavaScript training, or advanced programming courses, our expert instructor Bhavesh Bansal is ready to help you build amazing things. Visit AI Valley at SCO 11, ASM Plaza, VIP Road, Zirakpur or enroll online at aivalley.co.in!

    Tags

    coding for kids ZirakpurJavaScript tutorial for kidsweb development classes Tricitycoding classes ChandigarhHTML CSS JS game tutorialkids programming Mohaligame development for beginnersbest coding institute Panchkulalearn JavaScript step-by-stepSTEM education TricityAI Valley Zirakpur