2015-12-17 21:59:08 +00:00
|
|
|
export executable "guess_number";
|
|
|
|
|
|
|
|
use "std.zig";
|
2016-01-06 11:41:11 +00:00
|
|
|
use "rand.zig";
|
2015-12-17 21:59:08 +00:00
|
|
|
|
2016-01-02 10:38:45 +00:00
|
|
|
pub fn main(argc: isize, argv: &&u8, env: &&u8) -> i32 {
|
2015-12-17 21:59:08 +00:00
|
|
|
print_str("Welcome to the Guess Number Game in Zig.\n");
|
|
|
|
|
|
|
|
var seed : u32;
|
2016-01-03 04:56:33 +00:00
|
|
|
var err : isize;
|
2016-01-06 11:41:11 +00:00
|
|
|
if ({err = os_get_random_bytes(&seed as &u8, #sizeof(u32)); err != #sizeof(u32)}) {
|
2016-01-02 10:38:45 +00:00
|
|
|
// TODO full error message
|
2016-01-07 10:23:38 +00:00
|
|
|
fprint_str(stderr_fileno, "unable to get random bytes\n");
|
2016-01-02 10:38:45 +00:00
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
2016-01-06 11:41:11 +00:00
|
|
|
var rand : Rand;
|
|
|
|
rand.init(seed);
|
2015-12-17 21:59:08 +00:00
|
|
|
|
2016-01-06 11:41:11 +00:00
|
|
|
const answer = rand.range_u64(0, 100) + 1;
|
2015-12-17 21:59:08 +00:00
|
|
|
|
2016-01-02 10:38:45 +00:00
|
|
|
while (true) {
|
2016-01-07 10:23:38 +00:00
|
|
|
print_str("\nGuess a number between 1 and 100: ");
|
|
|
|
var line_buf : [20]u8;
|
2016-01-08 10:59:37 +00:00
|
|
|
var line_len : usize;
|
|
|
|
// TODO fix this awkward error handling
|
|
|
|
if (readline(line_buf, &line_len) || line_len == line_buf.len) {
|
2016-01-07 10:23:38 +00:00
|
|
|
// TODO full error message
|
|
|
|
fprint_str(stderr_fileno, "unable to read input\n");
|
|
|
|
return 1;
|
2016-01-08 10:59:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var guess : u64;
|
2016-01-08 11:08:42 +00:00
|
|
|
if (parse_u64(line_buf[0...line_len - 1], 10, &guess)) {
|
2015-12-17 21:59:08 +00:00
|
|
|
print_str("Invalid number format.\n");
|
2016-01-08 10:59:37 +00:00
|
|
|
} else if (guess > answer) {
|
|
|
|
print_str("Guess lower.\n");
|
|
|
|
} else if (guess < answer) {
|
|
|
|
print_str("Guess higher.\n");
|
|
|
|
} else {
|
|
|
|
print_str("You win!\n");
|
|
|
|
return 0;
|
2015-12-17 21:59:08 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|