Finished number guessing game

main
2wenty1ne 2024-10-14 08:48:41 +02:00
parent 750970b73f
commit 8f1666be9d
1 changed files with 29 additions and 13 deletions

View File

@ -1,22 +1,38 @@
const std = @import("std"); const std = @import("std");
pub fn main() !void { pub fn main() !void {
const rand = std.crypto.random;
const reader = std.io.getStdIn().reader(); const reader = std.io.getStdIn().reader();
const writer = std.io.getStdOut().writer(); const writer = std.io.getStdOut().writer();
const rand = std.crypto.random;
try writer.print("Welcome to my number guessing game! \n", .{}); try writer.print("Welcome to my number guessing game! \n\n", .{});
try writer.print("Enter an upper limit\n", .{}); try writer.print("Enter an upper limit: \n", .{});
const upperLimit = oneIntInput(writer, reader); const upperLimit: i64 = try oneIntInput(writer, reader);
try writer.print("Your upper limit is {d}! \n", .{upperLimit}); try writer.print("The number you need to find is between 0 and {d}! \n\n", .{upperLimit});
for (0..10) |i| { const targetNumber: i64 = rand.intRangeLessThan(i64, 0, upperLimit);
const randomInt = rand.intRangeLessThan(u16, 0, 3);
try writer.print("Random number {d}: {d} \n\n", .{i, randomInt}); 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 { pub fn oneIntInput(writer: anytype, reader: anytype) !i64 {
@ -27,13 +43,13 @@ pub fn oneIntInput(writer: anytype, reader: anytype) !i64 {
const amountInputBytes = try reader.read(&buffer); const amountInputBytes = try reader.read(&buffer);
const input_slice: []u8 = buffer[0..(amountInputBytes - 1)]; const input_slice: []u8 = buffer[0..(amountInputBytes - 1)];
const result: i64 = std.fmt.parseInt(i64, input_slice, 10) catch |err| { const result = std.fmt.parseInt(i64, input_slice, 10) catch |err| {
switch (err) { switch (err) {
error.InvalidCharacter => { error.InvalidCharacter => {
try writer.print("Error: Invalid character, try again! \n", .{}); try writer.print("Error: '{s}' contains invalid character, try again! \n", .{input_slice});
}, },
error.Overflow => { error.Overflow => {
try writer.print("Error: Too big for an i64, try again! \n", .{}); try writer.print("Error: '{s}' ist too big for an i64, try again! \n", .{input_slice});
}, },
} }
try writer.print("\n", .{}); try writer.print("\n", .{});