Snake Game With Rust, JavaScript, and WebAssembly | Part 3

This is part of the course “Snake Game With Rust, JavaScript, and WebAssembly”.

Image for post
Image for post
GitHub Repository and Deployed Game

In this part, we will render all the objects of the game. Changes that we will introduce in this part reflected in this commit.

We are almost ready to render all objects of the game. The only field that we were unable to reach from JavaScript was the snake. Let’s fix this.

We will use js-sys dependency to return JavaScript Array of vectors. Let’s add it to the list of dependencies in Cargo.toml.

[dependencies]
wasm-bindgen = "0.2"
js-sys = "0.3.32"

Now we can add a public method that will return an Array. It will clone the snake, and convert each vector to JavaScript value.

Before writing rendering logic, we want to prepare the HTML. To make content take the full height of the page, we make the height of html and body equal to 100%. In the body, we have a place for current and best scores and container for canvas, that we attach in JavaScript.

www/index.html

All the rendering will happen in the View class.

www/src/view.js

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.

www/src/view.js

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.

Image for post
projecting vector from game to screen
www/src/view.js

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.

www/src/game-manager.js

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.

Image for post
Image for post
resizing 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.

Image for post
Image for post
Increaser

Written by

Software engineer, creator of increaser.org. More at geekrodion.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store