zig/example/guess_number/main.zig
Andrew Kelley 9d4eaf1e07
update std lib API for I/O
std.io.FileInStream -> std.os.File.InStream
std.io.FileInStream.init(file) -> file.inStream()
std.io.FileOutStream -> std.os.File.OutStream
std.io.FileOutStream.init(file) -> file.outStream()

remove a lot of error code possibilities from os functions

std.event.net.socketRead -> std.event.net.read
std.event.net.socketWrite -> std.event.net.write
add std.event.net.readv
add std.event.net.writev
add std.event.net.readvPosix
add std.event.net.writevPosix
add std.event.net.OutStream
add std.event.net.InStream

add std.event.io.InStream
add std.event.io.OutStream
2018-09-30 17:28:35 -04:00

49 lines
1.5 KiB
Zig

const builtin = @import("builtin");
const std = @import("std");
const io = std.io;
const fmt = std.fmt;
const os = std.os;
pub fn main() !void {
var stdout_file = try io.getStdOut();
const stdout = &stdout_file.outStream().stream;
try stdout.print("Welcome to the Guess Number Game in Zig.\n");
var seed_bytes: [@sizeOf(u64)]u8 = undefined;
os.getRandomBytes(seed_bytes[0..]) catch |err| {
std.debug.warn("unable to seed random number generator: {}", err);
return err;
};
const seed = std.mem.readInt(seed_bytes, u64, builtin.Endian.Big);
var prng = std.rand.DefaultPrng.init(seed);
const answer = prng.random.range(u8, 0, 100) + 1;
while (true) {
try stdout.print("\nGuess a number between 1 and 100: ");
var line_buf: [20]u8 = undefined;
const line_len = io.readLine(line_buf[0..]) catch |err| switch (err) {
error.InputTooLong => {
try stdout.print("Input too long.\n");
continue;
},
error.EndOfFile, error.StdInUnavailable => return err,
};
const guess = fmt.parseUnsigned(u8, line_buf[0..line_len], 10) catch {
try stdout.print("Invalid number.\n");
continue;
};
if (guess > answer) {
try stdout.print("Guess lower.\n");
} else if (guess < answer) {
try stdout.print("Guess higher.\n");
} else {
try stdout.print("You win!\n");
return;
}
}
}