In this part, we will allow the user to control the snake direction and stop the game. Changes that we will introduce in this part reflected in this commit.
To communicate to Rust what direction the player wants to move the snake, we will use the enum.
Also, we need two more Vector methods.
Now we can update methods with an optional argument for movement.
Let’s add a block between the last two lines.
First, we match movement to the corresponding vector. In our game the start of coordinates in the left top corner. Therefore vector pointed to the top has a negative Y-component.
When the new direction isn’t equal or isn’t opposed to the old one we round old and new components, to check if the snakehead crossed the center of the cell because only in this case we can update the direction.
Then we push an edge at the center of the crossed cell to shake tail. Finally, we calculate a new position for the head and update the direction.
The controller updates the value of the movement field and executes the callback on the stop button press.
Let’s create an instance of Controller in GameManager constructor.
When the game is resumed, we change lastUpdate so that it seems there was no stopping.
Finally, we want to pass the movement to the process method and update the tick method, so that it won’t call Rust and render when the game stopped.
Now we can go to the page, move the snake around the field, and stop the game by pressing the space button.
In the next part, we will make that every time the snake eats the food, its tail grows longer.
Reach the next level of focus and productivity with increaser.org.