zig/example/guess_number/main.zig

47 lines
1.3 KiB
Zig
Raw Normal View History

export executable "guess_number";
2016-01-16 01:45:52 +00:00
import "std.zig";
import "rand.zig";
pub fn main(args: [][]u8) i32 => {
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
fprint_str(stderr_fileno, "unable to get random bytes\n");
2016-01-02 10:38:45 +00:00
return 1;
}
var rand : Rand;
rand.init(seed);
const answer = rand.range_u64(0, 100) + 1;
2016-01-02 10:38:45 +00:00
while (true) {
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;
// TODO fix this awkward error handling
if (readline(line_buf, &line_len) || line_len == line_buf.len) {
// TODO full error message
fprint_str(stderr_fileno, "unable to read input\n");
return 1;
}
var guess : u64;
2016-01-08 11:08:42 +00:00
if (parse_u64(line_buf[0...line_len - 1], 10, &guess)) {
print_str("Invalid number format.\n");
} 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;
}
}
}