Skip to content

Instantly share code, notes, and snippets.

@jrop
Created August 7, 2018 15:24
Show Gist options
  • Save jrop/a29b5cf0daaa4f6c11ce47f416364029 to your computer and use it in GitHub Desktop.
Save jrop/a29b5cf0daaa4f6c11ce47f416364029 to your computer and use it in GitHub Desktop.
Rust: Number Guesser
extern crate rand;
use rand::Rng;
use std::cmp::Ordering;
use std::io::prelude::*;
enum GameResult {
WON,
LOST,
}
fn main() {
let mut tries = 0;
let mut game_result = GameResult::LOST;
let secret_number = rand::thread_rng().gen_range(1, 101);
loop {
if tries >= 10 {
break;
}
print!("Guess the number ({} tries left): ", 10 - tries);
std::io::stdout().flush().expect("I/O error");
let mut guess = String::new();
std::io::stdin().read_line(&mut guess).expect("I/O error");
let guess: usize = match guess.trim().parse() {
Ok(n) => n,
Err(_) => {
println!("Please type a number!");
continue;
}
};
match guess.cmp(&secret_number) {
Ordering::Less => println!("{}: too _small_", guess),
Ordering::Greater => println!("{}: too BIG", guess),
Ordering::Equal => {
game_result = GameResult::WON;
break;
}
};
tries += 1
}
match game_result {
GameResult::WON => println!("You won!"),
GameResult::LOST => println!("You lost :( [the answer was {}]", secret_number),
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment