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-08-31 20:23:47 -07:00
|
|
|
const Rand = std.rand.Rand;
|
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();
|
2017-11-07 00:22:27 -08:00
|
|
|
var stdout_file_stream = io.FileOutStream.init(&stdout_file);
|
|
|
|
const stdout = &stdout_file_stream.stream;
|
2017-10-31 01:47:55 -07:00
|
|
|
|
2018-01-07 13:51:46 -08:00
|
|
|
var stdin_file = try io.getStdIn();
|
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
|
|
|
|
2017-02-12 14:22:35 -08:00
|
|
|
var seed_bytes: [@sizeOf(usize)]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;
|
|
|
|
};
|
2017-12-04 07:35:55 -08:00
|
|
|
const seed = std.mem.readInt(seed_bytes, usize, builtin.Endian.Big);
|
2017-04-17 23:47:10 -07:00
|
|
|
var rand = Rand.init(seed);
|
2016-01-02 02:38:45 -08:00
|
|
|
|
2017-05-31 15:23:56 -07:00
|
|
|
const answer = rand.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: ");
|
2016-01-25 22:56:46 -08:00
|
|
|
var line_buf : [20]u8 = undefined;
|
2016-01-24 21:53:00 -08:00
|
|
|
|
2018-01-07 14:28:20 -08:00
|
|
|
const line_len = stdin_file.read(line_buf[0..]) catch |err| {
|
2018-01-07 13:51:46 -08:00
|
|
|
try stdout.print("Unable to read from stdin: {}\n", @errorName(err));
|
2016-01-25 12:53:40 -08:00
|
|
|
return err;
|
|
|
|
};
|
2016-01-08 02:59:37 -08:00
|
|
|
|
2018-01-07 14:28:20 -08:00
|
|
|
const guess = fmt.parseUnsigned(u8, line_buf[0..line_len - 1], 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
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|