We only have two components in a whole game that have state — Scene and Page. All other components are dummy SVG elements.
Let’s start by updating the index.css file with variables and few styles to finish with CSS in this series!
Ball and Paddle components are pretty straightforward. Let’s put them into ball.js and paddle.js files inside the components folder.
Block has different opacity depending on its density.
The Level component display text that placed at top left corner.
We are not bothering ourselves with making lives in the form of classic red hurts. In our game lives displayed as rounded rectangles at the right top corner. Why not?
We implemented all boring components and ready to put them all together. Let’s open scene.js file and import all we need.
Every time the player gets to a new level, we will save the number to local storage, so that next time the user opens the game, he can continue from the last level. Therefore at the start, we will check if there is a level number saved in local storage. To hack the game and get to the last level player can open console and type localStorage.level = 3.
We need to somehow project the game state to the screen. In the example below — the point with coordinates (3, 6) in the game state projected on the screen to point at (180, 360).
To do this, we will write a function that receives container size and size of the game field and returns an object with two projectors — for distances and for vectors.
We will use a Redux hook to manage the state of the scene because it will allow us to reduce the amount of unnecessary rerenders. In this part, we only implement a function that will create an initial state for it. And in upcoming parts, we’ll implement actions and handlers.
We are familiar with all properties in the returned state object, except time, stopTime, and movement:
- time will be used to calculate duration between updates and then determine how far ball and paddle moved during this period.
- when stopTime is not undefined, it means that the user stopped the game, and we don’t need to update the game state.
- If movement is defined, it means that the user holding the left or right key, and wants to change the position of the paddle.
Let’s finish this part by updating the component. Here we are receiving state via hook. Then we take all the properties that we need from the state and by using projectors render all SVG elements.
If we run the app and open a browser, we can see that all elements are in place, and we are getting closer to implementing a real game.
In this part, we’ve made all components and made Scene reflect the current state. The commit with these changes you can find here. If you like more video format, check out this course on YouTube. In the next part, we will start writing the core logic for the game. Stay tuned!
Reach the next level of focus and productivity with increaser.org.