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.
What you’ll build
Section titled “What you’ll build”Here’s a real game, played in a terminal against the finished program:
Guess the number! (1 to 100)Your guess: helloPlease type a whole number from 1 to 100.Your guess: 50Too big!Your guess: 25Too small!Your guess: 37Too small!Your guess: 43Too big!Your guess: 40Too big!Your guess: 38Too small!Your guess: 39You 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.Randomand a seed frominit.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.orderand aswitch(Zig Switch). - Splitting the game into a function that takes a reader and a writer, so you can run it with fake input.
Step 1: Set up
Section titled “Step 1: Set up”You don’t need a build script for a one-file program. Make a folder and a file:
mkdir guesscd guessCreate guess.zig in that folder. Every program on this page goes in that file, replacing the last one, and you run it with:
zig run guess.zigIf 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.
Step 2: Pick a secret number
Section titled “Step 2: Pick a secret number”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 53Line by line:
var prng: std.Random.DefaultPrng = .init(12345);creates the generator with the seed12345. It has to bevar, because every number you take from it changes its inner state.prng.random()gives you astd.Random, the general “source of random numbers” with all the handy methods on it.random.intRangeAtMost(u8, 1, 100)returns au8from 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.
A different seed every time
Section titled “A different seed every time”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 98The secret is 1The secret is 33io.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.
Step 3: Read a guess from the keyboard
Section titled “Step 3: Read a guess from the keyboard”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:
zig run guess.zigYou’ll see:
Your guess: 42You typed " 42" (3 bytes)What’s going on:
- The stdin reader fills
in_bufferfrom 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 returnsnullwhen the input has ended (the player pressed Ctrl+D, or you piped in an empty file), andorelse ""turns that into an empty string for now.- The
flushafter 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.parseIntwon’t accept that space, which brings us to the next step.
Step 4: Turn the text into a number
Section titled “Step 4: Turn the text into a number”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.InvalidCharacterA few surprises worth knowing:
" 7"fails. A space isn’t a digit, so trim the line first."300"doesn’t fit in au8(0 to 255), so you geterror.Overflow. Zig never wraps it to some other number behind your back."-3"is alsoOverflowfor an unsigned type, notInvalidCharacter: 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:
42750not a guessnot a guessnot a guessstd.mem.trim(u8, line, " \t\r")cuts spaces, tabs and\roff both ends. The\ris there for Windows, where pressing Enter sends\r\n, andtakeDelimiter('\n')leaves the\rbehind.catch return nullmeans “if parsing fails, for any reason, this function returnsnull”. It’s the short form of handling every error the same way.0is a validu8but not a valid guess, so the range check catches it.
Step 5: Compare the guess with the secret
Section titled “Step 5: Compare the guess with the secret”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.Readerandout: *std.Io.Writerare the general reader and writer interfaces. A stdin reader, a file reader and a fixed string all give you a*std.Io.Reader, soplayworks with any of them (Zig Readers & Writers goes deeper).try in.takeDelimiter('\n') orelse { ... }:trypasses real read errors up, and theorelseblock 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 beforeattempts += 1, so bad input doesn’t cost an attempt.- On
.eq, the function flushes and returns, which ends the loop and the game.
Step 7: The complete program
Section titled “Step 7: The complete program”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:
zig run guess.zigFor example:
Guess the number! (1 to 100)Your guess: helloPlease type a whole number from 1 to 100.Your guess: 50Too small!Your guess: 75Too small!Your guess: 88You 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).
Common mistakes
Section titled “Common mistakes”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:
5020That’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.
Ideas to extend it
Section titled “Ideas to extend it”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 thanu8. - Write tests.
parseGuessandplaydon’t touch the terminal, so they’re easy to check in atestblock withstd.Io.Reader.fixedandstd.Io.Writer.fixed. Zig Testing shows how.
std.Random.DefaultPrngmakes random-looking numbers from a seed. A fixed seed repeats; seed it fromio.randomfor a real game. Keep the generator in avar.random.intRangeAtMost(u8, 1, 100)picks a number with both ends included.- Read a line with a buffered stdin reader and
takeDelimiter('\n'), which returnsnullat the end of input. Flush your prompt before reading. std.fmt.parseIntreturns an error union. Trim the text first, and usecatchto ask again instead of crashing.std.math.orderplus aswitchhandles less, greater and equal, and the compiler checks you covered all three.- A function that takes
*std.Io.Readerand*std.Io.Writercan be run with fake input fromstd.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
Section titled “Quick check”Quick check
Read more
Section titled “Read more”std.Randomsource (0.17.1): every generator and every helper likeintRangeAtMost,float,shuffleandweightedIndex, with doc comments.- Optionals in the 0.17.1 language reference:
?T,orelseandnull, used bytakeDelimiterandparseGuess. switchin the 0.17.1 language reference: exhaustive switches on enums likestd.math.Order.- Writergate in the 0.15.1 release notes: why readers and writers have their own buffers, and why you have to flush.