2024-10-11 21:51:51 +00:00
|
|
|
use rand::Rng;
|
2024-10-11 22:17:30 +00:00
|
|
|
use std::cmp::Ordering;
|
|
|
|
use std::io;
|
2024-10-11 21:07:22 +00:00
|
|
|
|
2025-03-02 22:50:58 +00:00
|
|
|
pub struct Guess {
|
|
|
|
value: i32,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Guess {
|
|
|
|
pub fn new(value: i32) -> Guess {
|
|
|
|
if value < 1 || value > 100 {
|
|
|
|
panic!("Guess value must be between 1 and 100, got {value}.");
|
|
|
|
}
|
|
|
|
|
|
|
|
Guess { value }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-10-11 21:07:22 +00:00
|
|
|
fn main() {
|
|
|
|
println!("Guess the number!");
|
2024-10-11 21:51:51 +00:00
|
|
|
let secret_number = rand::thread_rng().gen_range(1..=100);
|
|
|
|
println!("The secret number is: {secret_number}");
|
2024-10-11 21:07:22 +00:00
|
|
|
|
2024-10-11 22:21:54 +00:00
|
|
|
loop {
|
|
|
|
println!("Please input your guess.");
|
|
|
|
|
|
|
|
let mut guess = String::new();
|
|
|
|
|
|
|
|
io::stdin()
|
|
|
|
.read_line(&mut guess)
|
|
|
|
.expect("Failed to read line");
|
|
|
|
|
2025-03-02 22:50:58 +00:00
|
|
|
let guess: Guess = match guess.trim().parse() {
|
|
|
|
Ok(num) => Guess::new(num),
|
2024-10-11 22:29:01 +00:00
|
|
|
Err(_) => {
|
|
|
|
println!("Please type a number!");
|
|
|
|
continue;
|
|
|
|
},
|
|
|
|
};
|
|
|
|
|
2025-03-02 22:50:58 +00:00
|
|
|
println!("You guessed: {}", guess.value);
|
2024-10-11 22:21:54 +00:00
|
|
|
|
2025-03-02 22:50:58 +00:00
|
|
|
match guess.value.cmp(&secret_number) {
|
2024-10-11 22:21:54 +00:00
|
|
|
Ordering::Less => println!("Too small!"),
|
|
|
|
Ordering::Greater => println!("Too big!"),
|
2024-10-11 22:22:11 +00:00
|
|
|
Ordering::Equal => {
|
|
|
|
println!("You win!");
|
|
|
|
break;
|
|
|
|
},
|
2024-10-11 22:21:54 +00:00
|
|
|
}
|
2024-10-11 22:17:30 +00:00
|
|
|
}
|
2024-10-11 21:07:22 +00:00
|
|
|
}
|
2025-03-02 22:50:58 +00:00
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
#[should_panic]
|
|
|
|
fn greater_than_100() {
|
|
|
|
Guess::new(200);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|