Whack a Mole Game using ReactJS Last Updated : 30 May, 2024 Comments Improve Suggest changes Like Article Like Report In this article, we explore the creation of a digital Whac-A-Mole game using React. This beloved classic challenges players to "whack" moles as they pop up from their holes. Whack-a-mole projectPrerequisites:Basic Knowledge of HTML, CSS, and JavaScript:React.jsNode.js and npmApproachProject Setup: Set up a new React project using the Create React App.Component Creation: Develop the main game component and its sub-elements.State Management: Utilize React state to manage game state, score, and timer.Game Logic and Styling: Implement game logic for mole appearance and scoring, and apply CSS for styling game elements.Steps to Set Up Your React ProjectCreate React App: Use the Create React App tool to set up your project. npx create-react-app whac-a-molecd whac-a-moleProject StructureFolder StructureExample: To demonstrate creating a whack-a-mole game using the react.js CSS /* src/App.css */ body { background-color: rgb(255, 228, 196); display: flex; flex-direction: column; align-items: center; justify-content: center; } .game-info { display: flex; flex-direction: column; align-items: center; justify-content: center; margin: 20px; } #startButton, #endButton { margin-bottom: 20px; padding: 10px; font-size: 16px; cursor: pointer; } .game-container { background-color: rgb(1, 254, 64); display: grid; grid-template-columns: repeat(3, 160px); gap: 10px; border: 2px solid rgb(216, 216, 216); padding: 20px; border-radius: 10px; } .hole { height: 150px; background: rgb(19, 55, 139); border: 5px solid rgb(30, 30, 30); cursor: pointer; border-radius: 100px; } .mole { background-size: 150px; background-image: url("https://media.geeksforgeeks.org/wp-content/uploads/20231130123541/mole.png"); } @media only screen and (max-width: 600px) { .game-container { width: 80%; gap: 10px; padding: 5%; grid-template-columns: repeat(3, 38%); } .hole { height: 50px; width: 50px; border-radius: 100px; } .mole { background-size: 50px; background-image: url( "https://media.geeksforgeeks.org/wp-content/uploads/20231130123541/mole.png"); } } JavaScript // src/App.js import React, { useState, useEffect } from 'react'; import './App.css'; const App = () => { const [score, setScore] = useState(0); const [timer, setTimer] = useState(60); const [gameOver, setGameOver] = useState(true); const [molePosition, setMolePosition] = useState(null); useEffect(() => { let countdown; let moleInterval; if (!gameOver) { countdown = setInterval(() => { setTimer((prevTimer) => { if (prevTimer <= 1) { clearInterval(countdown); setGameOver(true); alert(`Game Over!\nYour final score: ${score}`); setScore(0); setTimer(60); return 60; } return prevTimer - 1; }); }, 1000); moleInterval = setInterval(() => { if (!gameOver) { const random = Math.floor(Math.random() * 9); setMolePosition(random); } }, 1000); } return () => { clearInterval(countdown); clearInterval(moleInterval); }; }, [gameOver, score]); const startGame = () => { if (!gameOver) return; setGameOver(false); setScore(0); setTimer(60); }; const endGame = () => { setGameOver(true); alert(`Game Ended!\nYour final score: ${score}`); setScore(0); setTimer(60); }; const handleMoleClick = () => { if (!gameOver) { setScore(score + 1); setMolePosition(null); // Immediately remove mole } }; return ( <div className="App"> <div className="game-info"> <div id="score">Score: {score}</div> <div id="timer">Time: {timer}s</div> </div> <button id="startButton" onClick={startGame} disabled={!gameOver}> Start Game </button> <button id="endButton" onClick={endGame} disabled={gameOver}> End Game </button> <div className="game-container"> {Array.from({ length: 9 }).map((_, index) => ( <div key={index} className={`hole ${molePosition === index ? 'mole' : ''}`} onClick={molePosition === index ? handleMoleClick : undefined} ></div> ))} </div> </div> ); }; export default App; JavaScript //index.js import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <React.StrictMode> <App /> </React.StrictMode> ); Final Step: Run Your Project npm startOutput: Comment More infoAdvertise with us Next Article Whack a Mole Game using ReactJS A ashishrew7vh Follow Improve Article Tags : Project Web Technologies ReactJS Similar Reads 15 Puzzle Game using ReactJS In this article, we will create the 15 Puzzle Game using ReactJS. 15 puzzle game is basically a tile-based game in which there are 16 tiles out of which 1 tile is left empty and the remaining tiles are filled with numbers from 1 to 15 in random order. The user has to arrange all the tiles in numeric 6 min read Word Guess Game using React In this article, we will create an Interactive Word Guess Game using ReactJS. Word Guess game is basically a guessing game, where a hint will be given based on the hint you have to guess the word.This project basically implements functional components and manages the state accordingly. This Game all 6 min read Conwayâs Game of Life using React In this article, we'll explore how to build an interactive version of Conway's Game of Life using React. Conway's Game of Life is a classic cellular automaton devised by mathematician John Conway. It's a fascinating simulation that demonstrates emergent complexity from simple rules. Output Preview: 4 min read ReactJS | Using Babel Now we know that what Babel is, we will focus on how to install it on your machine using node. Babel can be installed easily after following these simple steps. Requirements :  A code editor like atom, sublime text or Visual studio code.Node should be installed on the machine with npm too. We will 2 min read PacMan game using React Let's make a Pacman game using React for a fun and nostalgic web experience. We'll include classic features like the maze, pellets, and ghosts, and learn some cool React stuff along the way. The game will be easy to play with arrow keys, and we'll add extras like keeping score and power pellets. It' 7 min read Hangman game using React React provides an excellent platform for creating interactive and engaging web applications. In this tutorial, you will be guided to build a classic Hangman game using React. Hangman is a word-guessing game that is not only entertaining but also a great way to practice your React skills.Preview of f 5 min read Math Sprint Game using React In this article, we will create a Math Sprint Game Using ReactJS. Math Sprint is a fun and challenging game where players have to solve math problems within a time limit to earn points. This game presents random math questions with four options. Players click the correct answer, and if correct, itâs 5 min read Whack-a-Mole Game using HTML CSS and JavaScript Whack-A-Mole is a classic arcade-style game that combines speed and precision. The game is set in a grid of holes, and the objective is to "whack" or hit the moles that randomly pop up from these holes. In this article, we are going to create Whack-a-Mole using HTML, CSS and JavaScript.Preview Image 3 min read Tenzies Game using ReactJS In this article, we are going to implement Tenzied Games using React JS. Tenzies is a fast-paced and fun game where players have to race to roll a specific combination with a set of ten dice. As we are building this game with ReactJS, we are using the functional components to build the application, 7 min read Memory Game from scratch using React In this article, we will create a Memory game using ReactJS. A memory game is a famous game in which a pair of cards are placed in front of a player with their face down. The two pairs are always going to have the same content. The player has the choice to select any two cards at a time and check if 6 min read Like