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

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.

# ...
rand = { version = "0.7.2", features = ["wasm-bindgen"] }

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


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


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


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


Now, we are ready to implement methods.


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!

Reach the next level of focus and productivity with




Indie hacker behind More at

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