Andrew Kelley 07a71fc322 improved behavior on debug safety crash
* instead of emitting a breakpoint for a debug safety crash,
   zig calls a panic function which prints an error message
   and a stack trace and then calls abort.
 * on freestanding OS, this panic function has a default
   implementation of a simple infinite loop.
 * users can override the panic implementation by providing
   `pub fn panic(message: []const u8) -> unreachable { }`
 * workaround for LLVM segfaulting when you try to use cold
   calling convention on ARM.

closes #245
2017-02-06 03:10:32 -05:00

39 lines
1.1 KiB
Zig

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");
var seed: [@sizeOf(usize)]u8 = undefined;
%%os.getRandomBytes(seed);
var rand: Rand = undefined;
rand.init(([]usize)(seed)[0]);
const answer = rand.rangeUnsigned(u8, 0, 100) + 1;
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: {}\n", @errorName(err));
return err;
};
const guess = io.parseUnsigned(u8, line_buf[0...line_len - 1], 10) %% {
%%io.stdout.printf("Invalid number.\n");
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;
}
}
}