Last active
June 12, 2022 18:59
-
-
Save boofexxx/811a0f6476cba6dbb2c73f9034e382f7 to your computer and use it in GitHub Desktop.
guessing game zig
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const std = @import("std"); | |
const print = std.debug.print; | |
pub fn main() anyerror!void { | |
print("Guess the number!\n", .{}); | |
var secretNumber: i32 = std.rand.DefaultPrng | |
.init(@intCast(u64, std.time.timestamp())) | |
.random().intRangeAtMost(i32, 0, 100); | |
print("The secret number is {}\n", .{secretNumber}); | |
var buf: [256]u8 = undefined; | |
var guess_str: []const u8 = undefined; | |
while (true) { | |
print("Please input your guess.\n", .{}); | |
guess_str = try(std.io.getStdIn() | |
.reader() | |
.readUntilDelimiterOrEof(buf[0..], '\n')) orelse continue; | |
guess_str = std.mem.trim(u8, guess_str, " "); | |
var guess = std.fmt.parseInt(i32, guess_str, 10) catch { | |
continue; | |
}; | |
print("{s}\n", .{guess_str}); | |
if (guess < secretNumber) { | |
print("To small!\n", .{}); | |
} else if (guess > secretNumber) { | |
print("Too big!\n", .{}); | |
} else { | |
print("You win!\n", .{}); | |
break; | |
} | |
print("You guessed: {}\n", .{guess}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment