Решение на Wordle от Климент Бербатов

Обратно към всички решения

Към профила на Климент Бербатов

Резултати

  • 20 точки от тестове
  • 0 бонус точки
  • 20 точки общо
  • 15 успешни тест(а)
  • 0 неуспешни тест(а)

Код

#[derive(Debug, PartialEq, Clone)]
pub enum GameStatus {
InProgress,
Won,
Lost,
}
#[derive(Debug)]
pub enum GameError {
NotInAlphabet(char),
WrongLength { expected: usize, actual: usize },
GameIsOver(GameStatus),
}
#[derive(Debug, Clone)]
pub struct Game {
pub status: GameStatus,
pub attempts: u8,
pub goal_word: String,
pub alphabet: Vec<char>,
pub word_attempts: Vec<Word>,
// Каквито други полета ви трябват
}
#[derive(Debug, Clone)]
pub struct Word {
pub info: Vec<Letter>,
// Каквито полета ви трябват
}
#[derive(Debug, Clone)]
pub enum Letter {
FullMatch(char),
PartialMatch(char),
NoMatch(char),
}
impl Game {
/// Конструира нова игра с думи/букви от дадената в `alphabet` азбука. Alphabet е просто низ,
/// в който всеки символ е отделна буква, който вероятно искате да си запазите някак за после.
///
/// Подадената дума с `word` трябва да има само букви от тази азбука. Иначе очакваме да върнете
/// `GameError::NotInAlphabet` грешка с първия символ в `word`, който не е от азбуката.
///
/// Началното състояние на играта е `InProgress` а началния брой опити `attempts` е 0.
///
pub fn new(alphabet: &str, word: &str) -> Result<Self, GameError> {
let chars: Vec<char> = alphabet.chars().collect();
let flag = word.chars().find(|&x| !chars.iter().any(|&y| y == x));
if let Some(x) = flag {
println!("{}", x);
Err(GameError::NotInAlphabet(x))
} else {
Ok(Game {
status: GameStatus::InProgress,
attempts: 0,
goal_word: word.to_string(),
alphabet: chars,
word_attempts: vec![],
})
}
}
/// Опитва се да познае търсената дума. Опита е в `guess`.
///
/// Ако играта е приключила, тоест статуса ѝ е `Won` или `Lost`, очакваме да върнете
/// `GameIsOver` със статуса, с който е приключила.
///
/// Ако `guess` има различен брой букви от търсената дума, очакваме да върнете
/// `GameError::WrongLength`. Полето `expected` на грешката трябва да съдържа броя букви на
/// търсената дума, а `actual` да е броя букви на опита `guess`.
///
/// Ако `guess` има правилния брой букви, но има буква, която не е от азбуката на играта,
/// очакваме `GameError::NotInAlphabet` както по-горе, с първия символ от `guess`, който не е
/// от азбуката.
///
/// Метода приема `&mut self`, защото всеки валиден опит (такъв, който не връща грешка) се
/// запазва в играта за по-нататък. Метода връща `Word`, което описва освен самите символи на
/// `guess`, и как тези символи са се напаснали на търсената дума. Също така инкрементира
/// `attempts` с 1.
///
/// След опита за напасване на думата, ако всички букви са уцелени на правилните места,
/// очакваме `state` полето да се промени на `Won`. Иначе, ако `attempts` са станали 5,
/// състоянието трябва да е `Lost`.
///
pub fn guess_word(&mut self, guess: &str) -> Result<Word, GameError> {
if self.status == GameStatus::Won || self.status == GameStatus::Lost {
//if game is over return status
return Err(GameError::GameIsOver(self.status.clone()));
}
let guess_len = guess.chars().count();
let goal_len = self.goal_word.chars().count();
if guess_len != goal_len {
//if guess length is different from word length return wrong length error
return Err(GameError::WrongLength {
expected: goal_len,
actual: guess_len,
});
}
let flag = guess
.chars()
.find(|&x| !self.alphabet.iter().any(|&y| y == x));
if let Some(x) = flag {
//if guess has a character not in the alphabet return error not in alphabet
println!("{}", x);
return Err(GameError::NotInAlphabet(x));
}
let info_about_letters = guess
.chars()
.enumerate()
.map(|(i, c)| {
let f = self
.goal_word
.chars()
.enumerate()
.map(|(_j, w)| w == c)
.collect::<Vec<bool>>(); //get a vector of bools for each character in guess where f[i] tells us if character c matches the i-th
//char of the guess word
if i < f.len() && f[i] {
// if true at the same position -> full match
return Letter::FullMatch(c);
} else if f.iter().any(|x| *x) { // if true somewhere -> partial match
return Letter::PartialMatch(c);
}
return Letter::NoMatch(c); //otherwise no match
})
.collect::<Vec<Letter>>(); //get info about each character in guess - whether it is in the word and on correct possition
let try_accuracy = info_about_letters
.iter()
.all(|x| matches!(x, Letter::FullMatch(_)));
if try_accuracy {
//if we've hit all the letters, then the game is over
self.status = GameStatus::Won;
self.attempts = self.attempts + 1;
self.word_attempts.push(Word {
info: info_about_letters.clone(),
});
return Ok(Word {
info: info_about_letters.clone(),
});
}
self.attempts = self.attempts + 1;
self.word_attempts.push(Word {
info: info_about_letters.clone(),
});
if self.attempts == 5 {
//if this is the 5th attempt, then the game is over
self.status = GameStatus::Lost;
self.word_attempts.push(Word {
info: info_about_letters.clone(),
});
return Ok(Word {
info: info_about_letters.clone(),
});
}
Ok(Word {
info: info_about_letters.clone(),
})
}
}
use std::fmt;
impl fmt::Display for Word {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let res: String = self
.info
.iter()
.map(|c| match *c {
Letter::FullMatch(t) => format!("[{}]", t.to_uppercase()),
Letter::PartialMatch(t) => format!("({})", t.to_uppercase()),
Letter::NoMatch(t) => format!(">{}<", t.to_uppercase()),
})
.collect();
write!(f, "{}", res)
}
}
impl fmt::Display for Game {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", "|_|".repeat(self.goal_word.chars().count()))?;
let res: String = self
.word_attempts
.iter()
.map(|x| format!("\n{}", x))
.collect();
write!(f, "{}", res)
}
}

