Skip to content

Instantly share code, notes, and snippets.

@glandaverde
Created November 14, 2017 21:08
Show Gist options
  • Save glandaverde/5da5b31560f4c6f5abf6690fdbc2daf1 to your computer and use it in GitHub Desktop.
Save glandaverde/5da5b31560f4c6f5abf6690fdbc2daf1 to your computer and use it in GitHub Desktop.
Guess Game (Rust)
use rand::Rng;
use std::io;
use std::cmp::Ordering;
//Main code
fn main() {
// Generate random number, create premise
println!("Guess the number!");
let mut breaking_choice = false;
while !breaking_choice {
let secret_number = rand::thread_rng().gen_range(1, 101);
// **Problem area**
loop {
println!("Please input a (number) guess");
println!("1"); // [**REFERENCE 1**]
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
println!("2"); // [**REFERENCE 2**]
let guess: u32 = match guess.trim().parse() { // [FIGURE 3]
Ok(num) => num, // [FIGURE 3]
Err(_) => continue, // [FIGURE 3]
};
// ...until correct
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small"),
Ordering::Greater => println!("Too big"),
Ordering::Equal => {
println!("Correct!");
break;
}
}
}
// **Possible problem area**
println!("Would you like to continue playing? Y or N");
let choice: String = read!();
if choice == "N" {
breaking_choice = true
} else if choice == "n" {
breaking_choice = true
} else if choice == "Y" {
continue;
} else if choice == "y" {
continue;
}
}
}
@glandaverde
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment