Rust implementation of the animal guessing game, where the computer learns about animals and then guesses them with yes/no answers.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
animals.rs/src/cli_user.rs

76 lines
1.8 KiB

use crate::animals;
use crate::prompt;
pub struct CliUser<'a> {
db: &'a animals::AnimalDB,
}
impl<'a> CliUser<'a> {
pub fn new(db: &'a animals::AnimalDB) -> Self {
CliUser { db }
}
fn abort(&self) -> ! {
println!("Exit.");
std::process::exit(1);
}
}
impl<'a> animals::UserAPI for CliUser<'_> {
fn notify_new_game(&self) {
println!("----- NEW GAME -----");
}
fn notify_game_ended(&self) {
println!("Game ended.\n");
}
fn notify_new_animal(&self, animal: &str) {
println!("Learned a new animal: {}", animal);
self.db.save("animals.txt").unwrap();
}
fn notify_victory(&self) {
println!("Yay, found an answer! Thanks for playing.");
}
fn answer_yes_no(&self, question: &str) -> bool {
println!("{}", question);
match prompt::ask_yn("> ") {
None => self.abort(),
Some(b) => b,
}
}
fn is_it_a(&self, animal: &str) -> bool {
println!("Is it a {}?", animal);
match prompt::ask_yn("> ") {
None => self.abort(),
Some(b) => b,
}
}
fn what_is_it(&self) -> String {
println!("What animal is it?");
match prompt::ask("> ") {
None => self.abort(),
Some(s) => s,
}
}
fn how_to_tell_apart(&self, secret: &str, other: &str) -> (String, bool) {
println!("How to tell apart {} and {}?", secret, other);
let q: String = match prompt::ask("> ") {
None => self.abort(),
Some(s) => s,
};
println!("What is the answer for {}?", secret);
let b: bool = match prompt::ask_yn("> ") {
None => self.abort(),
Some(b) => b,
};
(q, b)
}
}