zig/test/standalone/guess_number/main.zig

39 lines
1.1 KiB
Zig
Raw Normal View History

const builtin = @import("builtin");
const std = @import("std");
const io = std.io;
const fmt = std.fmt;
2018-02-01 03:48:40 +00:00
pub fn main() !void {
2020-06-25 17:05:52 +01:00
const stdout = io.getStdOut().writer();
const stdin = io.getStdIn();
2019-12-09 05:03:08 +00:00
try stdout.print("Welcome to the Guess Number Game in Zig.\n", .{});
2020-12-18 04:09:42 +00:00
const answer = std.crypto.random.intRangeLessThan(u8, 0, 100) + 1;
2016-01-02 10:38:45 +00:00
while (true) {
2019-12-09 05:03:08 +00:00
try stdout.print("\nGuess a number between 1 and 100: ", .{});
var line_buf: [20]u8 = undefined;
const amt = try stdin.read(&line_buf);
if (amt == line_buf.len) {
try stdout.print("Input too long.\n", .{});
continue;
}
const line = std.mem.trimRight(u8, line_buf[0..amt], "\r\n");
const guess = fmt.parseUnsigned(u8, line, 10) catch {
2019-12-09 05:03:08 +00:00
try stdout.print("Invalid number.\n", .{});
2016-01-25 20:53:40 +00:00
continue;
};
if (guess > answer) {
2019-12-09 05:03:08 +00:00
try stdout.print("Guess lower.\n", .{});
} else if (guess < answer) {
2019-12-09 05:03:08 +00:00
try stdout.print("Guess higher.\n", .{});
} else {
2019-12-09 05:03:08 +00:00
try stdout.print("You win!\n", .{});
return;
}
}
}