Skip to content

Zig Project: Terminal Snake Game

Time to have some fun. In this project you’ll build Snake: you steer a snake around a box, it grows every time it eats, and the game ends when it hits a wall or itself. It runs right in your terminal, in real time, using nothing but the standard library.

A game is a great project because it mixes everything: a struct holding the game’s state, enums and tagged unions, random numbers, a loop that runs many times a second, and reading the keyboard without waiting for Enter. You’ll also see a clean way to split a game into pure “logic” you can test, and the messy outside-world parts that you keep small.

Here’s a real frame from the finished game, a few seconds in:

Score: 5
##########################
# @ #
# o #
# o #
# ooooo #
# #
# #
# #
# #
# * #
# #
##########################
arrows or WASD to steer, q to quit

@ is the snake’s head, o its body and * the food. The snake moves about seven times a second, and you steer with the arrow keys or W, A, S and D.

What you’ll practise:

  • A struct with methods that holds the whole game state (Zig Struct Methods).
  • Enums with methods and a tagged union for input (Zig Enums, Zig Tagged Unions).
  • Random numbers with a seed, so a game can be replayed exactly (Project: Guessing Game).
  • Raw keyboard input with the terminal’s settings, and always restoring them with defer.
  • ANSI escape codes to move the cursor and redraw the screen.
  • A game loop: read input, update, draw, wait.

Make a folder with one file, snake.zig:

Terminal window
mkdir snake
cd snake

The game logic works anywhere. The keyboard part uses the POSIX terminal settings (termios), which exist on Linux and macOS. On Windows, run it inside WSL; the native Windows console uses a different API, and the program won’t compile for Windows as written (see “Ideas to extend it”). Everything here was checked with Zig 0.17.1 on Linux, and it also compiles for macOS.

Let’s start with the part that doesn’t need a terminal at all: the board, the snake, the food and the rules. It’s one struct, Game, with a few methods. To see it work, this program lets a very simple computer player chase the food for 60 ticks and draws the board before and after:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
var prng: std.Random.DefaultPrng = .init(2026);
var game: Game = .init(prng.random());
var buffer: [2048]u8 = undefined;
var stdout_writer = std.Io.File.stdout().writer(init.io, &buffer);
const out = &stdout_writer.interface;
try game.draw(out);
// Let a very simple "player" chase the food for 60 ticks.
var ticks: u32 = 0;
while (!game.over and ticks < 60) : (ticks += 1) {
game.turn(towardFood(&game));
game.step();
}
try out.print("after {d} ticks:\n", .{ticks});
try game.draw(out);
try out.flush();
}
/// Heads straight for the food: first sideways, then up or down.
fn towardFood(game: *const Game) Direction {
const head = game.body[0];
const food = game.food;
if (food.x > head.x and game.direction != .left) return .right;
if (food.x < head.x and game.direction != .right) return .left;
if (food.y > head.y) return .down;
if (food.y < head.y) return .up;
return game.direction;
}
const width = 24;
const height = 10;
const Point = struct { x: i16, y: i16 };
const Direction = enum {
up,
down,
left,
right,
fn opposite(d: Direction) Direction {
return switch (d) {
.up => .down,
.down => .up,
.left => .right,
.right => .left,
};
}
};
const Game = struct {
/// body[0] is the head. Only the first `len` points are used.
body: [width * height]Point = undefined,
len: usize = 3,
direction: Direction = .right,
food: Point = undefined,
score: u32 = 0,
over: bool = false,
random: std.Random,
fn init(random: std.Random) Game {
var game: Game = .{ .random = random };
// Start in the middle, three cells long, heading right.
for (0..game.len) |i| {
game.body[i] = .{ .x = width / 2 - @as(i16, @intCast(i)), .y = height / 2 };
}
game.placeFood();
return game;
}
/// Changes direction, but never straight back into the snake's own neck.
fn turn(game: *Game, direction: Direction) void {
if (direction != game.direction.opposite()) game.direction = direction;
}
/// Moves the snake one cell. Called once per tick.
fn step(game: *Game) void {
if (game.over) return;
const head = game.body[0];
const next: Point = switch (game.direction) {
.up => .{ .x = head.x, .y = head.y - 1 },
.down => .{ .x = head.x, .y = head.y + 1 },
.left => .{ .x = head.x - 1, .y = head.y },
.right => .{ .x = head.x + 1, .y = head.y },
};
const hit_wall = next.x < 0 or next.x >= width or next.y < 0 or next.y >= height;
// The tail moves out of the way this tick, so it doesn't count (unless we're growing).
const eating = std.meta.eql(next, game.food);
const body_to_check = if (eating) game.len else game.len - 1;
if (hit_wall or game.isSnake(next, body_to_check)) {
game.over = true;
return;
}
if (eating) {
game.len += 1;
game.score += 1;
}
// Shift every segment back by one and put the new head in front.
@memmove(game.body[1..game.len], game.body[0 .. game.len - 1]);
game.body[0] = next;
if (eating) {
if (game.len == game.body.len) {
game.over = true; // the board is full: you win!
return;
}
game.placeFood();
}
}
fn isSnake(game: *const Game, p: Point, count: usize) bool {
for (game.body[0..count]) |segment| {
if (std.meta.eql(segment, p)) return true;
}
return false;
}
/// Puts food on a random empty cell.
fn placeFood(game: *Game) void {
while (true) {
const p: Point = .{
.x = game.random.intRangeLessThan(i16, 0, width),
.y = game.random.intRangeLessThan(i16, 0, height),
};
if (!game.isSnake(p, game.len)) {
game.food = p;
return;
}
}
}
/// Draws the board as plain text, one line per row.
fn draw(game: *const Game, w: *std.Io.Writer) !void {
try w.print("Score: {d}\n", .{game.score});
try w.splatByteAll('#', width + 2);
try w.writeByte('\n');
for (0..height) |row| {
try w.writeByte('#');
for (0..width) |col| {
const p: Point = .{ .x = @intCast(col), .y = @intCast(row) };
const c: u8 = if (std.meta.eql(p, game.body[0]))
'@'
else if (game.isSnake(p, game.len))
'o'
else if (std.meta.eql(p, game.food))
'*'
else
' ';
try w.writeByte(c);
}
try w.writeAll("#\n");
}
try w.splatByteAll('#', width + 2);
try w.writeByte('\n');
}
};

