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

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 implement logic to place food in a random place that is free from the snake. Changes that we will introduce in this part reflected in this commit.

We want to write a function that receives the width and height of the game alongside with snake and returns position for the food. The algorithm is pretty simple. We will go over each cell and put aside those that don’t intersect with the snake. Then we randomly pick one of the cells and return it.

Image for post
Image for post
free from the snake cells

Before writing function, let’s add a dependency to Cargo.toml that will help us to generate a random number.

[dependencies]
# ...
rand = { version = "0.7.2", features = ["wasm-bindgen"] }
src/lib.rs

There is a lot of work with segments. Let’s start with a function that turns a sequence of vectors into segments.

src/lib.rs

We will use segments only for calculations and won’t save them anywhere. Therefore Segment struct will keep only references to start and end.

src/lib.rs

Before implementing the Segment’s methods, let’s write a function that will check if two float numbers are relatively equal.

src/lib.rs

Also, we will need a method that will calculate the length of the vector.

src/lib.rs

Now, we are ready to implement methods.

src/lib.rs

To check if the point is inside of the segment, we split it with point and check if the sum of lengths is equal to the initial segment length.

Image for post
Image for post
checking if the point is inside of the segment

To check how it’s all works, we need to update the Game constructor.

let food = get_food(width, height, &snake);

Now, let’s compile Rust, and try to reload the web page a few times to see how food position changes.

Image for post
Image for post
reloading the page

In the next part, we will start the game loop and make the snake move. Stay tuned!

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