Categories
React Projects

Create a Whack a Mole Game with React and JavaScript

Spread the love

React is an easy to use JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a whack a mole game with React and JavaScript.

Create the Project

We can create the React project with Create React App.

To install it, we run:

npx create-react-app whack-a-mole

with NPM to create our React project.

Create the Whack a Mole Game

To create the whack a mole game, we write:

import React, { useState } from "react";

export default function App() {
  const [index, setIndex] = useState(0);
  const [score, setScore] = useState(0);
  const [timer, setTimer] = useState();

  const generateIndex = () => {
    setIndex(Math.floor(Math.random() * 6));
  };

  const startGame = () => {
    const timer = setInterval(generateIndex, 2000);
    setTimer(timer);
  };

  const endGame = () => {
    clearInterval(timer);
    setScore(0);
    setIndex(0);
  };

  const onClick = (n) => {
    if (index === n) {
      setScore((score) => score + 1);
    }
  };

  return (
    <div>
      <style>
        {`
        .hole {
          width: 50px;
          height: 50px;
          border: 1px solid black;
          border-radius: 50%;
        }

        .container {
          display: inline-block;
        }

        img {
          width: 50px;
          height: 50px;
        }
      `}
      </style>
      <button onClick={startGame}>start game</button>
      <button onClick={endGame}>end game</button>
      <p>score: {score}</p>
      <div>
        {Array(6)
          .fill()
          .map((_, n) => {
            if (index === n) {
              return (
                <div className="container">
                  <img
                    src="https://grid.gograph.com/happy-mole-cartoon-vector-art_gg68718247.jpg"
                    alt="mole"
                    onClick={() => onClick(n)}
                  />
                </div>
              );
            } else {
              return (
                <div className="container">
                  <div className="hole"></div>
                </div>
              );
            }
          })}
      </div>
    </div>
  );
}

We create index , score , and timer states.

index is the index of the div to show the mole in.

Below that, we have the generateIndex function to generate the index to show the model.

startGame calls setInterval to start the timer.

We call setTimer to set the returned timer .

The endGame function calls clearInterval to clear the timer.

It also calls setScore and setIndex to reset the score and index values to 0.

Also, we have the onClick function to check if index is the same as n .

n is the index of the div that we clicked on.

If they’re the same, then we increase the score by calling setScore with a callback to return the existing score plus 1.

Below that, we have some styles to make the divs round.

We make them round with the border-radius .

Below that, we have buttons that call startGame and endGame respectively with we click them.

Then we add the score display.

And finally, we have an array with 6 slots rendered into divs.

If index is the same as n , we display the mole image.

Otherwise, we show an empty hole.

The img element has an onClick handler that calls onClick to check if what was clicked is where the mole image is displayed.

Conclusion

We can create a whack a mole game easily with React and Javascript.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *