We will work only in with one file today — scene.js since we already finished developing all other parts of the game. First, let’s update imports and declare a few variables at the top.
8: // We have an object that maps movements to key codes on the keyboard.
13: // If the player will press the space key, we will pause or resume the game.
15: // We will update the state of the game and rerender 60 times per second.
There are not that many actions, we only need to handle situations when the size of container changes(to render the game properly); when player presses or releases keys on the keyboard; every few milliseconds will be called tick action, and reducer will return a new state of the game.
To make a reducer cleaner, we replace the switch-case with a more functional approach by creating an object with a handler for each action. The handler is a function that receives old state and payload.
3: // When containers size changes, we update the state with new projectors.
8: // When the player presses the key, we check if it is left or right move.
16: // On key up, we check if a player wants to pause/resume the game and make appropriate operations with time.
27: // If the game is on pause, we return the old state. Otherwise, we calculate how much time left from the last update and call a function from the previous part.
In reducer, we take a handler for a received action type. If we implemented the handler for this action, we return a result of the call to the handler.
Next, let’s work on the component. To simplify the dispatch call, we can write a small helper function.
We want to update projectors every time the size of the container changes. To do this, we utilize useEffect hook.
After adding this hook, we can see that the game looks good regardless of the size of the screen.
On component mount, we want to subscribe to keys presses and spin up the game timer. To remove all these handlers on unmount, we return a function that will do unregistering.
Reach the next level of focus and productivity with increaser.org.