Skip to content

Zig Project: Guessing Game

Time for your first real project. The computer picks a secret number from 1 to 100. You guess, and it tells you “too small” or “too big” until you get it right. Then it tells you how many tries you needed.

It’s a small program, but it pulls together a lot of what you’ve learned: variables, loops, switch, optionals, error handling and reading input. We’ll build it one step at a time, and every step is a program you can run on its own.

Here’s a real game, played in a terminal against the finished program:

Guess the number! (1 to 100)
Your guess: hello
Please type a whole number from 1 to 100.
Your guess: 50
Too big!
Your guess: 25
Too small!
Your guess: 37
Too small!
Your guess: 43
Too big!
Your guess: 40
Too big!
Your guess: 38
Too small!
Your guess: 39
You got it in 7 attempts!

Two friendly details to notice: typing hello doesn’t crash the game, it just asks again, and that bad line doesn’t count as an attempt.

What you’ll practise:

  • Random numbers with std.Random and a seed from init.io.
  • Reading a line from the keyboard with a buffered reader (Zig Reading Input).
  • Writing to stdout and remembering to flush (Zig Output).
  • Parsing text into a number with std.fmt.parseInt, and handling bad input kindly (Zig Try & Catch).
  • Comparing with std.math.order and a switch (Zig Switch).
  • Splitting the game into a function that takes a reader and a writer, so you can run it with fake input.

You don’t need a build script for a one-file program. Make a folder and a file:

Terminal window
mkdir guess
cd guess

Create guess.zig in that folder. Every program on this page goes in that file, replacing the last one, and you run it with:

Terminal window
zig run guess.zig

If you’d rather have a full project with zig build run, zig init works too: put the code in src/main.zig instead (Zig Build System explains the files it makes). Everything here was checked with Zig 0.17.1.

Computers don’t really “pick” numbers. A pseudo-random number generator (PRNG) is a small machine that turns one starting number, the seed, into a long sequence of numbers that look random. Same seed, same sequence.

Zig’s standard library has several of them in std.Random. std.Random.DefaultPrng is a good, fast general choice. Let’s see what it gives us with a fixed seed:

const std = @import("std");
pub fn main() void {
var prng: std.Random.DefaultPrng = .init(12345);
const random = prng.random();
for (0..5) |_| {
const n = random.intRangeAtMost(u8, 1, 100);
std.debug.print("{d} ", .{n});
}
std.debug.print("\n", .{});
}

Output:

41 63 82 85 53

Line by line:

  • var prng: std.Random.DefaultPrng = .init(12345); creates the generator with the seed 12345. It has to be var, because every number you take from it changes its inner state.
  • prng.random() gives you a std.Random, the general “source of random numbers” with all the handy methods on it.
  • random.intRangeAtMost(u8, 1, 100) returns a u8 from 1 to 100, including both ends. Its sister, intRangeLessThan(u8, 1, 101), leaves out the top number. Pick whichever reads more clearly to you.

Run it twice and you get 41 63 82 85 53 both times. That’s great for testing, and useless for a game: the player would learn that the answer is always 41.

For a real game, the seed itself must be unpredictable. Your operating system can give you random bytes, and in Zig 0.17 you ask for them through init.io, the same I/O interface you use for files and the terminal (Zig Main & Init):

const std = @import("std");
pub fn main(init: std.process.Init) void {
var seed: u64 = undefined;
init.io.random(std.mem.asBytes(&seed));
var prng: std.Random.DefaultPrng = .init(seed);
const secret = prng.random().intRangeAtMost(u8, 1, 100);
std.debug.print("The secret is {d}\n", .{secret});
}

Three runs here gave:

The secret is 98
The secret is 1
The secret is 33

io.random fills a buffer of bytes, so std.mem.asBytes(&seed) lets it write straight into the 8 bytes of our u64. The undefined is fine, because the very next line overwrites every byte.

Reading a line is the same pattern as in Zig Reading Input: a buffered reader for stdin, a buffered writer for stdout, and takeDelimiter('\n') for one line:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const io = init.io;
var in_buffer: [256]u8 = undefined;
var stdin_reader = std.Io.File.stdin().reader(io, &in_buffer);
const in = &stdin_reader.interface;
var out_buffer: [256]u8 = undefined;
var stdout_writer = std.Io.File.stdout().writer(io, &out_buffer);
const out = &stdout_writer.interface;
try out.writeAll("Your guess: ");
try out.flush();
const line = try in.takeDelimiter('\n') orelse "";
try out.print("You typed \"{s}\" ({d} bytes)\n", .{ line, line.len });
try out.flush();
}

