-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.rs
More file actions
60 lines (52 loc) · 1.8 KB
/
main.rs
File metadata and controls
60 lines (52 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
use rand::Rng;
use std::cmp::Ordering;
use std::io::Write; //used for the random number generation
fn get_input(prompt: &str) -> String {
let mut input = String::new();
print!("{}: ", prompt);
std::io::stdout()
.flush()
.expect("could not flush output buffer"); // flush the output to make sure the line is seen
std::io::stdin()
.read_line(&mut input)
.expect("Could not read input");
input
}
fn get_guess() -> i32 {
let guess: String = get_input("Guess a number");
guess
.trim()
.parse()
.expect("Could not derive a number from guess")
}
fn compare_guess(guess: i32, actual: i32) -> bool {
let mut guessed_correctly = false;
// compare the user's guess to the secret number
match guess.cmp(&actual) {
Ordering::Less => {
println!("Your guess was too small")
}
Ordering::Equal => {
println!("You got it right!");
guessed_correctly = true;
}
Ordering::Greater => {
println!("Your guess was too big")
}
};
guessed_correctly // a boolean on if the guess was right or not
}
fn main() {
const MIN: i32 = 1;
const MAX: i32 = 100;
println!("Can you guess the secret Number??? ({}-{})", MIN, MAX);
let secret_number: i32 = rand::thread_rng().gen_range(MIN, MAX); // randomly create a secret number
let mut user_guess = secret_number + 1; //intentionally mismatch the secret number from the guess
let mut num_guesses = 0; //count how many guesses the user has made
while user_guess != secret_number {
user_guess = get_guess(); // Get the guess from the user
compare_guess(user_guess, secret_number);
num_guesses += 1;
}
println!("You won the game after {} guesses", num_guesses);
}