master
1const builtin = @import("builtin");
2const std = @import("std");
3
4pub fn main() !void {
5 var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
6 const out = &stdout_writer.interface;
7 const stdin: std.fs.File = .stdin();
8
9 try out.writeAll("Welcome to the Guess Number Game in Zig.\n");
10
11 const answer = std.crypto.random.intRangeLessThan(u8, 0, 100) + 1;
12
13 while (true) {
14 try out.writeAll("\nGuess a number between 1 and 100: ");
15 var line_buf: [20]u8 = undefined;
16 const amt = try stdin.read(&line_buf);
17 if (amt == line_buf.len) {
18 try out.writeAll("Input too long.\n");
19 continue;
20 }
21 const line = std.mem.trimEnd(u8, line_buf[0..amt], "\r\n");
22
23 const guess = std.fmt.parseUnsigned(u8, line, 10) catch {
24 try out.writeAll("Invalid number.\n");
25 continue;
26 };
27 if (guess > answer) {
28 try out.writeAll("Guess lower.\n");
29 } else if (guess < answer) {
30 try out.writeAll("Guess higher.\n");
31 } else {
32 try out.writeAll("You win!\n");
33 return;
34 }
35 }
36}