This one waits for you, so run it in your own terminal. Typing a space and then 42:

Terminal window
zig run guess.zig

You’ll see:

Your guess: 42
You typed " 42" (3 bytes)

What’s going on:

  • The stdin reader fills in_buffer from the keyboard. The longest line it can return is the buffer size, 256 bytes here, which is plenty for a number.
  • takeDelimiter('\n') gives you the line without the newline. It returns null when the input has ended (the player pressed Ctrl+D, or you piped in an empty file), and orelse "" turns that into an empty string for now.
  • The flush after the prompt matters. The writer keeps text in its buffer until it’s full or you flush. Without that flush, the player stares at a blank screen while the program waits for them to type.
  • The line came back as " 42", space included. parseInt won’t accept that space, which brings us to the next step.

std.fmt.parseInt(T, text, base) turns text into an integer of type T. It returns an error union: either the number, or an error saying what went wrong. Here’s what it does with things a player might type:

const std = @import("std");
pub fn main() void {
const inputs = [_][]const u8{ "42", " 7", "seven", "300", "-3", "" };
for (inputs) |input| {
if (std.fmt.parseInt(u8, input, 10)) |n| {
std.debug.print("{s:>7} -> {d}\n", .{ input, n });
} else |err| {
std.debug.print("{s:>7} -> error.{t}\n", .{ input, err });
}
}
}

Output:

42 -> 42
7 -> error.InvalidCharacter
seven -> error.InvalidCharacter
300 -> error.Overflow
-3 -> error.Overflow
-> error.InvalidCharacter

A few surprises worth knowing:

  • " 7" fails. A space isn’t a digit, so trim the line first.
  • "300" doesn’t fit in a u8 (0 to 255), so you get error.Overflow. Zig never wraps it to some other number behind your back.
  • "-3" is also Overflow for an unsigned type, not InvalidCharacter: the minus sign is fine, the value just can’t be stored.

For the game, every one of these errors means the same thing: “that’s not a guess, ask again”. So we fold them into one small function that returns an optional, ?u8: a number, or null:

const std = @import("std");
/// Turns a typed line into a guess from 1 to 100, or null if it isn't one.
fn parseGuess(line: []const u8) ?u8 {
const text = std.mem.trim(u8, line, " \t\r");
const n = std.fmt.parseInt(u8, text, 10) catch return null;
if (n < 1 or n > 100) return null;
return n;
}
pub fn main() void {
const inputs = [_][]const u8{ "42", " 7 ", "50\r", "seven", "300", "0" };
for (inputs) |input| {
if (parseGuess(input)) |n| {
std.debug.print("{d}\n", .{n});
} else {
std.debug.print("not a guess\n", .{});
}
}
}

Output:

42
7
50
not a guess
not a guess
not a guess
  • std.mem.trim(u8, line, " \t\r") cuts spaces, tabs and \r off both ends. The \r is there for Windows, where pressing Enter sends \r\n, and takeDelimiter('\n') leaves the \r behind.
  • catch return null means “if parsing fails, for any reason, this function returns null”. It’s the short form of handling every error the same way.
  • 0 is a valid u8 but not a valid guess, so the range check catches it.

You could write if (guess < secret) ... else if (guess > secret) ... else ..., and that works fine. Zig also has std.math.order(a, b), which returns an enum with three values: .lt (less than), .gt (greater than) and .eq (equal). A switch on it reads nicely, and the compiler makes sure you handle all three:

const std = @import("std");
pub fn main() void {
const secret: u8 = 42;
for ([_]u8{ 10, 99, 42 }) |guess| {
switch (std.math.order(guess, secret)) {
.lt => std.debug.print("{d}: too small!\n", .{guess}),
.gt => std.debug.print("{d}: too big!\n", .{guess}),
.eq => std.debug.print("{d}: you got it!\n", .{guess}),
}
}
}

Output:

10: too small!
99: too big!
42: you got it!

Leave out the .eq prong and Zig refuses to compile, with “switch must handle all possibilities”. That’s the point: you can’t forget the winning case. Zig Switch has more on how this works.

Step 6: The game loop, tested with fake input

Section titled “Step 6: The game loop, tested with fake input”

Now let’s put it together. The game keeps asking until the player wins, so it’s a while (true) loop that returns on a correct guess.

Here’s a trick that makes the game much easier to work on: put it in a function play that takes a reader and a writer, instead of making the stdin reader inside. The real program passes stdin. While you’re testing, you pass a reader over a fixed string, std.Io.Reader.fixed(...), so the “player” types the same thing every time. And with a fixed secret, the whole game becomes repeatable:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
// Pretend the player typed these lines.
var in: std.Io.Reader = .fixed("50\nhello\n25\n37\n42\n");
var out_buffer: [256]u8 = undefined;
var stdout_writer = std.Io.File.stdout().writer(init.io, &out_buffer);
try play(42, &in, &stdout_writer.interface);
}
/// Plays one round: asks for guesses until the player gets it or the input ends.
fn play(secret: u8, in: *std.Io.Reader, out: *std.Io.Writer) !void {
try out.writeAll("Guess the number! (1 to 100)\n");
var attempts: u32 = 0;
while (true) {
try out.writeAll("Your guess: ");
try out.flush();
const line = try in.takeDelimiter('\n') orelse {
try out.print("\nBye! The number was {d}.\n", .{secret});
try out.flush();
return;
};
const guess = parseGuess(line) orelse {
try out.writeAll("Please type a whole number from 1 to 100.\n");
continue;
};
attempts += 1;
switch (std.math.order(guess, secret)) {
.lt => try out.writeAll("Too small!\n"),
.gt => try out.writeAll("Too big!\n"),
.eq => {
try out.print("You got it in {d} attempts!\n", .{attempts});
try out.flush();
return;
},
}
}
}
/// Turns a typed line into a guess from 1 to 100, or null if it isn't one.
fn parseGuess(line: []const u8) ?u8 {
const text = std.mem.trim(u8, line, " \t\r");
const n = std.fmt.parseInt(u8, text, 10) catch return null;
if (n < 1 or n > 100) return null;
return n;
}

Output:

Guess the number! (1 to 100)
Your guess: Too big!
Your guess: Please type a whole number from 1 to 100.
Your guess: Too small!
Your guess: Too small!
Your guess: You got it in 4 attempts!

The answers sit right after “Your guess:” because nobody actually typed them, so the terminal never echoed them. Everything else is exactly what a player would see. Let’s walk through play:

  • in: *std.Io.Reader and out: *std.Io.Writer are the general reader and writer interfaces. A stdin reader, a file reader and a fixed string all give you a *std.Io.Reader, so play works with any of them (Zig Readers & Writers goes deeper).
  • try in.takeDelimiter('\n') orelse { ... }: try passes real read errors up, and the orelse block runs when the input has ended. Without it, a player who presses Ctrl+D would get stuck in an endless loop of prompts.
  • parseGuess(line) orelse { ...; continue; } prints a kind message and jumps back to the top of the loop before attempts += 1, so bad input doesn’t cost an attempt.
  • On .eq, the function flushes and returns, which ends the loop and the game.

The last change is in main: a random secret instead of 42, and the real stdin instead of the fixed string. play and parseGuess stay exactly as they are. Here’s the whole file:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const io = init.io;
// Pick the secret number.
var seed: u64 = undefined;
io.random(std.mem.asBytes(&seed));
var prng: std.Random.DefaultPrng = .init(seed);
const secret = prng.random().intRangeAtMost(u8, 1, 100);
// Set up the keyboard (stdin) and the screen (stdout).
var in_buffer: [256]u8 = undefined;
var stdin_reader = std.Io.File.stdin().reader(io, &in_buffer);
var out_buffer: [256]u8 = undefined;
var stdout_writer = std.Io.File.stdout().writer(io, &out_buffer);
try play(secret, &stdin_reader.interface, &stdout_writer.interface);
}
/// Plays one round: asks for guesses until the player gets it or the input ends.
fn play(secret: u8, in: *std.Io.Reader, out: *std.Io.Writer) !void {
try out.writeAll("Guess the number! (1 to 100)\n");
var attempts: u32 = 0;
while (true) {
try out.writeAll("Your guess: ");
try out.flush();
const line = try in.takeDelimiter('\n') orelse {
try out.print("\nBye! The number was {d}.\n", .{secret});
try out.flush();
return;
};
const guess = parseGuess(line) orelse {
try out.writeAll("Please type a whole number from 1 to 100.\n");
continue;
};
attempts += 1;
switch (std.math.order(guess, secret)) {
.lt => try out.writeAll("Too small!\n"),
.gt => try out.writeAll("Too big!\n"),
.eq => {
try out.print("You got it in {d} attempts!\n", .{attempts});
try out.flush();
return;
},
}
}
}
/// Turns a typed line into a guess from 1 to 100, or null if it isn't one.
fn parseGuess(line: []const u8) ?u8 {
const text = std.mem.trim(u8, line, " \t\r");
const n = std.fmt.parseInt(u8, text, 10) catch return null;
if (n < 1 or n > 100) return null;
return n;
}

