2017-12-04 15:35:55 +00:00
|
|
|
const builtin = @import("builtin");
|
2016-02-28 05:06:46 +00:00
|
|
|
const std = @import("std");
|
|
|
|
const io = std.io;
|
2017-03-10 00:12:15 +00:00
|
|
|
const fmt = std.fmt;
|
2015-12-17 21:59:08 +00:00
|
|
|
|
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();
|
2020-02-20 18:43:05 +00:00
|
|
|
const stdin = io.getStdIn();
|
2017-10-31 08:47:55 +00:00
|
|
|
|
2019-12-09 05:03:08 +00:00
|
|
|
try stdout.print("Welcome to the Guess Number Game in Zig.\n", .{});
|
2015-12-17 21:59:08 +00:00
|
|
|
|
2020-12-18 04:09:42 +00:00
|
|
|
const answer = std.crypto.random.intRangeLessThan(u8, 0, 100) + 1;
|
2015-12-17 21:59:08 +00:00
|
|
|
|
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: ", .{});
|
2018-05-26 23:16:39 +01:00
|
|
|
var line_buf: [20]u8 = undefined;
|
2016-01-25 05:53:00 +00:00
|
|
|
|
2020-02-20 18:43:05 +00:00
|
|
|
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");
|
2016-01-08 10:59:37 +00:00
|
|
|
|
2018-11-29 21:38:39 +00:00
|
|
|
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", .{});
|
2016-01-08 10:59:37 +00:00
|
|
|
} else if (guess < answer) {
|
2019-12-09 05:03:08 +00:00
|
|
|
try stdout.print("Guess higher.\n", .{});
|
2016-01-08 10:59:37 +00:00
|
|
|
} else {
|
2019-12-09 05:03:08 +00:00
|
|
|
try stdout.print("You win!\n", .{});
|
2016-01-23 09:45:54 +00:00
|
|
|
return;
|
2015-12-17 21:59:08 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|