2015-12-17 21:59:08 +00:00
|
|
|
export executable "guess_number";
|
|
|
|
|
2016-01-16 01:45:52 +00:00
|
|
|
import "std.zig";
|
|
|
|
import "rand.zig";
|
2015-12-17 21:59:08 +00:00
|
|
|
|
2016-01-16 07:07:20 +00:00
|
|
|
pub fn main(args: [][]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-19 04:13:14 +00:00
|
|
|
const seed_bytes = (&u8)(&seed)[0...@sizeof(u32)];
|
|
|
|
const err = os_get_random_bytes(seed_bytes);
|
2016-01-14 01:15:51 +00:00
|
|
|
if (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-19 04:13:14 +00:00
|
|
|
var line_len : isize;
|
2016-01-08 10:59:37 +00:00
|
|
|
// 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
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|