-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.rs
270 lines (237 loc) · 6.96 KB
/
game.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
use chrono::{DateTime, Local, TimeZone};
use clap::ArgEnum;
use rand::seq::SliceRandom;
use std::collections::HashMap;
use std::{
fmt::{Debug, Formatter},
fs::File,
io::{self, prelude::*, BufReader},
path::Path,
};
#[derive(Clone)]
pub struct WordSet {
wordlist: Vec<String>,
valid_guesses: Vec<String>,
}
impl Debug for WordSet {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_str("WordSet")
}
}
impl WordSet {
pub fn load(
wordlist_path: Option<impl AsRef<Path>>,
guesses_path: Option<impl AsRef<Path>>,
) -> io::Result<Self> {
let wordlist = wordlist_path
.map(|p| lines_from_file(p))
.unwrap_or(Ok(include_str!("../data/wordlist.txt")
.lines()
.map(|s| String::from(s))
.collect()))?;
let valid_guesses =
guesses_path
.map(|p| lines_from_file(p))
.unwrap_or(Ok(include_str!("../data/guesses.txt")
.lines()
.map(|s| String::from(s))
.collect()))?;
Ok(WordSet {
wordlist,
valid_guesses,
})
}
fn is_valid(&self, word: &str) -> bool {
let needle = &word.to_lowercase();
self.wordlist.contains(needle) || self.valid_guesses.contains(needle)
}
fn word_of_the_day(&self) -> String {
let epoch: DateTime<Local> = Local.ymd(2021, 6, 19).and_hms(0, 0, 0);
let idx = (Local::now().date().and_hms(0, 0, 0).timestamp() - epoch.timestamp()) / 86400;
self.wordlist
.get(idx as usize % self.wordlist.len())
.unwrap()
.to_ascii_uppercase()
}
fn random_word(&self) -> String {
self.wordlist
.choose(&mut rand::thread_rng())
.unwrap()
.to_ascii_uppercase()
}
}
#[derive(Debug)]
pub(crate) struct RusdleState {
words: WordSet,
target: Vec<char>,
pub(crate) entry: String,
pub(crate) last_error: Option<String>,
pub(crate) guesses: Vec<(String, [u8; 5])>,
pub(crate) clues: HashMap<char, u8>,
}
#[derive(ArgEnum, Clone)]
pub enum GameMode {
Wordle,
RandomWord,
}
pub enum GameInput {
Delete,
Input(char),
Quit,
Submit,
}
impl RusdleState {
pub fn new(words: WordSet, mode: GameMode) -> Self {
let word = match mode {
GameMode::RandomWord => words.random_word(),
GameMode::Wordle => words.word_of_the_day(),
};
Self::new_with_target(words, &word)
}
pub fn new_with_target(words: WordSet, target: &str) -> Self {
assert!(words.is_valid(target));
let target = target.chars().collect();
Self {
words,
target,
last_error: None,
entry: String::with_capacity(5),
guesses: Vec::with_capacity(6),
clues: HashMap::with_capacity(26),
}
}
pub fn handle_input(&mut self, input: GameInput) {
match input {
GameInput::Input(c) => {
if self.entry.len() < 5 {
self.entry.push(c.to_ascii_uppercase())
}
}
GameInput::Delete => {
if self.entry.len() > 0 {
self.entry.pop();
}
}
GameInput::Submit => {
if self.entry.len() == 5 {
self.process_guess();
}
}
GameInput::Quit => {}
}
}
pub fn is_over(&self) -> bool {
self.guesses.len() == 6 || self.is_win()
}
pub fn is_win(&self) -> bool {
match self.guesses.last() {
Some((_, r)) if *r == [RES_CORRECT; 5] => true,
_ => false,
}
}
fn process_guess(&mut self) {
if !(self.words.is_valid(&self.entry)) {
self.last_error = Some(format!("Word '{}' is not valid.", self.entry))
} else {
self.last_error = None;
let guess = self.entry.clone();
let result = self.compare_guess(&guess);
guess.chars().zip(result).for_each(|(c, r)| {
let clue = self.clues.entry(c).or_insert(r);
if r > *clue {
*clue = r
}
});
self.guesses.push((guess, result));
self.entry.clear()
}
}
fn compare_guess(&mut self, guess: &str) -> [u8; 5] {
let mut unmatched: Vec<char> = self
.target
.iter()
.cloned()
.zip(guess.chars())
.filter_map(|(actual, guessed)| {
if actual != guessed {
Some(actual)
} else {
None
}
})
.collect();
guess
.char_indices()
.map(|(i, c)| {
if c == self.target[i] {
RES_CORRECT
} else if unmatched.remove_item(c) {
RES_PRESENT
} else {
RES_WRONG
}
})
.collect::<Vec<u8>>()
.try_into()
.unwrap()
}
}
pub const RES_DEFAULT: u8 = 0;
pub const RES_WRONG: u8 = 1;
pub const RES_PRESENT: u8 = 2;
pub const RES_CORRECT: u8 = 3;
fn lines_from_file(filename: impl AsRef<Path>) -> io::Result<Vec<String>> {
let file = File::open(filename)?;
BufReader::new(file).lines().collect()
}
trait MutVecExt<T> {
fn remove_item(&mut self, val: T) -> bool;
}
impl<T: PartialEq> MutVecExt<T> for Vec<T> {
fn remove_item(&mut self, val: T) -> bool {
if let Some(idx) = self.iter().position(|x| *x == val) {
self.swap_remove(idx);
true
} else {
false
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn default_words() -> WordSet {
WordSet::load(None::<&str>, None::<&str>).unwrap()
}
fn test_game(target: &str) -> RusdleState {
RusdleState::new_with_target(default_words(), target)
}
fn result(code: &str) -> [u8; 5] {
code.chars()
.map(|c| match c {
'!' => RES_CORRECT,
'?' => RES_PRESENT,
'x' => RES_WRONG,
_ => panic!("unknown code char {}", c),
})
.collect::<Vec<u8>>()
.try_into()
.unwrap()
}
#[test]
fn compare_guess_confirms_all_match() {
assert_eq!(test_game("MATCH").compare_guess("MATCH"), result("!!!!!"))
}
#[test]
fn compare_guess_allows_double_correct() {
assert_eq!(test_game("NOOBS").compare_guess("ROOTY"), result("x!!xx"))
}
#[test]
fn compare_guess_allows_double_present() {
assert_eq!(test_game("NOOBS").compare_guess("IGLOO"), result("xxx??"))
}
#[test]
fn compare_guess_isnt_greedy() {
assert_eq!(test_game("FRAME").compare_guess("ELIDE"), result("xxxx!"))
}
}