Output:

Score: 0
##########################
# #
# #
# #
# #
# #
# oo@ #
# #
# * #
# #
# #
##########################
after 60 ticks:
Score: 4
##########################
# #
# #
# #
# @oooooo #
# #
# #
# * #
# #
# #
# #
##########################

Because the random generator starts from a fixed seed, 2026, the food appears in the same places every time, and you get exactly this output. That makes the logic easy to check and to debug. Let’s go through it.

The board and the snake. Point is a cell on a 24 by 10 board, with (0, 0) in the top-left corner and y growing downwards, like text lines. The snake is an array of points, body, with the head at index 0. The array has room for a snake that fills the whole board, and len says how many points are in use. No allocator needed: the whole game lives in one struct on the stack.

Default field values. Most fields have defaults (len: usize = 3, direction: Direction = .right), so init only has to pass the random generator and then fill in the starting body. @intCast(i) converts the loop counter, a usize, into the i16 the points use.

Turning. Direction is an enum with a method, opposite. turn ignores a request to go straight back the way you came, because that would drive the head into the neck and end the game instantly. Every snake game has this rule, and players notice when it’s missing.

Moving. step works out the next head position from the direction, then checks for a crash. Two details matter here:

  • The tail moves out of the way in the same tick, so the head may move into the cell the tail is leaving. That’s why the self-check looks at len - 1 segments, unless the snake is eating and therefore growing.
  • Moving is one line: @memmove(game.body[1..game.len], game.body[0 .. game.len - 1]) shifts every segment back one place, and then the new head goes in front. @memmove is the copy for overlapping memory, which is exactly what this is. When the snake eats, len grows by one before the shift, so the old tail stays and the snake gets longer.

Food. placeFood picks random cells until it finds one that isn’t part of the snake. With a small board and a short snake that takes a try or two. If the snake ever fills the whole board, there’s nowhere left, so step ends the game as a win before calling it.