Лог от изпълнението

Compiling solution v0.1.0 (/tmp/d20230111-3772066-14m1rb5/solution)
    Finished test [unoptimized + debuginfo] target(s) in 0.82s
     Running tests/solution_test.rs (target/debug/deps/solution_test-0edbea2040daef01)

running 15 tests
test solution_test::test_game_display ... ok
test solution_test::test_game_display_cyrillic ... ok
test solution_test::test_game_display_german ... ok
test solution_test::test_game_state_1 ... ok
test solution_test::test_game_state_2 ... ok
test solution_test::test_game_state_3 ... ok
test solution_test::test_word_display ... ok
test solution_test::test_word_display_bulgarian ... ok
test solution_test::test_word_display_german ... ok
test solution_test::test_word_display_with_repetitions ... ok
test solution_test::test_word_not_in_alphabet_on_construction ... ok
test solution_test::test_word_not_in_alphabet_on_construction_cyrrilic ... ok
test solution_test::test_word_not_in_alphabet_on_guess ... ok
test solution_test::test_word_not_in_alphabet_on_guess_cyrillic ... ok
test solution_test::test_wrong_length ... ok

test result: ok. 15 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

История (4 версии и 0 коментара)

Климент качи първо решение на 22.11.2022 20:13 (преди почти 3 години)

Климент качи решение на 22.11.2022 20:28 (преди почти 3 години)

