2016-02-28 13:06:46 +08:00
|
|
|
const std = @import("std");
|
|
|
|
const io = std.io;
|
2017-03-10 08:12:15 +08:00
|
|
|
const fmt = std.fmt;
|
2016-09-01 11:23:47 +08:00
|
|
|
const Rand = std.rand.Rand;
|
2016-02-28 13:06:46 +08:00
|
|
|
const os = std.os;
|
2015-12-18 05:59:08 +08:00
|
|
|
|
2017-04-04 12:17:24 +08:00
|
|
|
pub fn main() -> %void {
|
2016-02-28 13:06:46 +08:00
|
|
|
%%io.stdout.printf("Welcome to the Guess Number Game in Zig.\n");
|
2015-12-18 05:59:08 +08:00
|
|
|
|
2017-02-13 06:22:35 +08:00
|
|
|
var seed_bytes: [@sizeOf(usize)]u8 = undefined;
|
2017-05-19 22:39:59 +08:00
|
|
|
%%os.getRandomBytes(seed_bytes[0..]);
|
2017-02-13 06:22:35 +08:00
|
|
|
const seed = std.mem.readInt(seed_bytes, usize, true);
|
2017-04-18 14:47:10 +08:00
|
|
|
var rand = Rand.init(seed);
|
2016-01-02 18:38:45 +08:00
|
|
|
|
2017-06-01 06:23:56 +08:00
|
|
|
const answer = rand.range(u8, 0, 100) + 1;
|
2015-12-18 05:59:08 +08:00
|
|
|
|
2016-01-02 18:38:45 +08:00
|
|
|
while (true) {
|
2016-02-28 13:06:46 +08:00
|
|
|
%%io.stdout.printf("\nGuess a number between 1 and 100: ");
|
2016-01-26 14:56:46 +08:00
|
|
|
var line_buf : [20]u8 = undefined;
|
2016-01-25 13:53:00 +08:00
|
|
|
|
2017-05-19 22:39:59 +08:00
|
|
|
const line_len = io.stdin.read(line_buf[0..]) %% |err| {
|
2017-02-06 16:10:32 +08:00
|
|
|
%%io.stdout.printf("Unable to read from stdin: {}\n", @errorName(err));
|
2016-01-26 04:53:40 +08:00
|
|
|
return err;
|
|
|
|
};
|
2016-01-08 18:59:37 +08:00
|
|
|
|
2017-05-19 22:39:59 +08:00
|
|
|
const guess = fmt.parseUnsigned(u8, line_buf[0..line_len - 1], 10) %% {
|
2016-02-28 13:06:46 +08:00
|
|
|
%%io.stdout.printf("Invalid number.\n");
|
2016-01-26 04:53:40 +08:00
|
|
|
continue;
|
|
|
|
};
|
|
|
|
if (guess > answer) {
|
2016-02-28 13:06:46 +08:00
|
|
|
%%io.stdout.printf("Guess lower.\n");
|
2016-01-08 18:59:37 +08:00
|
|
|
} else if (guess < answer) {
|
2016-02-28 13:06:46 +08:00
|
|
|
%%io.stdout.printf("Guess higher.\n");
|
2016-01-08 18:59:37 +08:00
|
|
|
} else {
|
2016-02-28 13:06:46 +08:00
|
|
|
%%io.stdout.printf("You win!\n");
|
2016-01-23 17:45:54 +08:00
|
|
|
return;
|
2015-12-18 05:59:08 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|