Created
January 28, 2020 15:39
-
-
Save robrobbins/d102e1050c509a84cca02f749804ba0a to your computer and use it in GitHub Desktop.
Rust guessing game
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::{thread_rng, Rng}; | |
use std::cmp::Ordering; | |
use std::io; | |
fn main() { | |
let secret = get_secret(); | |
let mut guesses = 1; | |
loop { | |
let guess = get_guess(&guesses); | |
display_guess(&guess); | |
let guessed = display_result(&secret, &guess, &guesses); | |
if guessed { | |
break; | |
} | |
guesses += 1; | |
} | |
} | |
fn get_secret() -> u32 { | |
println!("Generating a secret number between 1 and 100."); | |
thread_rng().gen_range(1, 101) | |
} | |
fn get_guess(guesses: &u32) -> u32 { | |
let one: u32 = 1; | |
if guesses == &one { | |
println!("Try to guess that number:"); | |
} else { | |
println!("Try again..."); | |
} | |
let mut guessed = String::new(); | |
io::stdin() | |
.read_line(&mut guessed) | |
.expect("Failed to read line"); | |
parse_guess(&guessed) | |
} | |
fn parse_guess(guessed: &String) -> u32 { | |
guessed.trim().parse().expect("Input a Number please...") | |
} | |
fn display_guess(guess: &u32) { | |
println!("You guessed: {}", guess); | |
} | |
fn display_result(secret: &u32, guess: &u32, guesses: &u32) -> bool { | |
println!("Comparing your guess to the secret number"); | |
match guess.cmp(secret) { | |
Ordering::Less => println!("Too low, maybe guessing just isn't your thing."), | |
Ordering::Greater => println!("Too high, you are really bad at this."), | |
Ordering::Equal => { | |
println!("DING! You win on guess #{}! Huzzah! Your father is finally proud of you.", guesses); | |
return true; | |
} | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment