Building a Whack-a-Mole Game with React: A Beginner’s Challenge

Mediumcode
3 min readJan 15, 2024

--

Unlock the secrets of handling click events in React as you whack moles to score points. Delve into the logic behind incrementing scores, hiding moles, and creating a dynamic gaming experience.

Introduction:

Hey, everyone! How’s it going? Today, I have an exciting beginner-level React challenge for you — building a Whack-a-Mole game! In this project, we’ll create a 3x3 grid where moles pop up for a short duration, and your goal as a user is to click on them before they hide. Let’s dive into the code and explore how we can implement this interactive game using React.

Setting Up the Grid:

The first step is to create the main app and set up a 3x3 grid to display our moles. Leveraging the power of CSS Grid, we easily achieve the layout. The challenge lies in dynamically handling the mole display based on the state.

// Importing mole and hole images
import hole from './assets/hole.png';
import mole from './assets/mole.png';

// Setting up initial state for moles
const [moles, setMoles] = useState(Array(9).fill(false));

// Generating the grid layout
return (
<div className="grid">
{moles.map((isMole, idx) => (
<img
key={idx}
src={isMole ? mole : hole}
alt={isMole ? 'mole' : 'hole'}
onClick={() => whackMole(idx)}
/>
))}
</div>
);

Randomly Picking Moles:

To make the game challenging, we want moles to appear randomly. By utilizing React’s useEffect and setInterval, we can update the state at regular intervals, causing moles to pop up in different locations.

// Initializing interval for mole appearance
useEffect(() => {
const intervalId = setInterval(() => {
const randomIndex = Math.floor(Math.random() * moles.length);
setMoles((currentMoles) => {
const newMoles = [...currentMoles];
newMoles[randomIndex] = true;
setTimeout(() => hideMole(randomIndex), 500); // Hide mole after 0.5 seconds
return newMoles;
});
}, 1000);

// Cleaning up interval on component unmount
return () => clearInterval(intervalId);
}, [moles]);

Whacking Moles and Scoring:

Implementing the logic for whacking moles and updating the score involves handling click events and managing the game state.

const whackMole = (index) => {
if (!moles[index]) return; // If no mole at the clicked position, do nothing
setScore((prevScore) => prevScore + 1); // Increment score
hideMole(index); // Hide mole after clicking
};

const hideMole = (index) => {
setMoles((currentMoles) => {
const newMoles = [...currentMoles];
newMoles[index] = false;
return newMoles;
});
};

Adding Timeouts for Mole Duration:

To enhance the gaming experience, we introduce timeouts to control the visibility duration of moles.

const showMole = (index) => {
setMoles((currentMoles) => {
const newMoles = [...currentMoles];
newMoles[index] = true;
setTimeout(() => hideMole(index), 500); // Hide mole after 0.5 seconds
return newMoles;
});
};

// Inside the setInterval function
const randomIndex = Math.floor(Math.random() * moles.length);
setMoles((currentMoles) => {
const newMoles = [...currentMoles];
newMoles[randomIndex] = true;
setTimeout(() => hideMole(randomIndex), 500); // Hide mole after 0.5 seconds
return newMoles;
});

Conclusion:

And there you have it — a fully functional Whack-a-Mole game built with React! This beginner-level challenge covers essential React concepts, such as state management, effects, and event handling. Feel free to explore, tweak, and enhance the game further. Happy coding!

--

--

Mediumcode
0 Followers

🚀 Aspiring coder exploring HTML, CSS, and JavaScript. 🌐 Passionate about learning, coding, and building a tech-savvy future! 💻🌱 #CodeNewbie