Решение на Wordle от Венцислав Димитров

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

Към профила на Венцислав Димитров

Резултати

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

Код

use std::fmt;
#[derive(Debug, Copy, Clone)]
pub enum GameStatus {
InProgress,
Won,
Lost,
}
#[derive(Debug)]
pub enum GameError {
NotInAlphabet(char),
WrongLength { expected: usize, actual: usize },
GameIsOver(GameStatus),
EmptyWord,
}
#[derive(Debug)]
pub struct Game {
pub status: GameStatus,
pub attempts: u8,
pub alphabet: String,
pub word: String,
pub words: Vec<Word>,
}
#[derive(Debug, Clone)]
pub struct Word {
word: String,
guess: String,
pub matches: bool,
}
impl Word {
pub fn new(word: &str, guess: &str) -> Self {
let mut matches = true;
for (i, c) in guess.chars().enumerate() {
if word.chars().nth(i).unwrap() != c {
matches = false;
break;
}
}
Word {
word: word.to_string(),
guess: guess.to_string(),
matches: matches,
}
}
}
impl Game {
pub fn new(alphabet: &str, word: &str) -> Result<Self, GameError> {
if word.chars().count() == 0 {
return Err(GameError::EmptyWord);
}
if let Some(c) = word.chars().find(|&c| !alphabet.contains(c)) {
return Err(GameError::NotInAlphabet(c));
}
return Ok(Self{status: GameStatus::InProgress, attempts: 0, alphabet: alphabet.to_string(), word: word.to_string(), words: Vec::new()});
}
pub fn guess_word(&mut self, guess: &str) -> Result<Word, GameError> {
if matches!(self.status, GameStatus::Won | GameStatus::Lost) {
return Err(GameError::GameIsOver(self.status));
}
let expected = self.word.chars().count();
let actual = guess.chars().count();
if expected != actual {
return Err(GameError::WrongLength{expected, actual});
}
if let Some(c) = guess.chars().find(|&c| !self.alphabet.contains(c)) {
return Err(GameError::NotInAlphabet(c));
}
self.attempts = self.attempts + 1;
let attempt = Word::new(&self.word, guess);
if attempt.matches {
self.status = GameStatus::Won;
} else if self.attempts == 5 {
self.status = GameStatus::Lost;
}
self.words.push(attempt.clone());
return Ok(attempt);
}
}
impl fmt::Display for Word {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut print = "".to_string();
for (i, c) in self.guess.chars().enumerate() {
if self.word.chars().nth(i).unwrap() == c {
let s = format!("[{}]", c.to_uppercase());
print.push_str(&s);
} else if self.word.contains(c) {
let s = format!("({})", c.to_uppercase());
print.push_str(&s);
} else {
let s = format!(">{}<", c.to_uppercase());
print.push_str(&s);
}
}
write!(f, "{}", print)
}
}
impl fmt::Display for Game {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut print = "".to_string();
let mut placeholder = "".to_string();
for c in self.word.chars().enumerate() {
placeholder.push_str(&"|_|");
}
print.push_str(&placeholder);
for w in &self.words {
print.push_str(&"\n");
print.push_str(&w.to_string());
}
write!(f, "{}", print)
}
}

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

Compiling solution v0.1.0 (/tmp/d20230111-3772066-z5iowy/solution)
warning: unused variable: `c`
   --> src/lib.rs:118:13
    |
118 |         for c in self.word.chars().enumerate() {
    |             ^ help: if this is intentional, prefix it with an underscore: `_c`
    |
    = note: `#[warn(unused_variables)]` on by default

warning: `solution` (lib) generated 1 warning
    Finished test [unoptimized + debuginfo] target(s) in 0.77s
     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_german ... ok
test solution_test::test_word_display_bulgarian ... 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_guess ... ok
test solution_test::test_word_not_in_alphabet_on_construction_cyrrilic ... 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

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

Венцислав качи първо решение на 24.11.2022 14:57 (преди почти 3 години)