Drawing. draw writes the board as plain text to any *std.Io.Writer: a border of #, then one character per cell. splatByteAll('#', width + 2) writes the same byte many times. In the real game this writer is the terminal; here it’s stdout, so we can see the result.

In the game, each tick the program grabs whatever bytes were typed since the last tick and works out what the player wants. Letters are single bytes, but the arrow keys send three bytes each: ESC (27), [ (91), then A, B, C or D. Here’s that decoding, tried on some made-up key presses:

const std = @import("std");
pub fn main() void {
const tests = [_][]const u8{ "w", "x", "\x1b[A", "\x1b[D", "da", "q", "\x03", "" };
for (tests) |bytes| {
switch (readKeys(bytes)) {
.none => std.debug.print("{any} -> nothing\n", .{bytes}),
.quit => std.debug.print("{any} -> quit\n", .{bytes}),
.turn => |direction| std.debug.print("{any} -> turn {t}\n", .{ bytes, direction }),
}
}
}
const Input = union(enum) {
none,
quit,
turn: Direction,
};
/// Works out what the player wants from the bytes they typed. The last key wins.
fn readKeys(bytes: []const u8) Input {
var input: Input = .none;
for (bytes, 0..) |byte, i| {
// Arrow keys send three bytes: ESC, '[', then A, B, C or D.
const arrow = i >= 2 and bytes[i - 2] == 0x1b and bytes[i - 1] == '[';
input = switch (byte) {
'q', 3 => return .quit, // 3 is Ctrl+C
'w' => .{ .turn = .up },
's' => .{ .turn = .down },
'a' => .{ .turn = .left },
'd' => .{ .turn = .right },
'A' => if (arrow) .{ .turn = .up } else input,
'B' => if (arrow) .{ .turn = .down } else input,
'C' => if (arrow) .{ .turn = .right } else input,
'D' => if (arrow) .{ .turn = .left } else input,
else => input,
};
}
return input;
}
const Direction = enum {
up,
down,
left,
right,
fn opposite(d: Direction) Direction {
return switch (d) {
.up => .down,
.down => .up,
.left => .right,
.right => .left,
};
}
};

Output:

{ 119 } -> turn up
{ 120 } -> nothing
{ 27, 91, 65 } -> turn up
{ 27, 91, 68 } -> turn left
{ 100, 97 } -> turn left
{ 113 } -> quit
{ 3 } -> quit
{ } -> nothing
  • Input is a tagged union with three cases: nothing happened, quit, or turn in a direction. The game loop will switch on it.
  • readKeys looks at every byte. For A to D, it checks whether the two bytes before were ESC [, so only an arrow key counts, not a capital A typed by accident.
  • If several keys arrived in one tick, the last one wins ("da" means “left”), which feels right when you press keys quickly.
  • q and Ctrl+C (byte 3) quit. Ctrl+C normally stops a program on the spot, but in Step 4 we’ll ask the terminal to deliver it as an ordinary key, so the game can clean up first.
  • {any} prints the bytes as numbers, which is handy for seeing what a key really sends.

Normally your terminal is in line mode: it collects what you type, shows it on screen, and only hands the whole line to the program when you press Enter. Great for the guessing game, useless for Snake. We need three changes, made through the POSIX termios settings:

const stdin = posix.STDIN_FILENO;
const original = posix.tcgetattr(stdin) catch {
std.debug.print("snake needs a real terminal to run in\n", .{});
return;
};
var raw = original;
raw.lflag.ICANON = false; // don't wait for Enter
raw.lflag.ECHO = false; // don't print the keys
raw.lflag.ISIG = false; // Ctrl+C arrives as a key, so we can clean up
raw.cc[@backingInt(posix.V.MIN)] = 0; // read() may return 0 bytes...
raw.cc[@backingInt(posix.V.TIME)] = 0; // ...right away, instead of waiting
try posix.tcsetattr(stdin, .FLUSH, raw);
defer posix.tcsetattr(stdin, .FLUSH, original) catch {};
  • tcgetattr reads the current settings. If stdin isn’t a terminal (say, you piped a file in), it fails with error.NotATerminal, and we print a friendly message instead.
  • We keep a copy of the original settings, change a copy, and apply it with tcsetattr.
  • ICANON off means no line mode: keys arrive one by one. ECHO off means typed keys don’t appear on the board. ISIG off turns Ctrl+C into byte 3 instead of killing the program.
  • V.MIN = 0 and V.TIME = 0 make read return immediately, with 0 bytes if nothing was pressed. The game never waits for the player; it just checks each tick.
  • defer restores the original settings whenever main returns, by any path. This is the most important line in the program. Without it, your terminal stays in raw mode after the game: no echo, no line editing, and it looks broken.

Drawing uses ANSI escape codes, special byte sequences starting with ESC (\x1b) that terminals treat as commands instead of text:

Code What it does
\x1b[2J Clear the whole screen.
\x1b[H Move the cursor to the top-left corner.
\x1b[?25l Hide the cursor.
\x1b[?25h Show it again.

The game clears the screen once at the start, then for every frame just moves the cursor home with \x1b[H and draws over the old frame. Clearing on every frame would make the picture flicker.

Every real-time game has the same heartbeat: read input, update, draw, wait, over and over:

while (!game.over) {
// 1. Read every key pressed since the last tick.
var keys: [32]u8 = undefined;
const n = posix.read(stdin, &keys) catch 0;
switch (readKeys(keys[0..n])) {
.none => {},
.quit => break,
.turn => |direction| game.turn(direction),
}
// 2. Move, 3. draw, 4. wait.
game.step();
try out.writeAll("\x1b[H"); // cursor to the top-left corner
try game.draw(out);
try out.writeAll("arrows or WASD to steer, q to quit\n");
try out.flush();
try io.sleep(.fromMilliseconds(tick_ms), .awake);
}
  • posix.read returns how many bytes were waiting, often 0. catch 0 treats a read error as “no keys”.
  • The whole frame goes into the buffered writer and is sent with one flush. The terminal gets the frame in one piece, which also helps against flicker.
  • io.sleep(.fromMilliseconds(tick_ms), .awake) pauses for one tick, 150 ms here. .awake is the clock that counts time while the computer is awake; for a game delay, that’s the one you want. Make tick_ms smaller and the snake gets faster.

Here’s all of snake.zig: the terminal setup and loop from Steps 4 and 5, readKeys from Step 3, and the Game logic from Step 2 (its main is replaced by the real one, and the seed now comes from io.random, so every game is different):

const std = @import("std");
const posix = std.posix;
/// Time between moves. Smaller is faster.
const tick_ms = 150;
pub fn main(init: std.process.Init) !void {
const io = init.io;
var seed: u64 = undefined;
io.random(std.mem.asBytes(&seed));
var prng: std.Random.DefaultPrng = .init(seed);
var game: Game = .init(prng.random());
// Raw mode: keys arrive one by one, without Enter and without being shown.
const stdin = posix.STDIN_FILENO;
const original = posix.tcgetattr(stdin) catch {
std.debug.print("snake needs a real terminal to run in\n", .{});
return;
};
var raw = original;
raw.lflag.ICANON = false; // don't wait for Enter
raw.lflag.ECHO = false; // don't print the keys
raw.lflag.ISIG = false; // Ctrl+C arrives as a key, so we can clean up
raw.cc[@backingInt(posix.V.MIN)] = 0; // read() may return 0 bytes...
raw.cc[@backingInt(posix.V.TIME)] = 0; // ...right away, instead of waiting
try posix.tcsetattr(stdin, .FLUSH, raw);
defer posix.tcsetattr(stdin, .FLUSH, original) catch {};
var buffer: [4096]u8 = undefined;
var stdout_writer = std.Io.File.stdout().writer(io, &buffer);
const out = &stdout_writer.interface;
try out.writeAll("\x1b[?25l\x1b[2J"); // hide the cursor, clear the screen
defer {
out.writeAll("\x1b[?25h") catch {}; // show the cursor again
out.flush() catch {};
}
while (!game.over) {
// 1. Read every key pressed since the last tick.
var keys: [32]u8 = undefined;
const n = posix.read(stdin, &keys) catch 0;
switch (readKeys(keys[0..n])) {
.none => {},
.quit => break,
.turn => |direction| game.turn(direction),
}
// 2. Move, 3. draw, 4. wait.
game.step();
try out.writeAll("\x1b[H"); // cursor to the top-left corner
try game.draw(out);
try out.writeAll("arrows or WASD to steer, q to quit\n");
try out.flush();
try io.sleep(.fromMilliseconds(tick_ms), .awake);
}
try out.print("\nGame over! You ate {d} pieces of food.\n", .{game.score});
}
const Input = union(enum) {
none,
quit,
turn: Direction,
};
/// Works out what the player wants from the bytes they typed. The last key wins.
fn readKeys(bytes: []const u8) Input {
var input: Input = .none;
for (bytes, 0..) |byte, i| {
// Arrow keys send three bytes: ESC, '[', then A, B, C or D.
const arrow = i >= 2 and bytes[i - 2] == 0x1b and bytes[i - 1] == '[';
input = switch (byte) {
'q', 3 => return .quit, // 3 is Ctrl+C
'w' => .{ .turn = .up },
's' => .{ .turn = .down },
'a' => .{ .turn = .left },
'd' => .{ .turn = .right },
'A' => if (arrow) .{ .turn = .up } else input,
'B' => if (arrow) .{ .turn = .down } else input,
'C' => if (arrow) .{ .turn = .right } else input,
'D' => if (arrow) .{ .turn = .left } else input,
else => input,
};
}
return input;
}
const width = 24;
const height = 10;
const Point = struct { x: i16, y: i16 };
const Direction = enum {
up,
down,
left,
right,
fn opposite(d: Direction) Direction {
return switch (d) {
.up => .down,
.down => .up,
.left => .right,
.right => .left,
};
}
};
const Game = struct {
/// body[0] is the head. Only the first `len` points are used.
body: [width * height]Point = undefined,
len: usize = 3,
direction: Direction = .right,
food: Point = undefined,
score: u32 = 0,
over: bool = false,
random: std.Random,
fn init(random: std.Random) Game {
var game: Game = .{ .random = random };
// Start in the middle, three cells long, heading right.
for (0..game.len) |i| {
game.body[i] = .{ .x = width / 2 - @as(i16, @intCast(i)), .y = height / 2 };
}
game.placeFood();
return game;
}
/// Changes direction, but never straight back into the snake's own neck.
fn turn(game: *Game, direction: Direction) void {
if (direction != game.direction.opposite()) game.direction = direction;
}
/// Moves the snake one cell. Called once per tick.
fn step(game: *Game) void {
if (game.over) return;
const head = game.body[0];
const next: Point = switch (game.direction) {
.up => .{ .x = head.x, .y = head.y - 1 },
.down => .{ .x = head.x, .y = head.y + 1 },
.left => .{ .x = head.x - 1, .y = head.y },
.right => .{ .x = head.x + 1, .y = head.y },
};
const hit_wall = next.x < 0 or next.x >= width or next.y < 0 or next.y >= height;
// The tail moves out of the way this tick, so it doesn't count (unless we're growing).
const eating = std.meta.eql(next, game.food);
const body_to_check = if (eating) game.len else game.len - 1;
if (hit_wall or game.isSnake(next, body_to_check)) {
game.over = true;
return;
}
if (eating) {
game.len += 1;
game.score += 1;
}
// Shift every segment back by one and put the new head in front.
@memmove(game.body[1..game.len], game.body[0 .. game.len - 1]);
game.body[0] = next;
if (eating) {
if (game.len == game.body.len) {
game.over = true; // the board is full: you win!
return;
}
game.placeFood();
}
}
fn isSnake(game: *const Game, p: Point, count: usize) bool {
for (game.body[0..count]) |segment| {
if (std.meta.eql(segment, p)) return true;
}
return false;
}
/// Puts food on a random empty cell.
fn placeFood(game: *Game) void {
while (true) {
const p: Point = .{
.x = game.random.intRangeLessThan(i16, 0, width),
.y = game.random.intRangeLessThan(i16, 0, height),
};
if (!game.isSnake(p, game.len)) {
game.food = p;
return;
}
}
}
/// Draws the board as plain text, one line per row.
fn draw(game: *const Game, w: *std.Io.Writer) !void {
try w.print("Score: {d}\n", .{game.score});
try w.splatByteAll('#', width + 2);
try w.writeByte('\n');
for (0..height) |row| {
try w.writeByte('#');
for (0..width) |col| {
const p: Point = .{ .x = @intCast(col), .y = @intCast(row) };
const c: u8 = if (std.meta.eql(p, game.body[0]))
'@'
else if (game.isSnake(p, game.len))
'o'
else if (std.meta.eql(p, game.food))
'*'
else
' ';
try w.writeByte(c);
}
try w.writeAll("#\n");
}
try w.splatByteAll('#', width + 2);
try w.writeByte('\n');
}
};

Build it and play:

Terminal window
zig build-exe snake.zig -O fast
./snake

You’ll see the board redrawn in place about seven times a second, like the frame at the top of the page. When the snake crashes, or you press q, the game ends with:

Game over! You ate 5 pieces of food.

and your terminal is back to normal. zig run snake.zig works too; building first just means the game starts right away next time.

A broken terminal after the program stops. If raw mode isn’t undone, typed text stays invisible and Enter may act strangely. That happens when the restore line is missing, or when the program is killed before defer can run. Type reset and press Enter (you won’t see it as you type) to get your terminal back. That’s also why the game turns ISIG off: Ctrl+C becomes a key the game handles, instead of a kill that skips the cleanup.

Forgetting flush. The buffered writer only sends text when it’s full or flushed. Without the flush in the loop, you’d see nothing, then a burst of old frames.

Moving the snake by redrawing only the head. It’s tempting to draw just the new head and erase the tail, and it’s faster. But one missed erase leaves junk on screen forever. Redrawing the whole small board each frame is simple and always correct.

Treating a capital A as an arrow key. If readKeys mapped every A, B, C and D, typing with Caps Lock on would steer the snake. Check for the ESC [ in front.

  • Speed up. Make the tick shorter as the score grows, for example tick_ms - 5 * score with a lower limit.
  • A high score. Save the best score to a file and show it on the board (Zig File I/O).
  • Colours. Wrap the head and food in ANSI colour codes, like \x1b[32m (green) and \x1b[0m (reset), or use std.Io.Terminal, which knows how to set colours on each platform.
  • Pause. Make p pause and resume: add a pause case to Input and let the compiler show you every switch to update.
  • A smarter computer player. The towardFood player from Step 2 runs into walls and itself. Make it check that its next cell is free first, then test it over thousands of seeded games without a terminal.
  • Windows support. The native Windows console needs SetConsoleMode instead of termios. Put the raw-mode code behind a check on builtin.target.os.tag and write the Windows version.
  • Real graphics. raylib-zig gives Zig programs windows, drawing and sound through the raylib C library. Your Game struct can stay as it is; only draw and the input change. Check its README for the Zig version it currently supports, since bindings often lag a little behind new Zig releases.
  • Split a game into pure logic (a Game struct with init, turn, step, draw) and a thin outside layer for the keyboard, screen and timing. The logic can run with a fixed seed and be checked exactly.
  • A game loop is read input, update, draw, wait. io.sleep(.fromMilliseconds(ms), .awake) sets the pace.
  • Raw mode with termios: turn off ICANON, ECHO and ISIG, set V.MIN/V.TIME to 0 for reads that don’t wait, and always restore the original settings with defer.
  • ANSI escape codes like \x1b[H (cursor home) and \x1b[?25l (hide cursor) let you redraw a screen in place. Send each frame with one flush.
  • Arrow keys arrive as three bytes, ESC [ A to D; a tagged union like Input makes the result easy to switch on.
  • @memmove shifts overlapping data, such as the snake’s body.

Next up: Zig Testing, writing test blocks and running them with zig test and zig build test.

Quick check

1. Why does the game turn off ICANON in the terminal settings?
2. What happens if the program changes the terminal settings but never restores them?
3. Why does the snake's self-collision check skip the last segment when it isn't eating?
4. Why redraw with \x1b[H each frame instead of clearing the screen with \x1b[2J?