Skip to main content

Creating the Snake

Let's take a look at the main component of the game: The snake. There are several ways to implement one.

To keep things tidy, I recommend to create a new file called snake.rs. This file contains two structs:

  • The Point - Holds x and y coordinates.
  • The Snake - The actual snake implementation.

Snake has an associated function new that returns a brand new snake.

We have also defined few derivable traits to Point:

  • PartialEq and Eq add the == operator to perform an equality checks between Point instances.
  • Clone and Copy simplify use of Point instance.

You can learn more about these traits in the rust-book:

#[derive(Clone, Copy, PartialEq, Eq)]pub struct Point {    pub x: i32,    pub y: i32,}
pub struct Snake {    pub body: Vec<Point>,    pub direction: Point,}
impl Snake {    pub fn new() -> Self {        Self {            body: vec![                Point { x: 2, y: 0 },                Point { x: 1, y: 0 },                Point { x: 0, y: 0 },            ],            direction: Point { x: 1, y: 0 },        }    }}
note

Don't forget to declare this module in lib.rs.

mod snake;