Pr3Leuchter-ZahlenrateSpiel/Zahlenraten.zig

61 lines
2.1 KiB
Zig
Raw Permalink Normal View History

2024-10-14 00:03:51 +02:00
const std = @import("std");
pub fn main() !void {
const reader = std.io.getStdIn().reader();
const writer = std.io.getStdOut().writer();
2024-10-14 08:48:41 +02:00
const rand = std.crypto.random;
2024-10-14 00:03:51 +02:00
2024-10-14 08:48:41 +02:00
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});
}
2024-10-14 00:03:51 +02:00
}
}
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)];
2024-10-14 08:48:41 +02:00
const result = std.fmt.parseInt(i64, input_slice, 10) catch |err| {
2024-10-14 00:03:51 +02:00
switch (err) {
error.InvalidCharacter => {
2024-10-14 08:48:41 +02:00
try writer.print("Error: '{s}' contains invalid character, try again! \n", .{input_slice});
2024-10-14 00:03:51 +02:00
},
error.Overflow => {
2024-10-14 08:48:41 +02:00
try writer.print("Error: '{s}' ist too big for an i64, try again! \n", .{input_slice});
2024-10-14 00:03:51 +02:00
},
}
try writer.print("\n", .{});
continue;
};
return result;
}
}