In this part, we will render all the objects of the game. Changes that we will introduce in this part reflected in this commit.
wasm-bindgen = "0.2"
js-sys = "0.3.32"
All the rendering will happen in the View class.
The constructor of the View class receives a callback so that the owner of an instance could make an extra rerender if needed. Later we will see how GameManager will handle this callback.
In the setUp() method, we take the width and height of the container to calculate the conversion rate between cells and pixels. Then we create two functions that will help us to project distances and positions from game to the view. Finally, we set up a canvas for rendering.
The last method receives the positions of the food and snake and scores to render all game objects. First, it clears everything from the previous render. Then it creates a field that looks like a chess-board. After that, it renders food and snake. Finally, it shows the current and best scores.
To bind it all together, let’s go to the GameManager class.
In the constructor, we create an instance of View class. To make an extra rerender on resizing, we pass the bound resize method.
Now, we can open a web page, see how everything is rendered and try to resize the window.
In the next part, we will implement logic to place food in a random place that is free from the snake.
Reach the next level of focus and productivity with increaser.org.