Snake Game With Rust, JavaScript, and WebAssembly | Part 4
This is part of the course “Snake Game With Rust, JavaScript, and WebAssembly”.
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.
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"] }
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.
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.
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.