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
use crate::Play;
use console::Term;
use rand::Rng;
use std::{
cmp::Ordering,
io::{stdin, stdout, Write},
};
pub struct GuessTheNumber;
impl Play for GuessTheNumber {
fn name(&self) -> &'static str {
"Guess the Number"
}
fn start(&self) {
let mut rng = rand::thread_rng();
let min = 0;
let max = 100;
let random_number = rng.gen_range(min..=max);
let term = Term::stdout();
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.is_empty() {
continue;
}
let input: u8 = match input.parse() {
Ok(val) => val,
Err(_) => continue,
};
term.clear_screen().expect("Failed to clear screen");
match input.cmp(&random_number) {
Ordering::Less => println!("{input}, Too low!\n"),
Ordering::Greater => println!("{input}, Too high!\n"),
Ordering::Equal => {
println!("You win!\n");
break;
}
}
}
println!("You lose!\nThe number was {random_number}\n");
}
}