The base scaffold for the game uses CustomEvents to communicate between the game instance and the main component.
So, it’s a good idea to follow this pattern in the new workflow.
You’ve already added the emitEvent(resetLives)
call in the onPurchase()
function.
Now, you need to add a listener for it.
If you go to frontend/src/Components/Game/index.js
, you’ll find that there are already listeners defined in the first useEffect
hook.
Define your new listener here, as follows.
window.addEventListener('resetLives', resetLives);
Also, make sure to remove the listener in the return
function.
That way, it gets deleted when the game component unmounts.
This step is important for preventing memory leaks.
window.removeEventListener('resetLives', resetLives);
You also need to define the callback function that is passed to the listener.
...
import { spawnFloatingText } from './Effects/FloatingText';
...
const resetLives = () => {
game.lives = game.startingLives;
game.gameOver = false;
spawnFloatingText("EXTRA LIVES", game.width / 2, game.height / 2, {
duration: 1,
maxSize: 45
});
}
This code resets the lives to the starting value and resets the game.gameOver
property to false
.
It also spawns some floating text in the middle of the screen to celebrate this happy event.
If you’ve gone through the customizable game tutorial or are already familiar with the base game scaffold, you could get even more creative and spawn some exploding particles.
The player just spent some cash on the game — they should be rewarded!