chore: removes old pages

feat: adds word struct
This commit is contained in:
itsscb 2024-09-09 14:39:19 +02:00
parent 5e1c5b3f07
commit a8114230b8
11 changed files with 698 additions and 990 deletions

1
Cargo.lock generated
View File

@ -2856,6 +2856,7 @@ dependencies = [
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
"wordl",
"yew",
"yew-router",
"yewdux",

View File

@ -20,4 +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 = "../"}

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;

View File

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

View File

@ -2,6 +2,15 @@ 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),
@ -10,7 +19,7 @@ pub enum CharStatus<T> {
Unknown,
}
pub(super) fn compare_strings(s1: &str, s2: &str) -> Vec<CharStatus<String>> {
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);
@ -44,7 +53,7 @@ pub(super) fn compare_strings(s1: &str, s2: &str) -> Vec<CharStatus<String>> {
}
}
result
Word(result)
}
#[cfg(test)]
@ -55,74 +64,74 @@ mod test {
fn test_compare_strings() {
let source = "HALLO";
let want = vec![
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 = vec![
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 = vec![
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 = vec![
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 = vec![
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 = vec![
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);

View File

@ -1,4 +1,4 @@
use super::charstatus::{compare_strings, CharStatus};
use super::charstatus::{compare_strings, CharStatus, Word};
use serde::{Deserialize, Serialize};
type Attempts = usize;
@ -6,7 +6,7 @@ type Attempts = usize;
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct Game {
word: Option<String>,
submitted_words: Vec<Vec<CharStatus<String>>>,
submitted_words: Vec<Word>,
max_attempts: Attempts,
status: Status,
}
@ -47,7 +47,11 @@ impl Game {
.submitted_words
.last()
.map_or(Status::Lose(word_count), |words| {
if words.iter().all(|v| matches!(v, CharStatus::Match(_))) {
if words
.chars()
.iter()
.all(|v| matches!(v, CharStatus::Match(_)))
{
Status::Win(word_count)
} else if i < self.max_attempts {
Status::InProgress
@ -58,6 +62,11 @@ impl Game {
}
})
}
#[must_use]
pub fn get_submitted_words(&self) -> Vec<Word> {
self.submitted_words.clone()
}
}
impl Default for Game {
@ -188,6 +197,22 @@ mod test {
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(())