Play it:

Terminal window
zig run guess.zig

For example:

Guess the number! (1 to 100)
Your guess: hello
Please type a whole number from 1 to 100.
Your guess: 50
Too small!
Your guess: 75
Too small!
Your guess: 88
You got it in 3 attempts!

Your secret will be different, of course. If you give up, press Ctrl+D (Ctrl+Z then Enter on Windows) and the game tells you the answer. Halving the range each time, like this player did, always wins within 7 guesses for 1 to 100.

To share the game, build a real program file and send that instead: zig build-exe guess.zig -O fast makes ./guess (guess.exe on Windows).

Forgetting to flush the prompt. Take out the try out.flush(); after "Your guess: " and the game looks broken. Here’s that version in a terminal, after typing 50 and 20:

50
20

That’s all you see. The prompt and the “Too big!” lines are waiting in the writer’s buffer, which only gets written when it fills up or when someone flushes it. Rule of thumb: flush before every read in an interactive program.

Not trimming the line. parseInt(u8, "42\r", 10) is error.InvalidCharacter. On Linux and macOS you might never notice, then every guess fails for a friend on Windows. std.mem.trim costs nothing, so always trim typed input.

Comparing text with a number. line is a []u8, the secret is a u8, and Zig won’t turn one into the other for you. if (line == secret) doesn’t compile. Parse first, then compare.

Using try on parseInt in the game loop. const guess = try std.fmt.parseInt(u8, text, 10); compiles, but the first typo ends the whole program with error: InvalidCharacter. try means “give up and pass the error up”. For user input, catch and ask again.

Each of these is small. Try them on your own copy:

  • Fix the grammar. Guess right on the first try and the game says “1 attempts”. Print “attempt” when attempts == 1.
  • Limit the attempts. Give the player 7 tries. When they run out, show the secret and stop.
  • Play again. After a win, ask “Play again? (y/n)” and start a new round with a new secret from the same prng.
  • Warmer hints. Say “very close!” when the guess is within 3. @abs(@as(i16, guess) - secret) gives the distance.
  • Choose the range. Read the top number from the command line, zig run guess.zig -- 1000, with Zig Command-Line Arguments. You’ll need a wider type than u8.
  • Write tests. parseGuess and play don’t touch the terminal, so they’re easy to check in a test block with std.Io.Reader.fixed and std.Io.Writer.fixed. Zig Testing shows how.
  • std.Random.DefaultPrng makes random-looking numbers from a seed. A fixed seed repeats; seed it from io.random for a real game. Keep the generator in a var.
  • random.intRangeAtMost(u8, 1, 100) picks a number with both ends included.
  • Read a line with a buffered stdin reader and takeDelimiter('\n'), which returns null at the end of input. Flush your prompt before reading.
  • std.fmt.parseInt returns an error union. Trim the text first, and use catch to ask again instead of crashing.
  • std.math.order plus a switch handles less, greater and equal, and the compiler checks you covered all three.
  • A function that takes *std.Io.Reader and *std.Io.Writer can be run with fake input from std.Io.Reader.fixed.

Next up: Zig Project: Word Counter, reading a file named on the command line and counting its words with a hash map.

Quick check

1. You seed the generator with .init(12345) and run the game twice. What happens?
2. The player types 300. What does std.fmt.parseInt(u8, "300", 10) return?
3. The prompt "Your guess: " never appears, but typing still works. What's missing?
4. What does takeDelimiter('\n') return when the player presses Ctrl+D?