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.zig. This file contains two structs:

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

The content is rather simple:

const std = @import("std");
pub const Point = struct {    x: i32,    y: i32,
    pub fn init(x: i32, y: i32) Point {        return .{            .x = x,            .y = y,        };    }
    pub fn equals(this: Point, other: Point) bool {        return this.x == other.x and this.y == other.y;    }};
pub const Snake = struct {    body: std.BoundedArray(Point, 400),    direction: Point,
    pub fn init() Snake {        return .{            .body = std.BoundedArray(Point, 400).fromSlice(&.{                Point.init(2, 0),                Point.init(1, 0),                Point.init(0, 0),            }) catch @panic("couldn't init snake body"),            .direction = Point.init(1, 0),        };    }};

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