61 lines
2.1 KiB
Zig
61 lines
2.1 KiB
Zig
const std = @import("std");
|
|
|
|
pub fn main() !void {
|
|
const reader = std.io.getStdIn().reader();
|
|
const writer = std.io.getStdOut().writer();
|
|
const rand = std.crypto.random;
|
|
|
|
try writer.print("Welcome to my number guessing game! \n\n", .{});
|
|
|
|
try writer.print("Enter an upper limit: \n", .{});
|
|
const upperLimit: i64 = try oneIntInput(writer, reader);
|
|
try writer.print("The number you need to find is between 0 and {d}! \n\n", .{upperLimit});
|
|
|
|
const targetNumber: i64 = rand.intRangeLessThan(i64, 0, upperLimit);
|
|
|
|
try writer.print("Target: {d} \n", .{targetNumber});
|
|
|
|
var counter: i64 = 0;
|
|
while(true) {
|
|
counter += 1;
|
|
try writer.print("\nEnter your guess: \n", .{});
|
|
const userGuess = try oneIntInput(writer, reader);
|
|
|
|
if (targetNumber == userGuess) {
|
|
try writer.print("Your guess {d} is correct! \n", .{userGuess});
|
|
try writer.print("It took you {d} tries. \n", .{counter});
|
|
return;
|
|
}
|
|
if (targetNumber > userGuess) {
|
|
try writer.print("Your guess '{d}' is smaller then the target number, try again! \n", .{userGuess});
|
|
}
|
|
else {
|
|
try writer.print("Your guess '{d}' is bigger then the target number, try again! \n", .{userGuess});
|
|
}
|
|
}
|
|
}
|
|
|
|
pub fn oneIntInput(writer: anytype, reader: anytype) !i64 {
|
|
var buffer: [256]u8 = undefined;
|
|
|
|
while (true) {
|
|
try writer.print("> ", .{});
|
|
const amountInputBytes = try reader.read(&buffer);
|
|
const input_slice: []u8 = buffer[0..(amountInputBytes - 1)];
|
|
|
|
const result = std.fmt.parseInt(i64, input_slice, 10) catch |err| {
|
|
switch (err) {
|
|
error.InvalidCharacter => {
|
|
try writer.print("Error: '{s}' contains invalid character, try again! \n", .{input_slice});
|
|
},
|
|
error.Overflow => {
|
|
try writer.print("Error: '{s}' ist too big for an i64, try again! \n", .{input_slice});
|
|
},
|
|
}
|
|
try writer.print("\n", .{});
|
|
continue;
|
|
};
|
|
return result;
|
|
}
|
|
}
|