console_games/games/
guess_the_word.rs1use console::{style, Term};
2
3use crate::{util::get_char_input, Play};
4use std::{
5 collections::BTreeSet,
6 io::{stdout, Write},
7};
8
9pub struct GuessTheWord;
10
11impl Play for GuessTheWord {
12 fn start(&self) {
13 let word = eff_wordlist::large::random_word();
14 let mut unique_chars = BTreeSet::from_iter(word.chars());
15 unique_chars.remove(&' ');
16 let mut guessed_chars: Vec<char> = Vec::with_capacity(26);
17 let mut guess_left = 10;
18
19 let alphabets: [char; 26] = [
20 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
21 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
22 ];
23
24 let term = Term::stdout();
25 term.clear_screen().expect("Failed to clear screen");
26
27 loop {
28 for c in word.chars() {
30 if guessed_chars.contains(&c) || c == ' ' {
31 print!("{c}");
32 } else {
33 print!("_")
34 }
35 }
36 println!("\nGuesses left: {}", style(guess_left).red());
37 print!("From ");
38 for c in alphabets {
39 if guessed_chars.contains(&c) {
40 print!("_")
41 } else {
42 print!("{c}");
43 }
44 print!(" ");
45 }
46 println!();
47 print!("You pick: ");
48 stdout().flush().expect("Failed to flush");
49
50 let input = get_char_input();
51 if input.is_none() {
53 term.clear_screen().expect("Failed to clear screen");
54 continue;
55 }
56 let input = input.unwrap();
57
58 if guessed_chars.contains(&input) {
59 term.clear_screen().expect("Failed to clear screen");
60 println!("You have entered a guessed character\n");
61 continue;
62 }
63
64 guessed_chars.push(input);
65 if unique_chars.contains(&input) {
66 unique_chars.remove(&input);
67 } else {
68 guess_left -= 1;
69 }
70
71 if unique_chars.is_empty() {
73 println!("You win!\nThe word is: {word}\n");
74 break;
75 }
76 if guess_left == 0 {
77 println!("You lose!\nThe word is: {word}\n");
78 break;
79 }
80
81 println!();
82 term.clear_screen().expect("Failed to clear screen");
83 }
84 }
85
86 fn name(&self) -> &'static str {
87 "Guess the Word"
88 }
89}