2017-12-04 07:35:55 -08:00
|
|
|
const builtin = @import("builtin");
|
2016-02-27 21:06:46 -08:00
|
|
|
const std = @import("std");
|
|
|
|
const io = std.io;
|
2017-03-09 16:12:15 -08:00
|
|
|
const fmt = std.fmt;
|
2016-02-27 21:06:46 -08:00
|
|
|
const os = std.os;
|
2015-12-17 13:59:08 -08:00
|
|
|
|
2018-01-31 19:48:40 -08:00
|
|
|
pub fn main() !void {
|
2018-01-07 13:51:46 -08:00
|
|
|
var stdout_file = try io.getStdOut();
|
2018-09-30 14:23:42 -07:00
|
|
|
const stdout = &stdout_file.outStream().stream;
|
2017-10-31 01:47:55 -07:00
|
|
|
|
2018-01-07 13:51:46 -08:00
|
|
|
try stdout.print("Welcome to the Guess Number Game in Zig.\n");
|
2015-12-17 13:59:08 -08:00
|
|
|
|
2018-03-29 09:33:29 -07:00
|
|
|
var seed_bytes: [@sizeOf(u64)]u8 = undefined;
|
2018-01-08 21:07:01 -08:00
|
|
|
os.getRandomBytes(seed_bytes[0..]) catch |err| {
|
|
|
|
std.debug.warn("unable to seed random number generator: {}", err);
|
|
|
|
return err;
|
|
|
|
};
|
2018-12-12 17:19:46 -08:00
|
|
|
const seed = std.mem.readIntNative(u64, &seed_bytes);
|
2018-03-29 09:33:29 -07:00
|
|
|
var prng = std.rand.DefaultPrng.init(seed);
|
2016-01-02 02:38:45 -08:00
|
|
|
|
2018-03-29 09:33:29 -07:00
|
|
|
const answer = prng.random.range(u8, 0, 100) + 1;
|
2015-12-17 13:59:08 -08:00
|
|
|
|
2016-01-02 02:38:45 -08:00
|
|
|
while (true) {
|
2018-01-07 13:51:46 -08:00
|
|
|
try stdout.print("\nGuess a number between 1 and 100: ");
|
2018-05-26 15:16:39 -07:00
|
|
|
var line_buf: [20]u8 = undefined;
|
2016-01-24 21:53:00 -08:00
|
|
|
|
2018-11-29 13:38:39 -08:00
|
|
|
const line = io.readLineSlice(line_buf[0..]) catch |err| switch (err) {
|
|
|
|
error.OutOfMemory => {
|
2018-04-02 08:34:31 -07:00
|
|
|
try stdout.print("Input too long.\n");
|
|
|
|
continue;
|
|
|
|
},
|
2018-11-29 13:38:39 -08:00
|
|
|
else => return err,
|
2016-01-25 12:53:40 -08:00
|
|
|
};
|
2016-01-08 02:59:37 -08:00
|
|
|
|
2018-11-29 13:38:39 -08:00
|
|
|
const guess = fmt.parseUnsigned(u8, line, 10) catch {
|
2018-01-07 13:51:46 -08:00
|
|
|
try stdout.print("Invalid number.\n");
|
2016-01-25 12:53:40 -08:00
|
|
|
continue;
|
|
|
|
};
|
|
|
|
if (guess > answer) {
|
2018-01-07 13:51:46 -08:00
|
|
|
try stdout.print("Guess lower.\n");
|
2016-01-08 02:59:37 -08:00
|
|
|
} else if (guess < answer) {
|
2018-01-07 13:51:46 -08:00
|
|
|
try stdout.print("Guess higher.\n");
|
2016-01-08 02:59:37 -08:00
|
|
|
} else {
|
2018-01-07 13:51:46 -08:00
|
|
|
try stdout.print("You win!\n");
|
2016-01-23 01:45:54 -08:00
|
|
|
return;
|
2015-12-17 13:59:08 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|