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 you'd create a new file called snake.ts. This file contains two classes:

  • The Point - Holding X and Y coordinates
  • The Snake - The actual snake implementation

The content is rather simple:

export class Point {    constructor(        public x: i32,        public y: i32    ) {}
    equals(other: Point): bool {        return this.x == other.x && this.y == other.y    }}
export class Snake {    body: Array<Point> = [        new Point(2, 0),        new Point(1, 0),        new Point(0, 0)    ]    direction: Point = new Point(1, 0)}

The snake class contains the body and the current direction of the snake instance. But it lacks any functionality for now.