-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcool-improved-guessing-game.rs
75 lines (61 loc) · 1.93 KB
/
cool-improved-guessing-game.rs
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
use rand::Rng;
use std::cmp::Ordering;
use std::io;
use std::io::prelude::*;
fn main() {
println!("=====================================");
println!("***********Guess the number**********");
println!("=====================================");
print!("Enter least number for guessing game: ");
io::stdout().flush().ok().expect("Could not flush stdout");
// let min: u32 = read_user_input2();
let min = match read_user_input() {
Ok(num) => num,
Err(_) => 0,
};
print!("Enter maximum number for guessing game: ");
io::stdout().flush().ok().expect("Could not flush stdout");
let max: u32 = match read_user_input() {
Ok(num) => num,
Err(_) => 100,
};
if min > max {
println!("Min cannot be greater than max!");
std::process::exit(1);
}
println!(
"Thank you. You will not be asked to guess a number between {} and {}",
min, max
);
let secret_number = rand::thread_rng().gen_range(min, max);
println!("{}", secret_number);
// keep track of number of guess
let mut guess_count = 0;
loop {
println!("Please input your guess.");
let guess: u32 = match read_user_input() {
Ok(num) => num,
Err(_) => continue,
};
println!("You guessed: {}", guess);
match guess.cmp(&secret_number) {
Ordering::Less => {
println!("Too small!");
guess_count += 1;
}
Ordering::Greater => {
println!("Too big!");
guess_count += 1;
}
Ordering::Equal => {
println!("You win! after {} wrong guess.", guess_count);
break;
}
}
}
}
fn read_user_input() -> Result<u32, std::num::ParseIntError> {
let mut s = String::new();
io::stdin().read_line(&mut s).expect("Failed to read line");
s.trim().parse()
}