Adding the snake
Well, maybe not a snake yet, but a square that moves according to your wishes! In this section, you can try to apply what you have learned so far. If you don't know how to continue, you can either ask for help, or look at one way of solving the problems on the next page.
-
In the
lib
folder, make a new file calledsnake.rs
. -
Add the following line to the top of
snake.rs
#![allow(unused_variables)] fn main() { use crate::lib::types::{Cell, SnakeHead, Grid}; }
-
Add
pub mod snake;
right below the existingpub mod types;
. -
Write a function that initializes the snake as a
SnakeHead
.SnakeHead
is a struct that contains fields for a row, a column and aCell
value. The row and column values need to bei32
instead ofu32
. Why?
Defining a tuple
In fn main()
, after the grid is initialized, we define a tuple for direction. direction.0
is the row value, direction.1
is the column value.
#![allow(unused_variables)] fn main() { let mut direction = (1, 0); }
Movement
-
In
snake.rs
, write a function that takes a mutable reference of theSnakeHead
. It calculates a new position withdirection
values and the coordinates fromSnakeHead
and then returns a newSnakeHead
with an updated position. -
Write a function that takes ownership of the grid and changes the color of the square, where the current
SnakeHead
is located. The grid is then the return value.
Adding User Input
-
Add Events for
up
,down
,left
andright
key. -
How does the
direction.0
and thedirection.1
value change, when each of these buttons is pushed? Implement it!
Changing the Game Loop
-
Add this line to the top of
main.rs
:#![allow(unused_variables)] fn main() { use crate::lib::snake; }
-
Call the functions in the following order:
- update position of snake
- update grid with position of snake
- display frame
Run the game! Play the game!