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

Rodion Chachura
Jan 13 · 3 min read

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

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.

Get Food Function

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.

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.

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.

reloading the page

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


Check out my app at increaser.org to get more done by working smarter.

Increaser

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade