Merge pull request #30 from itsscb/feature
feat(frontend): improves game model and prepares for refactoring and storage
This commit is contained in:
commit
1becef955b
@ -1,14 +1,27 @@
|
|||||||
use rand::seq::SliceRandom;
|
// use rand::seq::SliceRandom;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use crate::CharStatus;
|
use crate::CharStatus;
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
const MAX_TRIES: usize = 5;
|
||||||
struct Game {
|
|
||||||
word: String,
|
// #[derive(Debug, Serialize, Deserialize, Clone)]
|
||||||
submitted_words: Vec<Vec<CharStatus<String>>>,
|
// struct Games(Vec<Game>);
|
||||||
result: GameResult,
|
|
||||||
}
|
// 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)]
|
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct WordList {
|
pub struct WordList {
|
||||||
@ -22,43 +35,90 @@ impl WordList {
|
|||||||
pub fn from_json(s: &str) -> Self {
|
pub fn from_json(s: &str) -> Self {
|
||||||
serde_json::from_str(s).map_or(Self::new(), |w| w)
|
serde_json::from_str(s).map_or(Self::new(), |w| w)
|
||||||
}
|
}
|
||||||
pub fn to_json(&self) -> String {
|
// pub fn to_json(&self) -> String {
|
||||||
serde_json::to_string_pretty(self).map_or(String::new(), |w| w)
|
// serde_json::to_string_pretty(self).map_or(String::new(), |w| w)
|
||||||
}
|
// }
|
||||||
pub fn get_word(&self) -> String {
|
// pub fn get_word(&self) -> String {
|
||||||
let mut rng = rand::thread_rng();
|
// let mut rng = rand::thread_rng();
|
||||||
self.words
|
// self.words
|
||||||
.choose(&mut rng)
|
// .choose(&mut rng)
|
||||||
.map_or_else(String::new, |w| (*w).to_string())
|
// .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 {
|
impl Game {
|
||||||
#[allow(dead_code)]
|
pub const fn new() -> Self {
|
||||||
pub fn new(word: String, submitted_words: Vec<Vec<CharStatus<String>>>) -> Self {
|
|
||||||
let result = submitted_words
|
|
||||||
.clone()
|
|
||||||
.into_iter()
|
|
||||||
.last()
|
|
||||||
.map_or(GameResult::Lose, |w| {
|
|
||||||
if w.iter().all(|v| matches!(v, CharStatus::Match(_))) {
|
|
||||||
GameResult::Win
|
|
||||||
} else {
|
|
||||||
GameResult::Lose
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
word,
|
word: None,
|
||||||
submitted_words,
|
tries: 0,
|
||||||
result,
|
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();
|
||||||
|
if self.tries == 0 {
|
||||||
|
Status::New
|
||||||
|
} else if self.tries < MAX_TRIES {
|
||||||
|
if self
|
||||||
|
.submitted_words
|
||||||
|
.last()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.all(|v| matches!(v, CharStatus::Match(_)))
|
||||||
|
{
|
||||||
|
Status::Win(word_count)
|
||||||
|
} else {
|
||||||
|
Status::InProgress
|
||||||
|
}
|
||||||
|
} else if self
|
||||||
|
.submitted_words
|
||||||
|
.last()
|
||||||
|
.unwrap()
|
||||||
|
.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)]
|
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
|
||||||
#[allow(clippy::module_name_repetitions)]
|
#[allow(clippy::module_name_repetitions)]
|
||||||
pub enum GameResult {
|
pub enum Status {
|
||||||
Win,
|
New,
|
||||||
Lose,
|
Win(Tries),
|
||||||
|
Lose(Tries),
|
||||||
|
InProgress,
|
||||||
}
|
}
|
||||||
|
@ -5,7 +5,7 @@ use web_sys::HtmlElement;
|
|||||||
use yew::prelude::*;
|
use yew::prelude::*;
|
||||||
use yew::{classes, function_component, Callback, Html};
|
use yew::{classes, function_component, Callback, Html};
|
||||||
|
|
||||||
use crate::pages::game::GameResult;
|
use crate::pages::game::{Game, Status};
|
||||||
use crate::CharStatus;
|
use crate::CharStatus;
|
||||||
|
|
||||||
use super::game::WordList;
|
use super::game::WordList;
|
||||||
@ -17,7 +17,7 @@ static MAX_TRIES: usize = 5;
|
|||||||
fn set_focus(index: usize) {
|
fn set_focus(index: usize) {
|
||||||
let prefix = match index {
|
let prefix = match index {
|
||||||
0 => "",
|
0 => "",
|
||||||
_ => "-"
|
_ => "-",
|
||||||
};
|
};
|
||||||
if let Some(w) = web_sys::window() {
|
if let Some(w) = web_sys::window() {
|
||||||
if let Some(d) = w.document() {
|
if let Some(d) = w.document() {
|
||||||
@ -111,7 +111,7 @@ fn fetch_new_word(
|
|||||||
game_over: &UseStateHandle<bool>,
|
game_over: &UseStateHandle<bool>,
|
||||||
length: &UseStateHandle<usize>,
|
length: &UseStateHandle<usize>,
|
||||||
node_refs: &UseStateHandle<Vec<NodeRef>>,
|
node_refs: &UseStateHandle<Vec<NodeRef>>,
|
||||||
result: &UseStateHandle<GameResult>,
|
result: &UseStateHandle<Status>,
|
||||||
) {
|
) {
|
||||||
let loading = loading.clone();
|
let loading = loading.clone();
|
||||||
let submitted_words = submitted_words.clone();
|
let submitted_words = submitted_words.clone();
|
||||||
@ -133,7 +133,7 @@ fn fetch_new_word(
|
|||||||
word.set(w.to_uppercase());
|
word.set(w.to_uppercase());
|
||||||
submitted_words.set(Vec::with_capacity(MAX_TRIES));
|
submitted_words.set(Vec::with_capacity(MAX_TRIES));
|
||||||
game_over.set(false);
|
game_over.set(false);
|
||||||
result.set(GameResult::Lose);
|
result.set(Status::New);
|
||||||
loading.set(false);
|
loading.set(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -153,8 +153,23 @@ fn fetch_words(state: &UseStateHandle<WordList>) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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]
|
#[function_component]
|
||||||
pub fn Home() -> Html {
|
pub fn Home() -> Html {
|
||||||
|
let game: UseStateHandle<Game> = use_state(Game::new);
|
||||||
let word: UseStateHandle<String> = use_state(String::new);
|
let word: UseStateHandle<String> = use_state(String::new);
|
||||||
let loading: UseStateHandle<bool> = use_state(|| true);
|
let loading: UseStateHandle<bool> = use_state(|| true);
|
||||||
let curr_index: UseStateHandle<usize> = use_state(|| 0usize);
|
let curr_index: UseStateHandle<usize> = use_state(|| 0usize);
|
||||||
@ -167,9 +182,10 @@ pub fn Home() -> Html {
|
|||||||
let input_values: UseStateHandle<Vec<String>> = use_state(|| vec![String::new(); *length]);
|
let input_values: UseStateHandle<Vec<String>> = use_state(|| vec![String::new(); *length]);
|
||||||
let game_over = use_state(|| false);
|
let game_over = use_state(|| false);
|
||||||
|
|
||||||
let result = use_state(|| GameResult::Lose);
|
let result = use_state(|| Status::New);
|
||||||
|
|
||||||
{
|
{
|
||||||
|
let game = game.clone();
|
||||||
let handle = word.clone();
|
let handle = word.clone();
|
||||||
let loading = loading.clone();
|
let loading = loading.clone();
|
||||||
|
|
||||||
@ -181,6 +197,7 @@ pub fn Home() -> Html {
|
|||||||
let result = result.clone();
|
let result = result.clone();
|
||||||
|
|
||||||
use_effect_with((), move |()| {
|
use_effect_with((), move |()| {
|
||||||
|
new_game(&game);
|
||||||
fetch_new_word(
|
fetch_new_word(
|
||||||
&handle,
|
&handle,
|
||||||
&loading,
|
&loading,
|
||||||
@ -212,7 +229,7 @@ pub fn Home() -> Html {
|
|||||||
.iter()
|
.iter()
|
||||||
.all(|v| matches!(v, CharStatus::Match(_)))
|
.all(|v| matches!(v, CharStatus::Match(_)))
|
||||||
{
|
{
|
||||||
result.set(GameResult::Win);
|
result.set(Status::Win(submitted_words.iter().count()));
|
||||||
}
|
}
|
||||||
game_over.set(true);
|
game_over.set(true);
|
||||||
}
|
}
|
||||||
@ -224,13 +241,19 @@ pub fn Home() -> Html {
|
|||||||
let input_values = input_values.clone();
|
let input_values = input_values.clone();
|
||||||
|
|
||||||
Callback::from(move |_e: MouseEvent| {
|
Callback::from(move |_e: MouseEvent| {
|
||||||
let index = input_values.iter().enumerate().find(|(_, v)| v.is_empty()).map_or(0, |(i,_)| i);
|
let index = input_values
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.find(|(_, v)| v.is_empty())
|
||||||
|
.map_or(0, |(i, _)| i);
|
||||||
set_focus(index);
|
set_focus(index);
|
||||||
curr_index.set(index);
|
curr_index.set(index);
|
||||||
})
|
})
|
||||||
};
|
};
|
||||||
|
|
||||||
let on_submit = {
|
let on_submit = {
|
||||||
|
let game = game.clone();
|
||||||
|
|
||||||
let input_values = input_values.clone();
|
let input_values = input_values.clone();
|
||||||
let submitted_words = submitted_words.clone();
|
let submitted_words = submitted_words.clone();
|
||||||
let game_over = game_over.clone();
|
let game_over = game_over.clone();
|
||||||
@ -268,6 +291,10 @@ pub fn Home() -> Html {
|
|||||||
if !values.iter().all(|v| !v.is_empty()) {
|
if !values.iter().all(|v| !v.is_empty()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
let mut g = (*game).clone();
|
||||||
|
g.submit_answer(&input_values);
|
||||||
|
game.set(g);
|
||||||
|
|
||||||
let mut new_items = (*submitted_words).clone();
|
let mut new_items = (*submitted_words).clone();
|
||||||
new_items.push(crate::compare_strings(&word, &values.join("")));
|
new_items.push(crate::compare_strings(&word, &values.join("")));
|
||||||
submitted_words.set(new_items);
|
submitted_words.set(new_items);
|
||||||
@ -367,6 +394,30 @@ pub fn Home() -> Html {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
|
// {
|
||||||
|
// 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 {
|
if *loading {
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" class="w-16 h-16 rotate-ease" viewBox="0 -960 960 960" fill="white">
|
<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"/>
|
<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"/>
|
||||||
@ -385,7 +436,7 @@ pub fn Home() -> Html {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
|
|
||||||
<div class={
|
<div class={
|
||||||
classes!(
|
classes!(
|
||||||
"mb-12",
|
"mb-12",
|
||||||
@ -408,14 +459,17 @@ pub fn Home() -> Html {
|
|||||||
>
|
>
|
||||||
{
|
{
|
||||||
if *game_over {
|
if *game_over {
|
||||||
|
|
||||||
let (text, color) = match *result {
|
let (text, color) = match *result {
|
||||||
GameResult::Win => {
|
Status::Win(_) => {
|
||||||
("FOUND", "bg-green-600")
|
("FOUND", "bg-green-600")
|
||||||
},
|
},
|
||||||
GameResult::Lose => {
|
Status::Lose(_) => {
|
||||||
("WANTED", "bg-red-600")
|
("WANTED", "bg-red-600")
|
||||||
}
|
},
|
||||||
|
_ => {
|
||||||
|
("NEW", "bg-gray-600")
|
||||||
|
},
|
||||||
};
|
};
|
||||||
html! (
|
html! (
|
||||||
<div>
|
<div>
|
||||||
@ -434,7 +488,7 @@ pub fn Home() -> Html {
|
|||||||
>
|
>
|
||||||
{
|
{
|
||||||
word.chars().map(|e|{
|
word.chars().map(|e|{
|
||||||
|
|
||||||
let text = e;
|
let text = e;
|
||||||
html!{
|
html!{
|
||||||
<li
|
<li
|
||||||
@ -471,7 +525,7 @@ pub fn Home() -> Html {
|
|||||||
node_refs.iter().enumerate().map(|(index, node_ref)| {
|
node_refs.iter().enumerate().map(|(index, node_ref)| {
|
||||||
let on_focus = {
|
let on_focus = {
|
||||||
let curr_index = curr_index.clone();
|
let curr_index = curr_index.clone();
|
||||||
|
|
||||||
Callback::from(move |e: FocusEvent| {
|
Callback::from(move |e: FocusEvent| {
|
||||||
let target = e.target_unchecked_into::<web_sys::HtmlElement>();
|
let target = e.target_unchecked_into::<web_sys::HtmlElement>();
|
||||||
if let Some(index) = target.get_attribute("tabindex") {
|
if let Some(index) = target.get_attribute("tabindex") {
|
||||||
@ -479,7 +533,7 @@ pub fn Home() -> Html {
|
|||||||
curr_index.set(i);
|
curr_index.set(i);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
})
|
})
|
||||||
};
|
};
|
||||||
let prefix = match index {
|
let prefix = match index {
|
||||||
@ -523,7 +577,7 @@ pub fn Home() -> Html {
|
|||||||
"w-full",
|
"w-full",
|
||||||
"flex",
|
"flex",
|
||||||
"justify-end",
|
"justify-end",
|
||||||
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
@ -571,7 +625,7 @@ pub fn Home() -> Html {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
|
Loading…
x
Reference in New Issue
Block a user