// 7 Boom game. The user enters a number he wants to start the game,
// (-1 to end the game, or lost), then the user enters numbers, from the number he entered
// If the current number is divisible by 7, or one of its digits is 7,
// And the user did not write the word 'Boom', the user loses.
use std::io::{self, Write};
fn contains_seven(num: i32) -> bool {
num.to_string().contains('7')
}
fn is_boom(num: i32) -> bool {
num % 7 == 0 || contains_seven(num)
}
fn get_user_input(prompt: &str) -> String {
print!("{}", prompt);
io::stdout().flush().unwrap();
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
input.trim().to_string()
}
fn process_turn(expected: i32, input: &str) -> bool {
let lower = input.to_lowercase();
let should_boom = is_boom(expected);
if should_boom {
if lower != "boom" {
println!("{} (should be Boom)", input);
println!("YOU LOSE!");
return false;
}
} else {
if lower == "boom" {
println!("Wrong move! It was {}", expected);
println!("YOU LOSE!");
return false;
}
match input.parse::<i32>() {
Ok(value) if value == expected => {}
_ => {
println!("Wrong move! It was {}", expected);
println!("YOU LOSE!");
return false;
}
}
}
true
}
fn run_game() {
let start_input = get_user_input("Enter a number from which you want to start the game (-1 to exit): ");
println!();
let mut current = match start_input.parse::<i32>() {
Ok(n) => n,
Err(_) => return,
};
if current == -1 {
return;
}
loop {
let input = get_user_input("Enter a number (or Boom): ");
println!();
if input == "-1" {
println!("Game Over!");
break;
}
if !process_turn(current, &input) {
break;
}
current += 1;
}
}
fn main() {
run_game();
}
/*
run:
Enter a number from which you want to start the game (-1 to exit): 6
Enter a number (or Boom): 6
Enter a number (or Boom): Boom
Enter a number (or Boom): 8
Enter a number (or Boom): 9
Enter a number (or Boom): 10
Enter a number (or Boom): 11
Enter a number (or Boom): 12
Enter a number (or Boom): 13
Enter a number (or Boom): Boom
Enter a number (or Boom): 15
Enter a number (or Boom): 16
Enter a number (or Boom): Boom
Enter a number (or Boom): 18
Enter a number (or Boom): 19
Enter a number (or Boom): 20
Enter a number (or Boom): 21
21 (should be Boom)
YOU LOSE!
*/