From ee6e59acf963d1d776aa87b0310e699410c4ca0a Mon Sep 17 00:00:00 2001 From: Rowan Torbitzky-Lane Date: Wed, 19 Mar 2025 00:23:03 -0500 Subject: [PATCH] finish guessing game --- guessing_game/src/main.rs | 45 ++++++++++++++++++++++----------------- 1 file changed, 26 insertions(+), 19 deletions(-) diff --git a/guessing_game/src/main.rs b/guessing_game/src/main.rs index 0739289..db937c8 100644 --- a/guessing_game/src/main.rs +++ b/guessing_game/src/main.rs @@ -7,33 +7,40 @@ fn main() { // I remember looking this up. Will find the undeprecated calls later. let secret_number = rand::thread_rng().gen_range(1..=100); - println!("The secret number is: {}", secret_number); - - println!("Please input your guess: "); - - // ::new() is an associated type. Function is implemented on this type - // Returns a new instance of String - let mut guess = String::new(); + // println!("Secret number: {}", secret_number); let apples = 5; // immutable let mut bananas = 7; // mutable - io::stdin() - .read_line(&mut guess) - .expect("Failed to read line!"); // Use this if truly want to error out. Use pattern matching otherwise - // Inner programming me screaming rn. This actually isn't all that // bad tho. What's wrong with reusing variable names? // Rust calls it shadowing. - let guess: u32 = guess.trim().parse().expect("Please type a number!"); + loop { + // ::new() is an associated type. Function is implemented on this type + // Returns a new instance of String + let mut guess = String::new(); - println!("You guessed: {}", guess); + io::stdin() + .read_line(&mut guess) + .expect("Failed to read line!"); // Use this if truly want to error out. Use pattern matching otherwise + println!("You guessed: {}", guess); - match guess.cmp(&secret_number) { - // pogger matching - Ordering::Less => println!("Too Small!"), - // -1 => println!("Too Small!"), // Not doable - Ordering::Greater => println!("Too big!"), - Ordering::Equal => println!("You win!"), + // Just like Haskell. This is awesome. + // Really just like Haskell, this is sick af. + let guess: u32 = match guess.trim().parse() { + Ok(num) => num, + Err(_) => continue, + }; + + match guess.cmp(&secret_number) { + // pogger matching + Ordering::Less => println!("Too Small!"), + // -1 => println!("Too Small!"), // Not doable + Ordering::Greater => println!("Too big!"), + Ordering::Equal => { + println!("You win!"); + break; + } + } } }