zig/example/guess_number/main.zig

41 lines
1.2 KiB
Zig
Raw Normal View History

const std = @import("std");
const io = std.io;
const Rand = std.rand.Rand;
const os = std.os;
pub fn main(args: [][]u8) -> %void {
%%io.stdout.printf("Welcome to the Guess Number Game in Zig.\n");
2016-08-17 13:42:50 +08:00
var seed: [@sizeOf(usize)]u8 = undefined;
2016-08-18 11:11:04 +08:00
%%os.getRandomBytes(seed);
2016-08-17 13:42:50 +08:00
var rand: Rand = undefined;
rand.init(([]usize)(seed)[0]);
2016-01-02 18:38:45 +08:00
2016-08-17 13:42:50 +08:00
const answer = rand.rangeUnsigned(u8, 0, 100) + 1;
2016-01-02 18:38:45 +08:00
while (true) {
%%io.stdout.printf("\nGuess a number between 1 and 100: ");
var line_buf : [20]u8 = undefined;
const line_len = io.stdin.read(line_buf) %% |err| {
%%io.stdout.printf("Unable to read from stdin: ");
2016-09-06 05:03:11 +08:00
%%io.stdout.printf(@errorName(err));
%%io.stdout.printf("\n");
2016-01-26 04:53:40 +08:00
return err;
};
2016-08-17 13:42:50 +08:00
const guess = io.parseUnsigned(u8, line_buf[0...line_len - 1], 10) %% {
%%io.stdout.printf("Invalid number.\n");
2016-01-26 04:53:40 +08:00
continue;
};
if (guess > answer) {
%%io.stdout.printf("Guess lower.\n");
} else if (guess < answer) {
%%io.stdout.printf("Guess higher.\n");
} else {
%%io.stdout.printf("You win!\n");
return;
}
}
}