Skip to content

Instantly share code, notes, and snippets.

@moolicc
Last active June 6, 2022 21:03
Show Gist options
  • Save moolicc/b40667b2d69079442c186f6fd1761716 to your computer and use it in GitHub Desktop.
Save moolicc/b40667b2d69079442c186f6fd1761716 to your computer and use it in GitHub Desktop.
rust scratchpad
use std::{io, cmp::Ordering};
use rand::{Rng, thread_rng};
const NUM_GUESSES: i32 = 5;
const MIN: i32 = 0;
const MAX: i32 = 100;
fn main() {
start_game();
}
fn start_game() {
let answer = thread_rng().gen_range(MIN..MAX);
let mut cur_attempt = 0;
println!("I'm thinking of a number between {} and {}...", MIN, MAX);
println!("Enter any number to guess, or any other character to end the game.");
let mut won = false;
for _i in 0..NUM_GUESSES {
cur_attempt += 1;
if let Some(guess) = handle_choice() {
won = handle_guess(answer, guess);
if won {
break;
}
}
else {
break;
}
}
if won {
println!("Yep, that's the number. Well done.");
println!("I call for a do-over!\n\n");
start_game();
}
else if cur_attempt == NUM_GUESSES {
println!("Out of guesses!\n\n");
}
else {
println!("Welp, you couldn't do it.");
}
}
fn handle_choice() -> Option<i32> {
let stdin = io::stdin();
let mut input = String::new();
stdin.read_line(&mut input).ok()?;
let i = input.trim().parse::<i32>().ok()?;
println!();
Some(i)
}
fn handle_guess(answer: i32, guess: i32) -> bool {
match guess.cmp(&answer) {
Ordering::Equal => return true,
Ordering::Less => println!("That's too low!"),
Ordering::Greater => println!("That's too high!")
}
if answer * answer == guess {
println!("Well, that's a square anyway.");
}
else if answer % guess == 0 {
println!("Well, that's a factor anyway.");
}
else if guess % answer == 0 {
println!("Well, that's a multiple anyway.");
}
false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment