Andrew Kelley 6dba1f1c8e slice and array re-work plus some misc. changes
* `@truncate` builtin allows casting to the same size integer.
   It also performs two's complement casting between signed and
   unsigned integers.
 * The idiomatic way to convert between bytes and numbers is now
   `mem.readInt` and `mem.writeInt` instead of an unsafe cast.
   It works at compile time, is safer, and looks cleaner.
 * Implicitly casting an array to a slice is allowed only if the
   slice is const.
 * Constant pointer values know if their memory is from a compile-
   time constant value or a compile-time variable.
 * Cast from [N]u8 to []T no longer allowed, but [N]u8 to []const T
   still allowed.
 * Fix inability to pass a mutable pointer to comptime variable at
   compile-time to a function and have the function modify the
   memory pointed to by the pointer.
 * Add the `comptime T: type` parameter back to mem.eql. Prevents
   accidentally creating instantiations for arrays.
2017-02-12 17:35:51 -05:00

40 lines
1.2 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_bytes: [@sizeOf(usize)]u8 = undefined;
%%os.getRandomBytes(seed_bytes[0...]);
const seed = std.mem.readInt(seed_bytes, usize, true);
var rand: Rand = undefined;
rand.init(seed);
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;
}
}
}