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
use crate::Play;
use rand::Rng;
use std::io::{stdin, stdout, Write};
pub struct GuessTheNumber;
impl Play for GuessTheNumber {
fn name(&self) -> &'static str {
"Guess the Number"
}
fn start(&mut self) {
let mut rng = rand::thread_rng();
let min = 0;
let max = 100;
let random_number = rng.gen_range(min..=max);
for i in (0..7).rev() {
print!(
"Guesses left: {}\nBetween {} and {}, inclusive\nYou Choose: ",
i + 1,
min,
max
);
stdout().flush().expect("Failed to flush");
let mut input = String::new();
stdin().read_line(&mut input).expect("Failed to read input");
let input = input.trim();
if input == "" {
continue;
}
let input: u8 = match input.parse() {
Ok(val) => val,
Err(_) => continue,
};
if input < random_number {
println!("Too low!\n");
} else if input > random_number {
println!("Too high!\n");
} else {
println!("You win!\n");
break;
}
}
println!("You lose!\nThe number was {random_number}\n");
}
}