Here’s a step-by-step tutorial to create a Whack-a-Mole game in Scratch with code snippets:
1. Setting Up the Stage:
- Open Scratch and create a new project.
- Choose a background that resembles a field. You can search for “grass” backgrounds in the library or draw your own.
2. Creating Sprites:
- Add a new sprite for your hammer. You can use the pre-loaded paintbrush sprite and modify it, or draw your own hammer.
- Add another sprite for the mole. You can use the cat sprite or search for “mole” sprites in the library.
3. Coding the Hammer Movement:
- Go to the scripting area for the hammer sprite.
- Drag a “When green flag clicked” block from the Events tab and snap it onto the scripting area.
- Inside the loop, drag a “forever” block from the Control tab. This will keep the hammer ready to whack.
- Add a “move to x: 0 y: 0” block from the Motion tab to position the hammer in the center (adjust coordinates if needed).
- Next, add a “go to mouse-pointer” block from the Motion tab. This will make the hammer follow your mouse cursor.
4. Coding the Mole:
- Go to the scripting area for the mole sprite.
- Drag a “When green flag clicked” block from the Events tab.
- Inside the loop, add a “hide” block to start with the mole hidden underground.
5. Making the Mole Pop Up:
- We want the mole to pop up from its hole at random times. Drag an “orange” control block and choose “repeat until” from the Control tab.
- Inside the loop, add a “wait random seconds from 1 to 5” block (adjust the time range for desired pop-up frequency).
- Then, add a “show” block to make the mole appear.
6. Whack Detection and Points:
- Go back to the hammer sprite’s script.
- Inside the “forever” loop, add an “if” block from the Control tab.
- Check the condition “touching mole?” under the Sensing tab.
- If the hammer touches the mole, we want several things to happen:
- Play a “squeak” sound effect (Sound tab).
- Hide the mole again with a “hide” block (Motion tab).
- Increase a score variable by 1 (create a variable from the Data tab and use “change (score variable) by 1”).
- Reset the mole pop-up loop with a “stop script” block (Control tab) inside another “repeat until” loop with a short wait (like 1 second) to prevent instant respawns.
7. (Optional) Adding Lives:
- You can add a lives variable and decrease it by 1 (with “change (lives variable) by -1”) whenever the hammer misses the mole (check for “not touching mole?”).
- Display the score and lives on the stage with text sprites.
- When lives reach 0, end the game with a “game over” message.