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

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 complete the development of the game by adding logic that will restart the game when the player lost. Changes that we will introduce in this part reflected in this commit.

To detect when the snake eats its tail, we will use the Segment method that will return the projection of the point on the segment.

src/lib.rs

The magic involved to find the projection of the point on the segment is outside this course scope.🧙‍♂️

Image for post
Image for post
projecting points

Now we are ready to add the method that will tell us if the game should be over.

src/lib.rs

First, we check if the head of the snake is outside of the game field. If the snake has more than five segments, we want to check for self-intersection.

Image for post
Image for post
detecting self-intersection

We declare a self-intersection when the projected head is inside of one of the tail segments, and the distance between the projected point and head is less than half of the cell.

Let’s compile Rust and finish the JavaScript side!

We will check if the game is over right after the call to process method.

www/src/game-manager.js

Now we can open the web page and enjoy the game!

Image for post
Image for post
enjoying the game

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