Compare commits

...

8 Commits
master ... v2

18 changed files with 1198 additions and 983 deletions

View File

@ -2,6 +2,7 @@ on:
pull_request:
branches:
- master
- feature
permissions:
contents: write
@ -35,7 +36,6 @@ jobs:
profile: minimal
toolchain: nightly
- name: run frontend tests
working-directory: ./frontend/
- name: run tests
run: |
cargo test
cargo test --workspace

15
.vscode/tasks.json vendored Normal file
View File

@ -0,0 +1,15 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "bacon",
"type": "shell",
"command": "bacon",
"problemMatcher": "$rustc",
"group": {
"kind": "build",
"isDefault": true
}
}
]
}

10
Cargo.lock generated
View File

@ -1833,9 +1833,9 @@ dependencies = [
[[package]]
name = "serde"
version = "1.0.209"
version = "1.0.210"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "99fce0ffe7310761ca6bf9faf5115afbc19688edd00171d81b1bb1b116c63e09"
checksum = "c8e3592472072e6e22e0a54d5904d9febf8508f65fb8552499a1abc7d1078c3a"
dependencies = [
"serde_derive",
]
@ -1864,9 +1864,9 @@ dependencies = [
[[package]]
name = "serde_derive"
version = "1.0.209"
version = "1.0.210"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5831b979fd7b5439637af1752d535ff49f4860c0f341d1baeb6faf0f4242170"
checksum = "243902eda00fad750862fc144cea25caca5e20d615af0a81bee94ca738f1df1f"
dependencies = [
"proc-macro2",
"quote",
@ -2838,6 +2838,7 @@ dependencies = [
"axum 0.7.5",
"http 1.1.0",
"rand",
"serde",
"shuttle-axum",
"shuttle-runtime",
"tower-http",
@ -2855,6 +2856,7 @@ dependencies = [
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
"wordl",
"yew",
"yew-router",
"yewdux",

View File

@ -7,6 +7,7 @@ edition = "2021"
axum = "0.7.5"
http = "1.1.0"
rand = "0.8.5"
serde = { version = "1.0.210", features = ["derive"] }
shuttle-axum = "0.47.0"
shuttle-runtime = "0.47.0"
tower-http = { version = "0.5.2", features = ["compression-br", "compression-gzip", "cors", "fs"] }
@ -15,3 +16,10 @@ tracing = "0.1.40"
[workspace]
members = [".", "frontend"]
[dev-dependencies]
rand = "0.8.5"
[profile.release.package.wordl-frontend]
opt-level = "z"
strip = true

144
bacon.toml Normal file
View File

@ -0,0 +1,144 @@
# This is a configuration file for the bacon tool
#
# Bacon repository: https://github.com/Canop/bacon
# Complete help on configuration: https://dystroy.org/bacon/config/
# You can also check bacon's own bacon.toml file
# as an example: https://github.com/Canop/bacon/blob/main/bacon.toml
default_job = "check"
[jobs.check]
command = ["cargo", "check", "--color", "always"]
need_stdout = false
[jobs.check-all]
command = ["cargo", "check", "--all-targets", "--color", "always"]
need_stdout = false
# Run clippy on the default target
[jobs.clippy]
command = [
"cargo", "clippy",
"--color", "always",
"--",
"-W", "clippy::all",
"-W", "clippy::pedantic",
"-W", "clippy::nursery",
"-W", "clippy::expect_used",
"-W", "clippy::unwrap_used"
]
need_stdout = false
# Run clippy on all targets
# To disable some lints, you may change the job this way:
# [jobs.clippy-all]
# command = [
# "cargo", "clippy",
# "--all-targets",
# "--color", "always",
# "--",
# "-A", "clippy::bool_to_int_with_if",
# "-A", "clippy::collapsible_if",
# "-A", "clippy::derive_partial_eq_without_eq",
# ]
# need_stdout = false
[jobs.clippy-all]
command = [
"cargo", "clippy",
"--all-targets",
"--color", "always",
"--",
"-W", "clippy::all",
"-W", "clippy::pedantic",
"-W", "clippy::nursery",
"-W", "clippy::expect_used",
"-W", "clippy::unwrap_used"
]
need_stdout = false
[jobs.clippy-all-workspace]
command = [
"cargo", "clippy",
"--all-targets",
"--color", "always",
"--workspace",
"--",
"-W", "clippy::all",
"-W", "clippy::pedantic",
"-W", "clippy::nursery",
"-W", "clippy::expect_used",
"-W", "clippy::unwrap_used"
]
need_stdout = false
[jobs.clippy-workspace]
command = [
"cargo", "clippy",
"--color", "always",
"--workspace",
"--",
"-W", "clippy::all",
"-W", "clippy::pedantic",
"-W", "clippy::nursery",
"-W", "clippy::expect_used",
"-W", "clippy::unwrap_used"
]
need_stdout = false
# This job lets you run
# - all tests: bacon test
# - a specific test: bacon test -- config::test_default_files
# - the tests of a package: bacon test -- -- -p config
[jobs.test]
command = [
"cargo", "test", "--color", "always",
"--", "--color", "always", # see https://github.com/Canop/bacon/issues/124
]
need_stdout = true
[jobs.doc]
command = ["cargo", "doc", "--color", "always", "--no-deps"]
need_stdout = false
# If the doc compiles, then it opens in your browser and bacon switches
# to the previous job
[jobs.doc-open]
command = ["cargo", "doc", "--color", "always", "--no-deps", "--open"]
need_stdout = false
on_success = "back" # so that we don't open the browser at each change
# You can run your application and have the result displayed in bacon,
# *if* it makes sense for this crate.
# Don't forget the `--color always` part or the errors won't be
# properly parsed.
# If your program never stops (eg a server), you may set `background`
# to false to have the cargo run output immediately displayed instead
# of waiting for program's end.
[jobs.run]
command = [
"cargo", "run",
"--color", "always",
# put launch parameters for your program behind a `--` separator
]
need_stdout = true
allow_warnings = true
background = true
# This parameterized job runs the example of your choice, as soon
# as the code compiles.
# Call it as
# bacon ex -- my-example
[jobs.ex]
command = ["cargo", "run", "--color", "always", "--example"]
need_stdout = true
allow_warnings = true
# You may define here keybindings that would be specific to
# a project, for example a shortcut to launch a specific job.
# Shortcuts to internal functions (scrolling, toggling, etc.)
# should go in your personal global prefs.toml file instead.
[keybindings]
ctrl-alt-w = "job:clippy-all-workspace"
alt-w = "job:clippy-workspace"
alt-c = "job:clippy-all" # comment this to have 'c' run clippy on only the default target
c = "job:clippy"

View File

@ -28,6 +28,8 @@
tailwindcss
cargo-shuttle
cargo-edit
cargo-binstall
bacon
openssl
pkg-config

View File

@ -20,8 +20,5 @@ gloo-net = "0.6.0"
serde = { version = "1.0.209", features = ["derive"] }
serde_json = "1.0.127"
rand = "0.8.5"
wordl = {path = "../"}
[profile.release]
opt-level = "z"
lto = true
strip = true

View File

@ -1,79 +0,0 @@
use web_sys::HtmlInputElement;
use yew::prelude::*;
#[derive(Properties, PartialEq)]
pub struct InputStringProps {
pub value: String,
}
pub enum Msg {
CharInput(usize, String),
}
pub struct InputString {
value: String,
nodes: Vec<NodeRef>,
focused_index: usize,
}
impl Component for InputString {
type Message = Msg;
type Properties = InputStringProps;
fn create(ctx: &Context<Self>) -> Self {
let value = ctx.props().value.clone();
let nodes = vec![NodeRef::default(); value.len()];
Self {
value,
nodes,
focused_index: 0,
}
}
fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::CharInput(index, new_char) => {
let mut new_value = self.value.clone();
new_value.replace_range(index..index + 1, &new_char);
self.value = new_value;
if index < self.value.len() - 1 {
self.focused_index = index + 1;
if let Some(next_node) = self.nodes.get(self.focused_index) {
if let Some(input) = next_node.cast::<HtmlInputElement>() {
input.focus().unwrap();
}
}
}
true
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
let chars = self.value.chars().enumerate().map(|(index, char)| {
let on_input = ctx.link().callback(move |input: InputEvent| {
let new_char = input.data();
Msg::CharInput(index, new_char.unwrap())
});
html! {
<input
type="text"
maxlength=1
value={char.to_string()}
oninput={on_input}
class="w-12 h-16 text-center"
ref={self.nodes.get(index).unwrap().clone()}
style={if index == self.focused_index { "background-color: yellow;" } else { "" }}
/>
}
});
html! {
<div style="display: flex; gap: 0.5rem;">
{ for chars }
</div>
}
}
}

View File

@ -1,137 +1,2 @@
pub mod pages;
pub mod router;
// pub mod storage;
// mod input;
use std::collections::HashMap;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)]
enum CharStatus<T> {
NotContained(T),
Contained(T),
Match(T),
Unknown,
}
fn compare_strings(s1: &str, s2: &str) -> Vec<CharStatus<String>> {
let mut result: Vec<CharStatus<String>> = Vec::with_capacity(s1.len());
result.resize_with(s1.len(), || CharStatus::Unknown);
let mut s1_char_count: HashMap<char, usize> = HashMap::new();
let mut s2_char_count: HashMap<char, usize> = HashMap::new();
for c in s1.chars() {
*s1_char_count.entry(c).or_insert(0) += 1;
}
for ((c1, c2), res) in s1.chars().zip(s2.chars()).zip(result.iter_mut()) {
if c1 == c2 {
*res = CharStatus::Match(c2.to_string());
*s2_char_count.entry(c2).or_insert(0) += 1;
} else {
*res = CharStatus::Unknown;
}
}
for (res, c2) in result.iter_mut().zip(s2.chars()) {
if res == &CharStatus::Unknown {
let c1_count = s1_char_count.get(&c2).unwrap_or(&0);
let c2_count = s2_char_count.get(&c2).unwrap_or(&0);
if *c1_count > 0 && c1_count > c2_count {
*res = CharStatus::Contained(c2.to_string());
*s2_char_count.entry(c2).or_insert(0) += 1;
} else {
*res = CharStatus::NotContained(c2.to_string());
}
}
}
result
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_compare_strings() {
let source = "HALLO";
let want = vec![
CharStatus::NotContained("0".to_owned()),
CharStatus::NotContained("0".to_owned()),
CharStatus::NotContained("0".to_owned()),
CharStatus::NotContained("0".to_owned()),
CharStatus::NotContained("0".to_owned()),
];
let input = "00000";
let got = compare_strings(source, input);
assert_eq!(want, got);
let source = "HALLO";
let want = vec![
CharStatus::NotContained("L".to_owned()),
CharStatus::NotContained("L".to_owned()),
CharStatus::Match("L".to_owned()),
CharStatus::Match("L".to_owned()),
CharStatus::NotContained("L".to_owned()),
];
let input = "LLLLL";
let got = compare_strings(source, input);
assert_eq!(want, got);
let want = vec![
CharStatus::Match("H".to_owned()),
CharStatus::Match("A".to_owned()),
CharStatus::Match("L".to_owned()),
CharStatus::Match("L".to_owned()),
CharStatus::Match("O".to_owned()),
];
let input = "HALLO";
let got = compare_strings(source, input);
assert_eq!(want, got);
let want = vec![
CharStatus::Match("H".to_owned()),
CharStatus::NotContained("L".to_owned()),
CharStatus::Match("L".to_owned()),
CharStatus::Match("L".to_owned()),
CharStatus::Match("O".to_owned()),
];
let input = "HLLLO";
let got = compare_strings(source, input);
assert_eq!(want, got);
let want = vec![
CharStatus::Match("H".to_owned()),
CharStatus::Contained("L".to_owned()),
CharStatus::Match("L".to_owned()),
CharStatus::NotContained("I".to_owned()),
CharStatus::NotContained("L".to_owned()),
];
let input = "HLLIL";
let got = compare_strings(source, input);
assert_eq!(want, got);
let want = vec![
CharStatus::Contained("L".to_owned()),
CharStatus::NotContained("L".to_owned()),
CharStatus::Match("L".to_owned()),
CharStatus::Contained("A".to_owned()),
CharStatus::Match("O".to_owned()),
];
let input = "LLLAO";
let got = compare_strings(source, input);
assert_eq!(want, got);
}
}

View File

@ -1,122 +0,0 @@
// use rand::seq::SliceRandom;
use serde::{Deserialize, Serialize};
use crate::CharStatus;
const MAX_TRIES: usize = 5;
// #[derive(Debug, Serialize, Deserialize, Clone)]
// struct Games(Vec<Game>);
// impl Games {
// pub const fn new() -> Self {
// Self(Vec::new())
// }
// pub fn new_game(&mut self, word: String) {
// let game = Game::new();
// self.0.push(game);
// }
// pub fn current_game(&self) -> Option<&Game> {
// self.0.last()
// }
// }
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct WordList {
words: Vec<String>,
}
impl WordList {
pub const fn new() -> Self {
Self { words: Vec::new() }
}
pub fn from_json(s: &str) -> Self {
serde_json::from_str(s).map_or(Self::new(), |w| w)
}
// pub fn to_json(&self) -> String {
// serde_json::to_string_pretty(self).map_or(String::new(), |w| w)
// }
// pub fn get_word(&self) -> String {
// let mut rng = rand::thread_rng();
// self.words
// .choose(&mut rng)
// .map_or_else(String::new, |w| (*w).to_string())
// }
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Game {
pub word: Option<String>,
pub submitted_words: Vec<Vec<CharStatus<String>>>,
tries: usize,
status: Status,
}
impl Game {
pub const fn new() -> Self {
Self {
word: None,
tries: 0,
submitted_words: Vec::new(),
status: Status::New,
}
}
pub fn start(&mut self, word: String) {
if self.word.is_none() && self.status == Status::New {
self.status = Status::InProgress;
self.word = Some(word);
}
}
pub fn submit_answer(&mut self, answer: &[String]) {
if let Some(ref word) = self.word {
let res = crate::compare_strings(word, &answer.join(""));
self.submitted_words.push(res);
self.tries += 1;
self.status = self.current_status();
}
}
pub fn current_status(&self) -> Status {
self.word.as_ref().map_or(Status::New, |_| {
let word_count = self.submitted_words.len();
match self.tries {
0 => Status::New,
1..MAX_TRIES => self
.submitted_words
.last()
.map_or(Status::InProgress, |words| {
if words.iter().all(|v| matches!(v, CharStatus::Match(_))) {
Status::Win(word_count)
} else {
Status::InProgress
}
}),
_ => self
.submitted_words
.last()
.map_or(Status::Lose(word_count), |words| {
if words.iter().all(|v| matches!(v, CharStatus::Match(_))) {
Status::Win(word_count)
} else {
Status::Lose(word_count)
}
}),
}
})
}
}
type Tries = usize;
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
#[allow(clippy::module_name_repetitions)]
pub enum Status {
New,
Win(Tries),
Lose(Tries),
InProgress,
}

View File

@ -1,639 +1,10 @@
use gloo_net::http::Request;
use web_sys::wasm_bindgen::convert::OptionIntoWasmAbi;
use web_sys::wasm_bindgen::JsCast;
use web_sys::HtmlElement;
use yew::prelude::*;
use yew::{classes, function_component, Callback, Html};
use crate::pages::game::{Game, Status};
use crate::CharStatus;
use super::game::WordList;
static NEW_WORD_URI: &str = "https://wordl.shuttleapp.rs/word";
static WORDS_URI: &str = "https://wordl.shuttleapp.rs/public/wordlist.json";
static MAX_TRIES: usize = 5;
fn set_focus(index: usize) {
let prefix = match index {
0 => "",
_ => "-",
};
if let Some(w) = web_sys::window() {
if let Some(d) = w.document() {
if let Some(n) = d
.query_selector(&format!("[tabindex='{prefix}{index}']"))
.ok()
.flatten()
{
if let Some(e) = n.dyn_ref::<HtmlElement>() {
e.focus().ok();
}
}
}
}
}
fn string_to_html(input: &[CharStatus<String>]) -> Html {
let classes = classes!(
"bg-gray-700",
"w-16",
"h-16",
"text-center",
"py-4",
"font-bold",
"text-lg",
"mb-4",
);
html! (
<ul
class={
classes!(
"flex",
"flex-row",
"gap-4",
"notranslate",
)
}
>
{
input.iter().map(|e|{
let mut classes = classes.clone();
let text = match e {
CharStatus::Match(s) => {
classes.push("bg-green-400");
s
},
CharStatus::Contained(s) => {
classes.push("bg-yellow-400");
s
},
CharStatus::NotContained(s) => {
classes.push("bg-gray-900");
classes.push("border-white");
classes.push("border-2");
s
}
CharStatus::Unknown => {
""
},
};
html!{
<li
class={
classes!(
"flex",
"items-center"
)
}
>
<span
class={
classes.clone()
}
>
{text}
</span>
</li>
}}).collect::<Html>()
}
</ul>
)
}
#[allow(clippy::too_many_arguments)]
fn fetch_new_word(
word: &UseStateHandle<String>,
loading: &UseStateHandle<bool>,
submitted_words: &UseStateHandle<Vec<Vec<CharStatus<String>>>>,
input_values: &UseStateHandle<Vec<String>>,
game_over: &UseStateHandle<bool>,
length: &UseStateHandle<usize>,
node_refs: &UseStateHandle<Vec<NodeRef>>,
result: &UseStateHandle<Status>,
) {
let loading = loading.clone();
let submitted_words = submitted_words.clone();
let input_values = input_values.clone();
let game_over = game_over.clone();
let length = length.clone();
let node_refs = node_refs.clone();
let result = result.clone();
let word = word.clone();
wasm_bindgen_futures::spawn_local(async move {
loading.set(true);
let res = Request::get(NEW_WORD_URI).send().await;
if let Ok(r) = res {
if let Ok(w) = r.text().await {
length.set(w.len());
node_refs.set(vec![NodeRef::default(); w.len()]);
input_values.set(vec![String::new(); w.len()]);
word.set(w.to_uppercase());
submitted_words.set(Vec::with_capacity(MAX_TRIES));
game_over.set(false);
result.set(Status::New);
loading.set(false);
}
}
});
}
#[allow(dead_code)]
fn fetch_words(state: &UseStateHandle<WordList>) {
let state = state.clone();
wasm_bindgen_futures::spawn_local(async move {
let res = Request::get(WORDS_URI).send().await;
if let Ok(r) = res {
if let Ok(w) = r.text().await {
state.set(WordList::from_json(&w));
}
}
});
}
fn new_game(game: &UseStateHandle<Game>) {
let game = game.clone();
wasm_bindgen_futures::spawn_local(async move {
let res = Request::get(NEW_WORD_URI).send().await;
if let Ok(r) = res {
if let Ok(w) = r.text().await {
let mut g = (*game).clone();
g.start(w);
game.set(g);
}
}
});
}
use wordl::Game;
use yew::{function_component, html, use_state, Html, UseStateHandle};
#[function_component]
pub fn Home() -> Html {
let game: UseStateHandle<Game> = use_state(Game::new);
let word: UseStateHandle<String> = use_state(String::new);
let loading: UseStateHandle<bool> = use_state(|| true);
let curr_index: UseStateHandle<usize> = use_state(|| 0usize);
let length = use_state(|| 0usize);
let submitted_words: UseStateHandle<Vec<Vec<CharStatus<String>>>> =
use_state(|| std::vec::Vec::with_capacity(MAX_TRIES));
let node_refs = use_state(|| vec![NodeRef::default(); 10]);
let input_values: UseStateHandle<Vec<String>> = use_state(|| vec![String::new(); *length]);
let game_over = use_state(|| false);
let result = use_state(|| Status::New);
{
let game = game.clone();
let handle = word.clone();
let loading = loading.clone();
let submitted_words = submitted_words.clone();
let input_values = input_values.clone();
let game_over = game_over.clone();
let length = length.clone();
let node_refs = node_refs.clone();
let result = result.clone();
use_effect_with((), move |()| {
new_game(&game);
fetch_new_word(
&handle,
&loading,
&submitted_words,
&input_values,
&game_over,
&length,
&node_refs,
&result,
);
});
let game: UseStateHandle<Game> = use_state(Game::default);
html! {
game.get_submitted_words().iter().map(|c| html!{<p>{format!("{c:?}")}</p>}).collect::<Html>()
}
let game_over_check = {
let word = word.clone();
let submitted_words = submitted_words.clone();
let input_values = input_values.clone();
let game_over = game_over.clone();
let length = length.clone();
let result = result.clone();
Callback::from(move |_| {
if submitted_words.iter().count() >= *length - 1
|| crate::compare_strings(&word, &input_values.join(""))
.iter()
.all(|v| matches!(v, CharStatus::Match(_)))
{
if crate::compare_strings(&word, &input_values.join(""))
.iter()
.all(|v| matches!(v, CharStatus::Match(_)))
{
result.set(Status::Win(submitted_words.iter().count()));
} else {
result.set(Status::Lose(MAX_TRIES));
}
game_over.set(true);
}
})
};
let on_disabled = {
let curr_index = curr_index.clone();
let input_values = input_values.clone();
Callback::from(move |_e: MouseEvent| {
let index = input_values
.iter()
.enumerate()
.find(|(_, v)| v.is_empty())
.map_or(0, |(i, _)| i);
set_focus(index);
curr_index.set(index);
})
};
let on_submit = {
let game = game.clone();
let input_values = input_values.clone();
let submitted_words = submitted_words.clone();
let game_over = game_over.clone();
let length = length.clone();
let word = word.clone();
let node_refs = node_refs.clone();
let loading = loading.clone();
let result = result.clone();
let curr_index = curr_index.clone();
Callback::from(move |_e: MouseEvent| {
if *game_over {
curr_index.set(0);
let input_values = input_values.clone();
let submitted_words = submitted_words.clone();
let game_over = game_over.clone();
let length = length.clone();
let word = word.clone();
let loading = loading.clone();
let node_refs = node_refs.clone();
let result = result.clone();
fetch_new_word(
&word,
&loading,
&submitted_words,
&input_values,
&game_over,
&length,
&node_refs,
&result,
);
return;
}
let values: Vec<_> = input_values.iter().cloned().collect();
if !values.iter().all(|v| !v.is_empty()) {
return;
}
let mut g = (*game).clone();
g.submit_answer(&input_values);
game.set(g);
let mut new_items = (*submitted_words).clone();
new_items.push(crate::compare_strings(&word, &values.join("")));
submitted_words.set(new_items);
input_values.set(vec![String::new(); word.len()]);
set_focus(0);
curr_index.set(0);
game_over_check.emit(MouseEvent::none());
})
};
let on_enter = {
let on_submit = on_submit.clone();
let curr_index = curr_index.clone();
let node_refs = node_refs.clone();
let input_values = input_values.clone();
let length = length.clone();
Callback::from(move |e: KeyboardEvent| match e.key().as_ref() {
"Enter" => {
if let Ok(m) = MouseEvent::new("click") {
on_submit.emit(m);
}
}
"Backspace" => {
e.prevent_default();
let mut index = *curr_index;
let mut values = (*input_values).clone();
if index >= *length {
curr_index.set(*length - 1);
index = *length - 1;
}
if node_refs[index]
.cast::<web_sys::HtmlInputElement>()
.is_some()
&& index > 0
{
values[index] = String::new();
input_values.set(values);
let index = index - 1;
curr_index.set(index);
set_focus(index);
}
}
_ => {}
})
};
let on_input = {
let curr_index = curr_index.clone();
let length = length.clone();
let input_values = input_values.clone();
Callback::from(move |e: InputEvent| {
if let Some(value) = e.data() {
let value = value.to_uppercase();
let index = *curr_index;
let mut values = (*input_values).clone();
if index >= *length {
values[index - 1] = value;
input_values.set(values);
} else if value.len() < values[index].len() && index > 0 && index <= *length {
values[index] = String::new();
input_values.set(values);
let new_index = index - 1;
curr_index.set(new_index);
set_focus(new_index);
} else if value.len() == 1 && value.chars().all(char::is_alphabetic) {
values[index] = value;
input_values.set(values);
if index < *length {
let new_index = index + 1;
curr_index.set(new_index);
set_focus(new_index);
}
} else {
values[index] = String::new();
input_values.set(values);
}
}
})
};
let view = {
move || {
html! {
<div
class={
classes!(
"flex",
"flex-col",
"items-center",
"justify-center",
if *loading { "h-[90vh]" } else { "" },
)
}
>
// {
// match game.current_status() {
// Status::New => html!{
// <>
// <svg xmlns="http://www.w3.org/2000/svg" class="w-16 h-16 rotate-ease" viewBox="0 -960 960 960" fill="white">
// <path d="M320-160h320v-120q0-66-47-113t-113-47q-66 0-113 47t-47 113v120Zm160-360q66 0 113-47t47-113v-120H320v120q0 66 47 113t113 47ZM160-80v-80h80v-120q0-61 28.5-114.5T348-480q-51-32-79.5-85.5T240-680v-120h-80v-80h640v80h-80v120q0 61-28.5 114.5T612-480q51 32 79.5 85.5T720-280v120h80v80H160Zm320-80Zm0-640Z"/>
// </svg>
// <p>{"Loading..."}</p>
// </>
// },
// Status::Win(tries) => html!{
// <p>{format!("WIN: {tries}")}</p>
// },
// Status::Lose(tries) => html!{
// <p>{format!("LOSE: {tries}")}</p>
// },
// Status::InProgress => html!{
// <div>
// <p>{"IN PROGRESS"}</p>
// <p>{&game.word}</p>
// </div>
// },
// }
// }
if *loading {
<svg xmlns="http://www.w3.org/2000/svg" class="w-16 h-16 rotate-ease" viewBox="0 -960 960 960" fill="white">
<path d="M320-160h320v-120q0-66-47-113t-113-47q-66 0-113 47t-47 113v120Zm160-360q66 0 113-47t47-113v-120H320v120q0 66 47 113t113 47ZM160-80v-80h80v-120q0-61 28.5-114.5T348-480q-51-32-79.5-85.5T240-680v-120h-80v-80h640v80h-80v120q0 61-28.5 114.5T612-480q51 32 79.5 85.5T720-280v120h80v80H160Zm320-80Zm0-640Z"/>
</svg>
<p>{"Loading..."}</p>
} else {
<div
class={
classes!(
"h-5/6",
"flex",
"flex-col",
"items-center",
"pt-12",
)
}
>
<div class={
classes!(
"mb-12",
)}>
{ for submitted_words.iter().map(|e| {string_to_html(e)})}
</div>
<form
class="mb-4"
>
<div
class={
classes!(
"flex",
"flex-row",
"font-bold",
"text-lg",
"gap-4",
)
}
>
{
if *game_over {
let (text, color) = match *result {
Status::Win(_) => {
("FOUND", "bg-green-600")
},
Status::Lose(_) => {
("WANTED", "bg-red-600")
},
_ => {
("NEW", "bg-gray-600")
},
};
html! (
<div>
<h1>{
text
}</h1>
<ul
class={
classes!(
"flex",
"flex-row",
"gap-4",
"notranslate",
)
}
>
{
word.chars().map(|e|{
let text = e;
html!{
<li
class={
classes!(
"flex",
"items-center"
)
}
>
<span
class={
classes!(
"w-16",
"h-16",
"text-center",
"py-4",
"font-bold",
"text-lg",
{color},
)
}
>
{text}
</span>
</li>
}}).collect::<Html>()
}
</ul>
</div>
)
}
else if !*game_over {
node_refs.iter().enumerate().map(|(index, node_ref)| {
let on_focus = {
let curr_index = curr_index.clone();
Callback::from(move |e: FocusEvent| {
let target = e.target_unchecked_into::<web_sys::HtmlElement>();
if let Some(index) = target.get_attribute("tabindex") {
if let Ok(i) = index.replace('-', "").parse::<usize>() {
curr_index.set(i);
}
}
})
};
let prefix = match index {
0 => String::new(),
_ => "-".to_owned(),
};
html! {
<input
aria-label={format!("letter-{index}")}
onkeyup={on_enter.clone()}
oninput={on_input.clone()}
tabindex={ format!("{prefix}{index}")}
ref={node_ref.clone()}
value={input_values[index].clone()}
onfocus={on_focus.clone()}
class={
classes!(
"w-16",
"h-16",
"text-center",
"bg-gray-600"
)
}
/>
}
}).collect::<Html>()
} else {
html!(<div></div>)
}
}
</div>
</form>
{
if *loading {
html!{<></>}
} else {
html!{
<div
class={
classes!(
"w-full",
"flex",
"justify-end",
)
}
>
<button
aria-label={if *game_over { "Play Again"} else { "Submit"}}
tabindex={format!("-{}",*length + 1)}
class={
classes!(
"w-24",
"h-16",
"text-2xl",
"font-bold",
"rounded-xl",
"flex",
"items-center",
"justify-center",
{if input_values.iter().any(std::string::String::is_empty) && !*game_over {"bg-gray-700"} else {"bg-green-600"}},
)
}
onclick={if input_values.iter().any(std::string::String::is_empty) && !*game_over {on_disabled} else {on_submit}} type="submit">
{
if *game_over {
html!{
<svg xmlns="http://www.w3.org/2000/svg" class="w-12 h-12 rotate-box" viewBox="0 -960 960 960" fill="white">
<path d="M440-122q-121-15-200.5-105.5T160-440q0-66 26-126.5T260-672l57 57q-38 34-57.5 79T240-440q0 88 56 155.5T440-202v80Zm80 0v-80q87-16 143.5-83T720-440q0-100-70-170t-170-70h-3l44 44-56 56-140-140 140-140 56 56-44 44h3q134 0 227 93t93 227q0 121-79.5 211.5T520-122Z"/>
</svg>
}
}
else if input_values.iter().any(std::string::String::is_empty) {
html!{
<svg xmlns="http://www.w3.org/2000/svg" class="w-12 h-12" viewBox="0 -960 960 960" width="24px" fill="white">
<path d="M480-80q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0-80q54 0 104-17.5t92-50.5L228-676q-33 42-50.5 92T160-480q0 134 93 227t227 93Zm252-124q33-42 50.5-92T800-480q0-134-93-227t-227-93q-54 0-104 17.5T284-732l448 448Z"/>
</svg>
}
} else {
html!{
<svg xmlns="http://www.w3.org/2000/svg" class="w-12 h-12" viewBox="0 -960 960 960" fill="white">
<path d="m424-296 282-282-56-56-226 226-114-114-56 56 170 170Zm56 216q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0-80q134 0 227-93t93-227q0-134-93-227t-227-93q-134 0-227 93t-93 227q0 134 93 227t227 93Zm0-320Z"/>
</svg>
}
}
}
</button>
</div>
}
}
}
</div>
}
</div>
}
}
};
view()
}

View File

@ -0,0 +1,639 @@
use gloo_net::http::Request;
use web_sys::wasm_bindgen::convert::OptionIntoWasmAbi;
use web_sys::wasm_bindgen::JsCast;
use web_sys::HtmlElement;
use yew::prelude::*;
use yew::{classes, function_component, Callback, Html};
use crate::pages::game::{Game, Status};
use crate::CharStatus;
use super::game::WordList;
static NEW_WORD_URI: &str = "https://wordl.shuttleapp.rs/word";
static WORDS_URI: &str = "https://wordl.shuttleapp.rs/public/wordlist.json";
static MAX_TRIES: usize = 5;
fn set_focus(index: usize) {
let prefix = match index {
0 => "",
_ => "-",
};
if let Some(w) = web_sys::window() {
if let Some(d) = w.document() {
if let Some(n) = d
.query_selector(&format!("[tabindex='{prefix}{index}']"))
.ok()
.flatten()
{
if let Some(e) = n.dyn_ref::<HtmlElement>() {
e.focus().ok();
}
}
}
}
}
fn string_to_html(input: &[CharStatus<String>]) -> Html {
let classes = classes!(
"bg-gray-700",
"w-16",
"h-16",
"text-center",
"py-4",
"font-bold",
"text-lg",
"mb-4",
);
html! (
<ul
class={
classes!(
"flex",
"flex-row",
"gap-4",
"notranslate",
)
}
>
{
input.iter().map(|e|{
let mut classes = classes.clone();
let text = match e {
CharStatus::Match(s) => {
classes.push("bg-green-400");
s
},
CharStatus::Contained(s) => {
classes.push("bg-yellow-400");
s
},
CharStatus::NotContained(s) => {
classes.push("bg-gray-900");
classes.push("border-white");
classes.push("border-2");
s
}
CharStatus::Unknown => {
""
},
};
html!{
<li
class={
classes!(
"flex",
"items-center"
)
}
>
<span
class={
classes.clone()
}
>
{text}
</span>
</li>
}}).collect::<Html>()
}
</ul>
)
}
#[allow(clippy::too_many_arguments)]
fn fetch_new_word(
word: &UseStateHandle<String>,
loading: &UseStateHandle<bool>,
submitted_words: &UseStateHandle<Vec<Vec<CharStatus<String>>>>,
input_values: &UseStateHandle<Vec<String>>,
game_over: &UseStateHandle<bool>,
length: &UseStateHandle<usize>,
node_refs: &UseStateHandle<Vec<NodeRef>>,
result: &UseStateHandle<Status>,
) {
let loading = loading.clone();
let submitted_words = submitted_words.clone();
let input_values = input_values.clone();
let game_over = game_over.clone();
let length = length.clone();
let node_refs = node_refs.clone();
let result = result.clone();
let word = word.clone();
wasm_bindgen_futures::spawn_local(async move {
loading.set(true);
let res = Request::get(NEW_WORD_URI).send().await;
if let Ok(r) = res {
if let Ok(w) = r.text().await {
length.set(w.len());
node_refs.set(vec![NodeRef::default(); w.len()]);
input_values.set(vec![String::new(); w.len()]);
word.set(w.to_uppercase());
submitted_words.set(Vec::with_capacity(MAX_TRIES));
game_over.set(false);
result.set(Status::New);
loading.set(false);
}
}
});
}
#[allow(dead_code)]
fn fetch_words(state: &UseStateHandle<WordList>) {
let state = state.clone();
wasm_bindgen_futures::spawn_local(async move {
let res = Request::get(WORDS_URI).send().await;
if let Ok(r) = res {
if let Ok(w) = r.text().await {
state.set(WordList::from_json(&w));
}
}
});
}
fn new_game(game: &UseStateHandle<Game>) {
let game = game.clone();
wasm_bindgen_futures::spawn_local(async move {
let res = Request::get(NEW_WORD_URI).send().await;
if let Ok(r) = res {
if let Ok(w) = r.text().await {
let mut g = (*game).clone();
g.start(w);
game.set(g);
}
}
});
}
#[function_component]
pub fn Home() -> Html {
let game: UseStateHandle<Game> = use_state(Game::new);
let word: UseStateHandle<String> = use_state(String::new);
let loading: UseStateHandle<bool> = use_state(|| true);
let curr_index: UseStateHandle<usize> = use_state(|| 0usize);
let length = use_state(|| 0usize);
let submitted_words: UseStateHandle<Vec<Vec<CharStatus<String>>>> =
use_state(|| std::vec::Vec::with_capacity(MAX_TRIES));
let node_refs = use_state(|| vec![NodeRef::default(); 10]);
let input_values: UseStateHandle<Vec<String>> = use_state(|| vec![String::new(); *length]);
let game_over = use_state(|| false);
let result = use_state(|| Status::New);
{
let game = game.clone();
let handle = word.clone();
let loading = loading.clone();
let submitted_words = submitted_words.clone();
let input_values = input_values.clone();
let game_over = game_over.clone();
let length = length.clone();
let node_refs = node_refs.clone();
let result = result.clone();
use_effect_with((), move |()| {
new_game(&game);
fetch_new_word(
&handle,
&loading,
&submitted_words,
&input_values,
&game_over,
&length,
&node_refs,
&result,
);
});
}
let game_over_check = {
let word = word.clone();
let submitted_words = submitted_words.clone();
let input_values = input_values.clone();
let game_over = game_over.clone();
let length = length.clone();
let result = result.clone();
Callback::from(move |_| {
if submitted_words.iter().count() >= *length - 1
|| crate::compare_strings(&word, &input_values.join(""))
.iter()
.all(|v| matches!(v, CharStatus::Match(_)))
{
if crate::compare_strings(&word, &input_values.join(""))
.iter()
.all(|v| matches!(v, CharStatus::Match(_)))
{
result.set(Status::Win(submitted_words.iter().count()));
} else {
result.set(Status::Lose(MAX_TRIES));
}
game_over.set(true);
}
})
};
let on_disabled = {
let curr_index = curr_index.clone();
let input_values = input_values.clone();
Callback::from(move |_e: MouseEvent| {
let index = input_values
.iter()
.enumerate()
.find(|(_, v)| v.is_empty())
.map_or(0, |(i, _)| i);
set_focus(index);
curr_index.set(index);
})
};
let on_submit = {
let game = game.clone();
let input_values = input_values.clone();
let submitted_words = submitted_words.clone();
let game_over = game_over.clone();
let length = length.clone();
let word = word.clone();
let node_refs = node_refs.clone();
let loading = loading.clone();
let result = result.clone();
let curr_index = curr_index.clone();
Callback::from(move |_e: MouseEvent| {
if *game_over {
curr_index.set(0);
let input_values = input_values.clone();
let submitted_words = submitted_words.clone();
let game_over = game_over.clone();
let length = length.clone();
let word = word.clone();
let loading = loading.clone();
let node_refs = node_refs.clone();
let result = result.clone();
fetch_new_word(
&word,
&loading,
&submitted_words,
&input_values,
&game_over,
&length,
&node_refs,
&result,
);
return;
}
let values: Vec<_> = input_values.iter().cloned().collect();
if !values.iter().all(|v| !v.is_empty()) {
return;
}
let mut g = (*game).clone();
g.submit_answer(&input_values);
game.set(g);
let mut new_items = (*submitted_words).clone();
new_items.push(crate::compare_strings(&word, &values.join("")));
submitted_words.set(new_items);
input_values.set(vec![String::new(); word.len()]);
set_focus(0);
curr_index.set(0);
game_over_check.emit(MouseEvent::none());
})
};
let on_enter = {
let on_submit = on_submit.clone();
let curr_index = curr_index.clone();
let node_refs = node_refs.clone();
let input_values = input_values.clone();
let length = length.clone();
Callback::from(move |e: KeyboardEvent| match e.key().as_ref() {
"Enter" => {
if let Ok(m) = MouseEvent::new("click") {
on_submit.emit(m);
}
}
"Backspace" => {
e.prevent_default();
let mut index = *curr_index;
let mut values = (*input_values).clone();
if index >= *length {
curr_index.set(*length - 1);
index = *length - 1;
}
if node_refs[index]
.cast::<web_sys::HtmlInputElement>()
.is_some()
&& index > 0
{
values[index] = String::new();
input_values.set(values);
let index = index - 1;
curr_index.set(index);
set_focus(index);
}
}
_ => {}
})
};
let on_input = {
let curr_index = curr_index.clone();
let length = length.clone();
let input_values = input_values.clone();
Callback::from(move |e: InputEvent| {
if let Some(value) = e.data() {
let value = value.to_uppercase();
let index = *curr_index;
let mut values = (*input_values).clone();
if index >= *length {
values[index - 1] = value;
input_values.set(values);
} else if value.len() < values[index].len() && index > 0 && index <= *length {
values[index] = String::new();
input_values.set(values);
let new_index = index - 1;
curr_index.set(new_index);
set_focus(new_index);
} else if value.len() == 1 && value.chars().all(char::is_alphabetic) {
values[index] = value;
input_values.set(values);
if index < *length {
let new_index = index + 1;
curr_index.set(new_index);
set_focus(new_index);
}
} else {
values[index] = String::new();
input_values.set(values);
}
}
})
};
let view = {
move || {
html! {
<div
class={
classes!(
"flex",
"flex-col",
"items-center",
"justify-center",
if *loading { "h-[90vh]" } else { "" },
)
}
>
// {
// match game.current_status() {
// Status::New => html!{
// <>
// <svg xmlns="http://www.w3.org/2000/svg" class="w-16 h-16 rotate-ease" viewBox="0 -960 960 960" fill="white">
// <path d="M320-160h320v-120q0-66-47-113t-113-47q-66 0-113 47t-47 113v120Zm160-360q66 0 113-47t47-113v-120H320v120q0 66 47 113t113 47ZM160-80v-80h80v-120q0-61 28.5-114.5T348-480q-51-32-79.5-85.5T240-680v-120h-80v-80h640v80h-80v120q0 61-28.5 114.5T612-480q51 32 79.5 85.5T720-280v120h80v80H160Zm320-80Zm0-640Z"/>
// </svg>
// <p>{"Loading..."}</p>
// </>
// },
// Status::Win(tries) => html!{
// <p>{format!("WIN: {tries}")}</p>
// },
// Status::Lose(tries) => html!{
// <p>{format!("LOSE: {tries}")}</p>
// },
// Status::InProgress => html!{
// <div>
// <p>{"IN PROGRESS"}</p>
// <p>{&game.word}</p>
// </div>
// },
// }
// }
if *loading {
<svg xmlns="http://www.w3.org/2000/svg" class="w-16 h-16 rotate-ease" viewBox="0 -960 960 960" fill="white">
<path d="M320-160h320v-120q0-66-47-113t-113-47q-66 0-113 47t-47 113v120Zm160-360q66 0 113-47t47-113v-120H320v120q0 66 47 113t113 47ZM160-80v-80h80v-120q0-61 28.5-114.5T348-480q-51-32-79.5-85.5T240-680v-120h-80v-80h640v80h-80v120q0 61-28.5 114.5T612-480q51 32 79.5 85.5T720-280v120h80v80H160Zm320-80Zm0-640Z"/>
</svg>
<p>{"Loading..."}</p>
} else {
<div
class={
classes!(
"h-5/6",
"flex",
"flex-col",
"items-center",
"pt-12",
)
}
>
<div class={
classes!(
"mb-12",
)}>
{ for submitted_words.iter().map(|e| {string_to_html(e)})}
</div>
<form
class="mb-4"
>
<div
class={
classes!(
"flex",
"flex-row",
"font-bold",
"text-lg",
"gap-4",
)
}
>
{
if *game_over {
let (text, color) = match *result {
Status::Win(_) => {
("FOUND", "bg-green-600")
},
Status::Lose(_) => {
("WANTED", "bg-red-600")
},
_ => {
("NEW", "bg-gray-600")
},
};
html! (
<div>
<h1>{
text
}</h1>
<ul
class={
classes!(
"flex",
"flex-row",
"gap-4",
"notranslate",
)
}
>
{
word.chars().map(|e|{
let text = e;
html!{
<li
class={
classes!(
"flex",
"items-center"
)
}
>
<span
class={
classes!(
"w-16",
"h-16",
"text-center",
"py-4",
"font-bold",
"text-lg",
{color},
)
}
>
{text}
</span>
</li>
}}).collect::<Html>()
}
</ul>
</div>
)
}
else if !*game_over {
node_refs.iter().enumerate().map(|(index, node_ref)| {
let on_focus = {
let curr_index = curr_index.clone();
Callback::from(move |e: FocusEvent| {
let target = e.target_unchecked_into::<web_sys::HtmlElement>();
if let Some(index) = target.get_attribute("tabindex") {
if let Ok(i) = index.replace('-', "").parse::<usize>() {
curr_index.set(i);
}
}
})
};
let prefix = match index {
0 => String::new(),
_ => "-".to_owned(),
};
html! {
<input
aria-label={format!("letter-{index}")}
onkeyup={on_enter.clone()}
oninput={on_input.clone()}
tabindex={ format!("{prefix}{index}")}
ref={node_ref.clone()}
value={input_values[index].clone()}
onfocus={on_focus.clone()}
class={
classes!(
"w-16",
"h-16",
"text-center",
"bg-gray-600"
)
}
/>
}
}).collect::<Html>()
} else {
html!(<div></div>)
}
}
</div>
</form>
{
if *loading {
html!{<></>}
} else {
html!{
<div
class={
classes!(
"w-full",
"flex",
"justify-end",
)
}
>
<button
aria-label={if *game_over { "Play Again"} else { "Submit"}}
tabindex={format!("-{}",*length + 1)}
class={
classes!(
"w-24",
"h-16",
"text-2xl",
"font-bold",
"rounded-xl",
"flex",
"items-center",
"justify-center",
{if input_values.iter().any(std::string::String::is_empty) && !*game_over {"bg-gray-700"} else {"bg-green-600"}},
)
}
onclick={if input_values.iter().any(std::string::String::is_empty) && !*game_over {on_disabled} else {on_submit}} type="submit">
{
if *game_over {
html!{
<svg xmlns="http://www.w3.org/2000/svg" class="w-12 h-12 rotate-box" viewBox="0 -960 960 960" fill="white">
<path d="M440-122q-121-15-200.5-105.5T160-440q0-66 26-126.5T260-672l57 57q-38 34-57.5 79T240-440q0 88 56 155.5T440-202v80Zm80 0v-80q87-16 143.5-83T720-440q0-100-70-170t-170-70h-3l44 44-56 56-140-140 140-140 56 56-44 44h3q134 0 227 93t93 227q0 121-79.5 211.5T520-122Z"/>
</svg>
}
}
else if input_values.iter().any(std::string::String::is_empty) {
html!{
<svg xmlns="http://www.w3.org/2000/svg" class="w-12 h-12" viewBox="0 -960 960 960" width="24px" fill="white">
<path d="M480-80q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0-80q54 0 104-17.5t92-50.5L228-676q-33 42-50.5 92T160-480q0 134 93 227t227 93Zm252-124q33-42 50.5-92T800-480q0-134-93-227t-227-93q-54 0-104 17.5T284-732l448 448Z"/>
</svg>
}
} else {
html!{
<svg xmlns="http://www.w3.org/2000/svg" class="w-12 h-12" viewBox="0 -960 960 960" fill="white">
<path d="m424-296 282-282-56-56-226 226-114-114-56 56 170 170Zm56 216q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0-80q134 0 227-93t93-227q0-134-93-227t-227-93q-134 0-227 93t-93 227q0 134 93 227t227 93Zm0-320Z"/>
</svg>
}
}
}
</button>
</div>
}
}
}
</div>
}
</div>
}
}
};
view()
}

View File

@ -3,5 +3,3 @@ pub use home::Home;
mod settings;
pub use settings::Settings;
mod game;

4
rustmft.toml Normal file
View File

@ -0,0 +1,4 @@
edition = "2021"
group_imports = "StdExternalCrate"
max_width = 80

3
src/lib.rs Normal file
View File

@ -0,0 +1,3 @@
mod model;
pub use model::game::Game;

140
src/model/charstatus.rs Normal file
View File

@ -0,0 +1,140 @@
use std::collections::HashMap;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)]
pub struct Word(Vec<CharStatus<String>>);
impl Word {
pub fn chars(&self) -> Vec<CharStatus<String>> {
self.0.clone()
}
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)]
pub enum CharStatus<T> {
NotContained(T),
Contained(T),
Match(T),
Unknown,
}
pub(super) fn compare_strings(s1: &str, s2: &str) -> Word {
let mut result: Vec<CharStatus<String>> = Vec::with_capacity(s1.len());
result.resize_with(s1.len(), || CharStatus::Unknown);
let mut s1_char_count: HashMap<char, usize> = HashMap::new();
let mut s2_char_count: HashMap<char, usize> = HashMap::new();
for c in s1.chars() {
*s1_char_count.entry(c).or_insert(0) += 1;
}
for ((c1, c2), res) in s1.chars().zip(s2.chars()).zip(result.iter_mut()) {
if c1 == c2 {
*res = CharStatus::Match(c2.to_string());
*s2_char_count.entry(c2).or_insert(0) += 1;
} else {
*res = CharStatus::Unknown;
}
}
for (res, c2) in result.iter_mut().zip(s2.chars()) {
if res == &CharStatus::Unknown {
let c1_count = s1_char_count.get(&c2).unwrap_or(&0);
let c2_count = s2_char_count.get(&c2).unwrap_or(&0);
if *c1_count > 0 && c1_count > c2_count {
*res = CharStatus::Contained(c2.to_string());
*s2_char_count.entry(c2).or_insert(0) += 1;
} else {
*res = CharStatus::NotContained(c2.to_string());
}
}
}
Word(result)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_compare_strings() {
let source = "HALLO";
let want = Word(vec![
CharStatus::NotContained("0".to_owned()),
CharStatus::NotContained("0".to_owned()),
CharStatus::NotContained("0".to_owned()),
CharStatus::NotContained("0".to_owned()),
CharStatus::NotContained("0".to_owned()),
]);
let input = "00000";
let got = compare_strings(source, input);
assert_eq!(want, got);
let source = "HALLO";
let want = Word(vec![
CharStatus::NotContained("L".to_owned()),
CharStatus::NotContained("L".to_owned()),
CharStatus::Match("L".to_owned()),
CharStatus::Match("L".to_owned()),
CharStatus::NotContained("L".to_owned()),
]);
let input = "LLLLL";
let got = compare_strings(source, input);
assert_eq!(want, got);
let want = Word(vec![
CharStatus::Match("H".to_owned()),
CharStatus::Match("A".to_owned()),
CharStatus::Match("L".to_owned()),
CharStatus::Match("L".to_owned()),
CharStatus::Match("O".to_owned()),
]);
let input = "HALLO";
let got = compare_strings(source, input);
assert_eq!(want, got);
let want = Word(vec![
CharStatus::Match("H".to_owned()),
CharStatus::NotContained("L".to_owned()),
CharStatus::Match("L".to_owned()),
CharStatus::Match("L".to_owned()),
CharStatus::Match("O".to_owned()),
]);
let input = "HLLLO";
let got = compare_strings(source, input);
assert_eq!(want, got);
let want = Word(vec![
CharStatus::Match("H".to_owned()),
CharStatus::Contained("L".to_owned()),
CharStatus::Match("L".to_owned()),
CharStatus::NotContained("I".to_owned()),
CharStatus::NotContained("L".to_owned()),
]);
let input = "HLLIL";
let got = compare_strings(source, input);
assert_eq!(want, got);
let want = Word(vec![
CharStatus::Contained("L".to_owned()),
CharStatus::NotContained("L".to_owned()),
CharStatus::Match("L".to_owned()),
CharStatus::Contained("A".to_owned()),
CharStatus::Match("O".to_owned()),
]);
let input = "LLLAO";
let got = compare_strings(source, input);
assert_eq!(want, got);
}
}

226
src/model/game.rs Normal file
View File

@ -0,0 +1,226 @@
use super::charstatus::{compare_strings, CharStatus, Word};
use serde::{Deserialize, Serialize};
type Attempts = usize;
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct Game {
word: Option<String>,
submitted_words: Vec<Word>,
max_attempts: Attempts,
status: Status,
}
impl Game {
#[must_use]
pub const fn new(max_attempts: Attempts) -> Self {
Self {
word: None,
max_attempts,
submitted_words: Vec::new(),
status: Status::New,
}
}
pub fn start(&mut self, word: &str) {
if self.word.is_none() && self.status == Status::New {
self.status = Status::InProgress;
self.word = Some(word.to_uppercase());
}
}
pub fn submit_answer(&mut self, answer: &str) {
if let Some(ref word) = self.word {
let res = compare_strings(word, &answer.to_uppercase());
self.submitted_words.push(res);
self.status = self.current_status();
}
}
#[must_use]
pub fn current_status(&self) -> Status {
self.word.as_ref().map_or(Status::New, |_| {
let word_count = self.submitted_words.len();
match word_count {
0 => Status::New,
i => self
.submitted_words
.last()
.map_or(Status::Lose(word_count), |words| {
if words
.chars()
.iter()
.all(|v| matches!(v, CharStatus::Match(_)))
{
Status::Win(word_count)
} else if i < self.max_attempts {
Status::InProgress
} else {
Status::Lose(word_count)
}
}),
}
})
}
#[must_use]
pub fn get_submitted_words(&self) -> Vec<Word> {
self.submitted_words.clone()
}
}
impl Default for Game {
fn default() -> Self {
Self::new(5)
}
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
#[allow(clippy::module_name_repetitions)]
pub enum Status {
New,
Win(Attempts),
Lose(Attempts),
InProgress,
}
#[cfg(test)]
mod test {
use super::*;
use rand::Rng;
use std::iter;
#[test]
fn new() {
assert_eq!(
Game {
word: None,
max_attempts: 5,
submitted_words: Vec::new(),
status: Status::New,
},
Game::default()
);
}
#[test]
#[allow(clippy::field_reassign_with_default)]
fn start() {
let word: String = random_word(5);
let want = Game {
word: Some(word.to_uppercase()),
submitted_words: Vec::new(),
max_attempts: 5,
status: Status::InProgress,
};
let mut got = Game::default();
got.start(&word);
assert_eq!(got, want);
let mut got = Game::default();
got.word = Some(word.to_uppercase());
assert_ne!(got, want);
}
#[test]
fn submit_answer() {
let word = "hallo";
let answer = "hello";
let want = Game {
word: Some(word.to_uppercase()),
submitted_words: vec![compare_strings(
&word.to_uppercase(),
&answer.to_uppercase(),
)],
max_attempts: 5,
status: Status::InProgress,
};
let mut got = Game::default();
got.start(word);
got.submit_answer(answer);
assert_eq!(got, want);
}
#[test]
fn current_status() {
let mut got = Game::default();
assert_eq!(got.current_status(), Status::New);
let word = "hallo";
let want = Game {
word: Some(word.to_uppercase()),
submitted_words: Vec::new(),
max_attempts: 5,
status: Status::InProgress,
};
got.start(word);
assert_eq!(got, want);
let answer = "hello";
let want = Game {
word: Some(word.to_uppercase()),
submitted_words: vec![compare_strings(
&word.to_uppercase(),
&answer.to_uppercase(),
)],
max_attempts: 5,
status: Status::InProgress,
};
got.submit_answer(answer);
assert_eq!(got, want);
got.submit_answer(answer);
got.submit_answer(answer);
got.submit_answer(answer);
got.submit_answer(answer);
assert_eq!(got.current_status(), Status::Lose(5));
let mut got = Game::default();
got.start(word);
got.submit_answer(word);
assert_eq!(got.current_status(), Status::Win(1));
let mut got = Game::default();
got.start(word);
got.submit_answer(answer);
got.submit_answer(answer);
got.submit_answer(word);
assert_eq!(got.current_status(), Status::Win(3));
}
#[test]
fn get_submitted_words() {
let word = "hallo";
let answer = "hello";
let mut got = Game::default();
got.start(word);
got.submit_answer(answer);
let want = vec![compare_strings(
&word.to_uppercase(),
&answer.to_uppercase(),
)];
assert_eq!(got.get_submitted_words(), want);
}
fn random_word(len: usize) -> String {
let mut rng = rand::thread_rng();
let word: String = iter::repeat(())
.map(|()| rng.sample(rand::distributions::Alphanumeric))
.map(char::from)
.filter(char::is_ascii_lowercase)
.take(len)
.collect();
word
}
}

2
src/model/mod.rs Normal file
View File

@ -0,0 +1,2 @@
mod charstatus;
pub mod game;