#[derive(Debug, PartialEq, Clone)]
pub enum GameStatus {
InProgress,
Won,
Lost,
}
#[derive(Debug)]
pub enum GameError {
NotInAlphabet(char),
WrongLength { expected: usize, actual: usize },
GameIsOver(GameStatus),
}
#[derive(Debug, Clone)]
pub struct Game {
pub status: GameStatus,
pub attempts: u8,
pub goal_word: String,
pub alphabet: Vec<char>,
pub word_attempts: Vec<Word>,
// Каквито други полета ви трябват
}
#[derive(Debug, Clone)]
pub struct Word {
pub info: Vec<Letter>,
// Каквито полета ви трябват
}
#[derive(Debug, Clone)]
pub enum Letter {
FullMatch(char),
PartialMatch(char),
NoMatch(char),
}
impl Game {
/// Конструира нова игра с думи/букви от дадената в `alphabet` азбука. Alphabet е просто низ,
/// в който всеки символ е отделна буква, който вероятно искате да си запазите някак за после.
///
/// Подадената дума с `word` трябва да има само букви от тази азбука. Иначе очакваме да върнете
/// `GameError::NotInAlphabet` грешка с първия символ в `word`, който не е от азбуката.
///
/// Началното състояние на играта е `InProgress` а началния брой опити `attempts` е 0.
///
pub fn new(alphabet: &str, word: &str) -> Result<Self, GameError> {
let chars: Vec<char> = alphabet.chars().collect();
let flag = word.chars().find(|&x| !chars.iter().any(|&y| y == x));
if let Some(x) = flag {
println!("{}", x);
Err(GameError::NotInAlphabet(x))
} else {
Ok(Game {
status: GameStatus::InProgress,
attempts: 0,
goal_word: word.to_string(),
alphabet: chars,
word_attempts: vec![],
})
}
}
/// Опитва се да познае търсената дума. Опита е в `guess`.
///
/// Ако играта е приключила, тоест статуса ѝ е `Won` или `Lost`, очакваме да върнете
/// `GameIsOver` със статуса, с който е приключила.
///
/// Ако `guess` има различен брой букви от търсената дума, очакваме да върнете
/// `GameError::WrongLength`. Полето `expected` на грешката трябва да съдържа броя букви на
/// търсената дума, а `actual` да е броя букви на опита `guess`.
///
/// Ако `guess` има правилния брой букви, но има буква, която не е от азбуката на играта,
/// очакваме `GameError::NotInAlphabet` както по-горе, с първия символ от `guess`, който не е
/// от азбуката.
///
/// Метода приема `&mut self`, защото всеки валиден опит (такъв, който не връща грешка) се
/// запазва в играта за по-нататък. Метода връща `Word`, което описва освен самите символи на
/// `guess`, и как тези символи са се напаснали на търсената дума. Също така инкрементира
/// `attempts` с 1.
///
/// След опита за напасване на думата, ако всички букви са уцелени на правилните места,
/// очакваме `state` полето да се промени на `Won`. Иначе, ако `attempts` са станали 5,
/// състоянието трябва да е `Lost`.
///
pub fn guess_word(&mut self, guess: &str) -> Result<Word, GameError> {
- if self.status == GameStatus::Won || self.status == GameStatus::Lost {
+ if self.status == GameStatus::Won || self.status == GameStatus::Lost { //if game is over return status
return Err(GameError::GameIsOver(self.status.clone()));
}
let guess_len = guess.chars().count();
let goal_len = self.goal_word.chars().count();
- if guess_len != goal_len {
+ if guess_len != goal_len { //if guess length is different from word length return wrong length error
return Err(GameError::WrongLength {
expected: goal_len,
actual: guess_len,
});
}
let flag = guess
.chars()
.find(|&x| !self.alphabet.iter().any(|&y| y == x));
- if let Some(x) = flag {
+ if let Some(x) = flag { //if guess has a character not in the alphabet return error not in alphabet
println!("{}", x);
return Err(GameError::NotInAlphabet(x));
}
let info_about_letters = guess
.chars()
.enumerate()
.map(|(i, c)| {
let f = self.goal_word.chars().enumerate().find(|(_j, w)| *w == c);
match f {
Some((k, _)) => {
if k == i {
Letter::FullMatch(c)
} else {
Letter::PartialMatch(c)
}
}
_ => Letter::NoMatch(c),
}
})
- .collect::<Vec<Letter>>();
+ .collect::<Vec<Letter>>(); //get info about each character in guess - whether it is in the word and on correct possition
let try_accuracy = info_about_letters
.iter()
.all(|x| matches!(x, Letter::FullMatch(_)));
if try_accuracy {
//if we've hit all the letters, then the game is over
self.status = GameStatus::Won;
self.attempts = self.attempts + 1;
self.word_attempts.push(Word {
info: info_about_letters.clone(),
});
return Ok(Word {
info: info_about_letters.clone(),
});
}
self.attempts = self.attempts + 1;
self.word_attempts.push(Word {
info: info_about_letters.clone(),
});
if self.attempts == 5 {
//if this is the 5th attempt, then the game is over
self.status = GameStatus::Lost;
self.word_attempts.push(Word {
info: info_about_letters.clone(),
});
return Ok(Word {
info: info_about_letters.clone(),
});
}
Ok(Word {
info: info_about_letters.clone(),
})
}
}
use std::fmt;
impl fmt::Display for Word {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let res: String = self
.info
.iter()
.map(|c| match *c {
Letter::FullMatch(t) => format!("[{}]", t.to_uppercase()),
Letter::PartialMatch(t) => format!("({})", t.to_uppercase()),
Letter::NoMatch(t) => format!(">{}<", t.to_uppercase()),
})
.collect();
write!(f, "{}", res)
}
}
impl fmt::Display for Game {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", "|_|".repeat(self.goal_word.chars().count()))?;
- // let iter = self.word_attempts.iter();
- // while let Some(x) = iter.next(){
- // write!(f,"\n{}")
- // }
let res: String = self
.word_attempts
.iter()
.map(|x| format!("\n{}", x))
.collect();
write!(f, "{}", res)
}
}

Климент качи решение на 22.11.2022 21:11 (преди почти 3 години)

#[derive(Debug, PartialEq, Clone)]
pub enum GameStatus {
InProgress,
Won,
Lost,
}
#[derive(Debug)]
pub enum GameError {
NotInAlphabet(char),
WrongLength { expected: usize, actual: usize },
GameIsOver(GameStatus),
}
#[derive(Debug, Clone)]
pub struct Game {
pub status: GameStatus,
pub attempts: u8,
pub goal_word: String,
pub alphabet: Vec<char>,
pub word_attempts: Vec<Word>,
// Каквито други полета ви трябват
}
#[derive(Debug, Clone)]
pub struct Word {
pub info: Vec<Letter>,
// Каквито полета ви трябват
}
#[derive(Debug, Clone)]
pub enum Letter {
FullMatch(char),
PartialMatch(char),
NoMatch(char),
}
impl Game {
/// Конструира нова игра с думи/букви от дадената в `alphabet` азбука. Alphabet е просто низ,
/// в който всеки символ е отделна буква, който вероятно искате да си запазите някак за после.
///
/// Подадената дума с `word` трябва да има само букви от тази азбука. Иначе очакваме да върнете
/// `GameError::NotInAlphabet` грешка с първия символ в `word`, който не е от азбуката.
///
/// Началното състояние на играта е `InProgress` а началния брой опити `attempts` е 0.
///
pub fn new(alphabet: &str, word: &str) -> Result<Self, GameError> {
let chars: Vec<char> = alphabet.chars().collect();
let flag = word.chars().find(|&x| !chars.iter().any(|&y| y == x));
if let Some(x) = flag {
println!("{}", x);
Err(GameError::NotInAlphabet(x))
} else {
Ok(Game {
status: GameStatus::InProgress,
attempts: 0,
goal_word: word.to_string(),
alphabet: chars,
word_attempts: vec![],
})
}
}
/// Опитва се да познае търсената дума. Опита е в `guess`.
///
/// Ако играта е приключила, тоест статуса ѝ е `Won` или `Lost`, очакваме да върнете
/// `GameIsOver` със статуса, с който е приключила.
///
/// Ако `guess` има различен брой букви от търсената дума, очакваме да върнете
/// `GameError::WrongLength`. Полето `expected` на грешката трябва да съдържа броя букви на
/// търсената дума, а `actual` да е броя букви на опита `guess`.
///
/// Ако `guess` има правилния брой букви, но има буква, която не е от азбуката на играта,
/// очакваме `GameError::NotInAlphabet` както по-горе, с първия символ от `guess`, който не е
/// от азбуката.
///
/// Метода приема `&mut self`, защото всеки валиден опит (такъв, който не връща грешка) се
/// запазва в играта за по-нататък. Метода връща `Word`, което описва освен самите символи на
/// `guess`, и как тези символи са се напаснали на търсената дума. Също така инкрементира
/// `attempts` с 1.
///
/// След опита за напасване на думата, ако всички букви са уцелени на правилните места,
/// очакваме `state` полето да се промени на `Won`. Иначе, ако `attempts` са станали 5,
/// състоянието трябва да е `Lost`.
///
pub fn guess_word(&mut self, guess: &str) -> Result<Word, GameError> {
- if self.status == GameStatus::Won || self.status == GameStatus::Lost { //if game is over return status
+ if self.status == GameStatus::Won || self.status == GameStatus::Lost {
+ //if game is over return status
return Err(GameError::GameIsOver(self.status.clone()));
}
let guess_len = guess.chars().count();
let goal_len = self.goal_word.chars().count();
- if guess_len != goal_len { //if guess length is different from word length return wrong length error
+ if guess_len != goal_len {
+ //if guess length is different from word length return wrong length error
return Err(GameError::WrongLength {
expected: goal_len,
actual: guess_len,
});
}
let flag = guess
.chars()
.find(|&x| !self.alphabet.iter().any(|&y| y == x));
- if let Some(x) = flag { //if guess has a character not in the alphabet return error not in alphabet
+ if let Some(x) = flag {
+ //if guess has a character not in the alphabet return error not in alphabet
println!("{}", x);
return Err(GameError::NotInAlphabet(x));
}
let info_about_letters = guess
.chars()
.enumerate()
.map(|(i, c)| {
- let f = self.goal_word.chars().enumerate().find(|(_j, w)| *w == c);
- match f {
- Some((k, _)) => {
- if k == i {
- Letter::FullMatch(c)
- } else {
- Letter::PartialMatch(c)
- }
- }
- _ => Letter::NoMatch(c),
+ let f = self
+ .goal_word
+ .chars()
+ .enumerate()
+ .map(|(_j, w)| w == c)
+ .collect::<Vec<bool>>(); //get a vector of bools for each character in guess
+ if i < f.len() && f[i] {
+ // if true at the same position -> full match
+ return Letter::FullMatch(c);
+ } else if f.iter().any(|x| *x) { // if true somewhere -> partial match
+ return Letter::PartialMatch(c);
}
+ return Letter::NoMatch(c); //otherwise no match
})
- .collect::<Vec<Letter>>(); //get info about each character in guess - whether it is in the word and on correct possition
+ .collect::<Vec<Letter>>(); //get info about each character in guess - whether it is in the word and on correct possition
let try_accuracy = info_about_letters
.iter()
.all(|x| matches!(x, Letter::FullMatch(_)));
if try_accuracy {
//if we've hit all the letters, then the game is over
self.status = GameStatus::Won;
self.attempts = self.attempts + 1;
self.word_attempts.push(Word {
info: info_about_letters.clone(),
});
return Ok(Word {
info: info_about_letters.clone(),
});
}
self.attempts = self.attempts + 1;
self.word_attempts.push(Word {
info: info_about_letters.clone(),
});
if self.attempts == 5 {
//if this is the 5th attempt, then the game is over
self.status = GameStatus::Lost;
self.word_attempts.push(Word {
info: info_about_letters.clone(),
});
return Ok(Word {
info: info_about_letters.clone(),
});
}
Ok(Word {
info: info_about_letters.clone(),
})
}
}
use std::fmt;
impl fmt::Display for Word {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let res: String = self
.info
.iter()
.map(|c| match *c {
Letter::FullMatch(t) => format!("[{}]", t.to_uppercase()),
Letter::PartialMatch(t) => format!("({})", t.to_uppercase()),
Letter::NoMatch(t) => format!(">{}<", t.to_uppercase()),
})
.collect();
write!(f, "{}", res)
}
}
impl fmt::Display for Game {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", "|_|".repeat(self.goal_word.chars().count()))?;
let res: String = self
.word_attempts
.iter()
.map(|x| format!("\n{}", x))
.collect();
write!(f, "{}", res)
}
}

Климент качи решение на 22.11.2022 21:16 (преди почти 3 години)

#[derive(Debug, PartialEq, Clone)]
pub enum GameStatus {
InProgress,
Won,
Lost,
}
#[derive(Debug)]
pub enum GameError {
NotInAlphabet(char),
WrongLength { expected: usize, actual: usize },
GameIsOver(GameStatus),
}
#[derive(Debug, Clone)]
pub struct Game {
pub status: GameStatus,
pub attempts: u8,
pub goal_word: String,
pub alphabet: Vec<char>,
pub word_attempts: Vec<Word>,
// Каквито други полета ви трябват
}
#[derive(Debug, Clone)]
pub struct Word {
pub info: Vec<Letter>,
// Каквито полета ви трябват
}
#[derive(Debug, Clone)]
pub enum Letter {
FullMatch(char),
PartialMatch(char),
NoMatch(char),
}
impl Game {
/// Конструира нова игра с думи/букви от дадената в `alphabet` азбука. Alphabet е просто низ,
/// в който всеки символ е отделна буква, който вероятно искате да си запазите някак за после.
///
/// Подадената дума с `word` трябва да има само букви от тази азбука. Иначе очакваме да върнете
/// `GameError::NotInAlphabet` грешка с първия символ в `word`, който не е от азбуката.
///
/// Началното състояние на играта е `InProgress` а началния брой опити `attempts` е 0.
///
pub fn new(alphabet: &str, word: &str) -> Result<Self, GameError> {
let chars: Vec<char> = alphabet.chars().collect();
let flag = word.chars().find(|&x| !chars.iter().any(|&y| y == x));
if let Some(x) = flag {
println!("{}", x);
Err(GameError::NotInAlphabet(x))
} else {
Ok(Game {
status: GameStatus::InProgress,
attempts: 0,
goal_word: word.to_string(),
alphabet: chars,
word_attempts: vec![],
})
}
}
/// Опитва се да познае търсената дума. Опита е в `guess`.
///
/// Ако играта е приключила, тоест статуса ѝ е `Won` или `Lost`, очакваме да върнете
/// `GameIsOver` със статуса, с който е приключила.
///
/// Ако `guess` има различен брой букви от търсената дума, очакваме да върнете
/// `GameError::WrongLength`. Полето `expected` на грешката трябва да съдържа броя букви на
/// търсената дума, а `actual` да е броя букви на опита `guess`.
///
/// Ако `guess` има правилния брой букви, но има буква, която не е от азбуката на играта,
/// очакваме `GameError::NotInAlphabet` както по-горе, с първия символ от `guess`, който не е
/// от азбуката.
///
/// Метода приема `&mut self`, защото всеки валиден опит (такъв, който не връща грешка) се
/// запазва в играта за по-нататък. Метода връща `Word`, което описва освен самите символи на
/// `guess`, и как тези символи са се напаснали на търсената дума. Също така инкрементира
/// `attempts` с 1.
///
/// След опита за напасване на думата, ако всички букви са уцелени на правилните места,
/// очакваме `state` полето да се промени на `Won`. Иначе, ако `attempts` са станали 5,
/// състоянието трябва да е `Lost`.
///
pub fn guess_word(&mut self, guess: &str) -> Result<Word, GameError> {
if self.status == GameStatus::Won || self.status == GameStatus::Lost {
//if game is over return status
return Err(GameError::GameIsOver(self.status.clone()));
}
let guess_len = guess.chars().count();
let goal_len = self.goal_word.chars().count();
if guess_len != goal_len {
//if guess length is different from word length return wrong length error
return Err(GameError::WrongLength {
expected: goal_len,
actual: guess_len,
});
}
let flag = guess
.chars()
.find(|&x| !self.alphabet.iter().any(|&y| y == x));
if let Some(x) = flag {
//if guess has a character not in the alphabet return error not in alphabet
println!("{}", x);
return Err(GameError::NotInAlphabet(x));
}
let info_about_letters = guess
.chars()
.enumerate()
.map(|(i, c)| {
let f = self
.goal_word
.chars()
.enumerate()
.map(|(_j, w)| w == c)
- .collect::<Vec<bool>>(); //get a vector of bools for each character in guess
+ .collect::<Vec<bool>>(); //get a vector of bools for each character in guess where f[i] tells us if character c matches the i-th
+ //char of the guess word
if i < f.len() && f[i] {
// if true at the same position -> full match
return Letter::FullMatch(c);
} else if f.iter().any(|x| *x) { // if true somewhere -> partial match
return Letter::PartialMatch(c);
}
return Letter::NoMatch(c); //otherwise no match
})
.collect::<Vec<Letter>>(); //get info about each character in guess - whether it is in the word and on correct possition
let try_accuracy = info_about_letters
.iter()
.all(|x| matches!(x, Letter::FullMatch(_)));
if try_accuracy {
//if we've hit all the letters, then the game is over
self.status = GameStatus::Won;
self.attempts = self.attempts + 1;
self.word_attempts.push(Word {
info: info_about_letters.clone(),
});
return Ok(Word {
info: info_about_letters.clone(),
});
}
self.attempts = self.attempts + 1;
self.word_attempts.push(Word {
info: info_about_letters.clone(),
});
if self.attempts == 5 {
//if this is the 5th attempt, then the game is over
self.status = GameStatus::Lost;
self.word_attempts.push(Word {
info: info_about_letters.clone(),
});
return Ok(Word {
info: info_about_letters.clone(),
});
}
Ok(Word {
info: info_about_letters.clone(),
})
}
}
use std::fmt;
impl fmt::Display for Word {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let res: String = self
.info
.iter()
.map(|c| match *c {
Letter::FullMatch(t) => format!("[{}]", t.to_uppercase()),
Letter::PartialMatch(t) => format!("({})", t.to_uppercase()),
Letter::NoMatch(t) => format!(">{}<", t.to_uppercase()),
})
.collect();
write!(f, "{}", res)
}
}
impl fmt::Display for Game {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", "|_|".repeat(self.goal_word.chars().count()))?;
let res: String = self
.word_attempts
.iter()
.map(|x| format!("\n{}", x))
.collect();
write!(f, "{}", res)
}
}