Last active
March 23, 2024 14:21
-
-
Save mkaz/b8552fe6735a82a4e479b2f002cf85ca to your computer and use it in GitHub Desktop.
Guessing Game in Rust
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
[package] | |
name = "guess-game" | |
version = "0.1.0" | |
edition = "2021" | |
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html | |
[dependencies] | |
rand = "0.8.5" |
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
use rand::Rng; | |
use std::io; | |
use std::io::Write; | |
fn main() { | |
// Set number, last number in range is not included so +1 | |
let x = rand::thread_rng().gen_range(1..101); | |
// Track number of guesses | |
let mut count = 1; | |
// Prompt | |
println!("Guess a number from 1-100:"); | |
loop { | |
print!("Guess #{}: ", count); | |
// Output gets flushed on new lines | |
// To prompt on same line requires manual flush the output | |
let _ = io::stdout().flush(); | |
// Get user input | |
let mut input = String::new(); | |
io::stdin().read_line(&mut input).expect("User Input Error"); | |
// validate user input | |
let guess = match input.trim().parse::<i32>() { | |
Ok(x) => x, | |
Err(_err) => { | |
println!(" > Not a number. Try again"); | |
continue; | |
} | |
}; | |
if guess > x { | |
println!(" > Too high"); | |
} | |
else if guess < 0 { | |
println!(" > 🤨 negative number, did you read instructions?"); | |
} | |
else if guess < x { | |
println!(" > Too low"); | |
} | |
else { | |
println!(" 🎉 Congrats, it took {} guesses", count); | |
break; | |
} | |
count += 1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment