Refactorings, fix bug where board doesn't update

Also silence warnings related to unused code since the front-end and
back-end share some code.
This commit is contained in:
Stephen Seo 2022-05-03 13:17:54 +09:00
parent 4331a20daa
commit f4f3ad7a5b
6 changed files with 51 additions and 32 deletions

View file

@ -683,7 +683,8 @@ impl DBHandler {
} }
// TODO maybe handle "opponent_disconnected" case // TODO maybe handle "opponent_disconnected" case
let row_result: Result<(String, i64, Option<u32>, Option<u32>, String), RusqliteError> = conn.query_row( type ResultTuple = (String, i64, Option<u32>, Option<u32>, String);
let row_result: Result<ResultTuple, RusqliteError> = conn.query_row(
"SELECT games.board, games.status, games.cyan_player, games.magenta_player, games.turn_time_start FROM games JOIN players WHERE players.id = ? AND games.id = players.game_id;", "SELECT games.board, games.status, games.cyan_player, games.magenta_player, games.turn_time_start FROM games JOIN players WHERE players.id = ? AND games.id = players.game_id;",
[player_id], [player_id],
|row| { |row| {

View file

@ -15,6 +15,7 @@ use crate::state::{board_deep_clone, BoardState, BoardType, Turn};
const AI_THIRD_MAX_UTILITY: f64 = 0.89; const AI_THIRD_MAX_UTILITY: f64 = 0.89;
#[allow(dead_code)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)] #[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum AIDifficulty { pub enum AIDifficulty {
Easy, Easy,

View file

@ -9,25 +9,36 @@
pub const ROWS: u8 = 8; pub const ROWS: u8 = 8;
pub const COLS: u8 = 7; pub const COLS: u8 = 7;
#[allow(dead_code)]
pub const INFO_TEXT_MAX_ITEMS: u32 = 100; pub const INFO_TEXT_MAX_ITEMS: u32 = 100;
pub const AI_EASY_MAX_CHOICES: usize = 5; pub const AI_EASY_MAX_CHOICES: usize = 5;
pub const AI_NORMAL_MAX_CHOICES: usize = 3; pub const AI_NORMAL_MAX_CHOICES: usize = 3;
#[allow(dead_code)]
pub const AI_CHOICE_DURATION_MILLIS: i32 = 1000; pub const AI_CHOICE_DURATION_MILLIS: i32 = 1000;
#[allow(dead_code)]
pub const PLAYER_COUNT_LIMIT: usize = 1000; pub const PLAYER_COUNT_LIMIT: usize = 1000;
#[allow(dead_code)]
pub const TURN_SECONDS: u64 = 25; pub const TURN_SECONDS: u64 = 25;
#[allow(dead_code)]
pub const GAME_CLEANUP_TIMEOUT: u64 = (TURN_SECONDS + 1) * ((ROWS * COLS) as u64 + 5u64); pub const GAME_CLEANUP_TIMEOUT: u64 = (TURN_SECONDS + 1) * ((ROWS * COLS) as u64 + 5u64);
#[allow(dead_code)]
pub const PLAYER_CLEANUP_TIMEOUT: u64 = 300; pub const PLAYER_CLEANUP_TIMEOUT: u64 = 300;
#[allow(dead_code)]
pub const BACKEND_TICK_DURATION_MILLIS: i32 = 500; pub const BACKEND_TICK_DURATION_MILLIS: i32 = 500;
#[allow(dead_code)]
pub const BACKEND_CLEANUP_INTERVAL_SECONDS: u64 = 120; pub const BACKEND_CLEANUP_INTERVAL_SECONDS: u64 = 120;
#[allow(dead_code)]
pub const BACKEND_PHRASE_MAX_LENGTH: usize = 128; pub const BACKEND_PHRASE_MAX_LENGTH: usize = 128;
// TODO: Change this to "https://asdm.seodisparate.com/api" when backend is installed // TODO: Change this to "https://asdm.seodisparate.com/api" when backend is installed
#[allow(dead_code)]
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
pub const BACKEND_URL: &str = "http://testlocalhost/api"; pub const BACKEND_URL: &str = "http://testlocalhost/api";
#[allow(dead_code)]
#[cfg(not(debug_assertions))] #[cfg(not(debug_assertions))]
pub const BACKEND_URL: &str = "https://asdm.seodisparate.com/api"; pub const BACKEND_URL: &str = "https://asdm.seodisparate.com/api";

View file

@ -10,7 +10,7 @@ use js_sys::{Function, JsString, Promise};
use std::collections::HashMap; use std::collections::HashMap;
use wasm_bindgen::{JsCast, JsValue}; use wasm_bindgen::{JsCast, JsValue};
use wasm_bindgen_futures::JsFuture; use wasm_bindgen_futures::JsFuture;
use web_sys::{window, Document, Request, RequestInit, Window}; use web_sys::{window, Document, Window};
use crate::constants::BACKEND_URL; use crate::constants::BACKEND_URL;
@ -119,34 +119,6 @@ pub fn element_has_class(document: &Document, id: &str, class: &str) -> Result<b
Ok(element_class.contains(class)) Ok(element_class.contains(class))
} }
pub fn create_json_request(target_url: &str, json_body: &str) -> Result<Request, String> {
let mut req_init: RequestInit = RequestInit::new();
req_init.body(Some(&JsValue::from_str(json_body)));
req_init.method("POST");
// TODO omit the NoCors when hosted on website
req_init.mode(web_sys::RequestMode::NoCors);
// req_init.headers(
// &JsValue::from_str("{'Content-Type': 'application/json'}"),
// &JsValue::from_serde("{'Content-Type': 'application/json'}")
// .map_err(|e| format!("{}", e))?,
// &JsValue::from_serde("'headers': { 'Content-Type': 'application/json' }")
// .map_err(|e| format!("{}", e))?,
// );
let request: Request =
Request::new_with_str_and_init(target_url, &req_init).map_err(|e| format!("{:?}", e))?;
request
.headers()
.set("Content-Type", "application/json")
.map_err(|e| format!("{:?}", e))?;
request
.headers()
.set("Accept", "application/json")
.map_err(|e| format!("{:?}", e))?;
Ok(request)
}
pub async fn send_to_backend(entries: HashMap<String, String>) -> Result<String, String> { pub async fn send_to_backend(entries: HashMap<String, String>) -> Result<String, String> {
let mut send_json_string = String::from("{"); let mut send_json_string = String::from("{");
for (key, value) in entries { for (key, value) in entries {

View file

@ -17,6 +17,7 @@ use std::collections::hash_set::HashSet;
use std::fmt::Display; use std::fmt::Display;
use std::rc::Rc; use std::rc::Rc;
#[allow(dead_code)]
#[derive(Clone, Debug, PartialEq, Eq)] #[derive(Clone, Debug, PartialEq, Eq)]
pub enum GameState { pub enum GameState {
MainMenu, MainMenu,
@ -32,6 +33,7 @@ pub enum GameState {
} }
impl GameState { impl GameState {
#[allow(dead_code)]
pub fn is_networked_multiplayer(&self) -> bool { pub fn is_networked_multiplayer(&self) -> bool {
matches!( matches!(
*self, *self,
@ -44,6 +46,7 @@ impl GameState {
) )
} }
#[allow(dead_code)]
pub fn set_networked_paired(&mut self) { pub fn set_networked_paired(&mut self) {
if let GameState::NetworkedMultiplayer { if let GameState::NetworkedMultiplayer {
ref mut paired, ref mut paired,
@ -56,6 +59,7 @@ impl GameState {
} }
} }
#[allow(dead_code)]
pub fn get_networked_current_side(&self) -> Option<Turn> { pub fn get_networked_current_side(&self) -> Option<Turn> {
if let GameState::NetworkedMultiplayer { if let GameState::NetworkedMultiplayer {
paired: _, paired: _,
@ -70,6 +74,7 @@ impl GameState {
} }
} }
#[allow(dead_code)]
pub fn set_networked_current_side(&mut self, side: Option<Turn>) { pub fn set_networked_current_side(&mut self, side: Option<Turn>) {
if let GameState::NetworkedMultiplayer { if let GameState::NetworkedMultiplayer {
paired: _, paired: _,
@ -82,6 +87,7 @@ impl GameState {
} }
} }
#[allow(dead_code)]
pub fn get_current_turn(&self) -> Turn { pub fn get_current_turn(&self) -> Turn {
if let GameState::SinglePlayer(turn, _) = *self { if let GameState::SinglePlayer(turn, _) = *self {
turn turn
@ -98,6 +104,7 @@ impl GameState {
} }
} }
#[allow(dead_code)]
pub fn set_networked_current_turn(&mut self, turn: Turn) { pub fn set_networked_current_turn(&mut self, turn: Turn) {
if let GameState::NetworkedMultiplayer { if let GameState::NetworkedMultiplayer {
paired: _, paired: _,
@ -110,6 +117,7 @@ impl GameState {
} }
} }
#[allow(dead_code)]
pub fn get_phrase(&self) -> Option<String> { pub fn get_phrase(&self) -> Option<String> {
if let GameState::NetworkedMultiplayer { if let GameState::NetworkedMultiplayer {
paired: _, paired: _,
@ -124,6 +132,7 @@ impl GameState {
} }
} }
#[allow(dead_code)]
pub fn get_singleplayer_current_side(&self) -> Option<Turn> { pub fn get_singleplayer_current_side(&self) -> Option<Turn> {
if let GameState::SinglePlayer(turn, _) = *self { if let GameState::SinglePlayer(turn, _) = *self {
Some(turn) Some(turn)
@ -154,6 +163,7 @@ impl From<MainMenuMessage> for GameState {
} }
} }
#[allow(dead_code)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)] #[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum BoardState { pub enum BoardState {
Empty, Empty,
@ -191,10 +201,12 @@ impl From<Turn> for BoardState {
} }
impl BoardState { impl BoardState {
#[allow(dead_code)]
pub fn is_empty(&self) -> bool { pub fn is_empty(&self) -> bool {
*self == BoardState::Empty *self == BoardState::Empty
} }
#[allow(dead_code)]
pub fn is_win(self) -> bool { pub fn is_win(self) -> bool {
match self { match self {
BoardState::Empty | BoardState::Cyan | BoardState::Magenta => false, BoardState::Empty | BoardState::Cyan | BoardState::Magenta => false,
@ -202,6 +214,7 @@ impl BoardState {
} }
} }
#[allow(dead_code)]
pub fn into_win(self) -> Self { pub fn into_win(self) -> Self {
match self { match self {
BoardState::Empty => BoardState::Empty, BoardState::Empty => BoardState::Empty,
@ -210,8 +223,9 @@ impl BoardState {
} }
} }
pub fn from_win(&self) -> Self { #[allow(dead_code, clippy::wrong_self_convention)]
match *self { pub fn from_win(self) -> Self {
match self {
BoardState::Empty => BoardState::Empty, BoardState::Empty => BoardState::Empty,
BoardState::Cyan | BoardState::CyanWin => BoardState::Cyan, BoardState::Cyan | BoardState::CyanWin => BoardState::Cyan,
BoardState::Magenta | BoardState::MagentaWin => BoardState::Magenta, BoardState::Magenta | BoardState::MagentaWin => BoardState::Magenta,
@ -219,6 +233,7 @@ impl BoardState {
} }
} }
#[allow(dead_code)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)] #[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Turn { pub enum Turn {
CyanPlayer, CyanPlayer,
@ -244,6 +259,7 @@ impl From<BoardState> for Turn {
} }
impl Turn { impl Turn {
#[allow(dead_code)]
pub fn get_color(&self) -> &str { pub fn get_color(&self) -> &str {
match *self { match *self {
Turn::CyanPlayer => "cyan", Turn::CyanPlayer => "cyan",
@ -261,6 +277,7 @@ impl Turn {
pub type BoardType = [Rc<Cell<BoardState>>; 56]; pub type BoardType = [Rc<Cell<BoardState>>; 56];
#[allow(dead_code)]
pub fn new_empty_board() -> BoardType { pub fn new_empty_board() -> BoardType {
[ [
Rc::new(Cell::new(BoardState::default())), Rc::new(Cell::new(BoardState::default())),
@ -322,6 +339,7 @@ pub fn new_empty_board() -> BoardType {
] ]
} }
#[allow(dead_code)]
pub fn board_deep_clone(board: &BoardType) -> BoardType { pub fn board_deep_clone(board: &BoardType) -> BoardType {
let cloned_board = new_empty_board(); let cloned_board = new_empty_board();
for i in 0..board.len() { for i in 0..board.len() {
@ -333,6 +351,7 @@ pub fn board_deep_clone(board: &BoardType) -> BoardType {
pub type PlacedType = [Rc<Cell<bool>>; 56]; pub type PlacedType = [Rc<Cell<bool>>; 56];
#[allow(dead_code)]
pub fn new_placed() -> PlacedType { pub fn new_placed() -> PlacedType {
[ [
Rc::new(Cell::new(false)), Rc::new(Cell::new(false)),
@ -394,6 +413,7 @@ pub fn new_placed() -> PlacedType {
] ]
} }
#[allow(dead_code)]
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
pub struct SharedState { pub struct SharedState {
pub board: BoardType, pub board: BoardType,
@ -416,6 +436,7 @@ impl Default for SharedState {
// This enum moved from yew_components module so that this module would have no // This enum moved from yew_components module so that this module would have no
// dependencies on the yew_components module // dependencies on the yew_components module
#[allow(dead_code)]
#[derive(Clone, Debug, PartialEq, Eq)] #[derive(Clone, Debug, PartialEq, Eq)]
pub enum MainMenuMessage { pub enum MainMenuMessage {
SinglePlayer(Turn, AIDifficulty), SinglePlayer(Turn, AIDifficulty),
@ -423,6 +444,7 @@ pub enum MainMenuMessage {
NetworkedMultiplayer(Option<String>), NetworkedMultiplayer(Option<String>),
} }
#[allow(dead_code)]
pub fn new_string_board() -> String { pub fn new_string_board() -> String {
let mut board = String::with_capacity(56); let mut board = String::with_capacity(56);
for _i in 0..56 { for _i in 0..56 {
@ -431,6 +453,7 @@ pub fn new_string_board() -> String {
board board
} }
#[allow(dead_code)]
pub fn board_from_string(board_string: String) -> BoardType { pub fn board_from_string(board_string: String) -> BoardType {
let board = new_empty_board(); let board = new_empty_board();
@ -450,6 +473,7 @@ pub fn board_from_string(board_string: String) -> BoardType {
/// Returns the board as a String, and None if game has not ended, Empty if game /// Returns the board as a String, and None if game has not ended, Empty if game
/// ended in a draw, or a player if that player has won /// ended in a draw, or a player if that player has won
#[allow(dead_code)]
pub fn string_from_board(board: &BoardType, placed: usize) -> (String, Option<BoardState>) { pub fn string_from_board(board: &BoardType, placed: usize) -> (String, Option<BoardState>) {
let mut board_string = String::with_capacity(56); let mut board_string = String::with_capacity(56);
@ -537,6 +561,7 @@ pub fn string_from_board(board: &BoardType, placed: usize) -> (String, Option<Bo
} }
} }
#[allow(dead_code)]
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
pub struct PairingRequestResponse { pub struct PairingRequestResponse {
pub r#type: String, pub r#type: String,
@ -545,6 +570,7 @@ pub struct PairingRequestResponse {
pub color: Option<String>, pub color: Option<String>,
} }
#[allow(dead_code)]
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
pub struct PairingStatusResponse { pub struct PairingStatusResponse {
pub r#type: String, pub r#type: String,
@ -552,6 +578,7 @@ pub struct PairingStatusResponse {
pub color: Option<String>, pub color: Option<String>,
} }
#[allow(dead_code)]
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
pub struct GameStateResponse { pub struct GameStateResponse {
pub r#type: String, pub r#type: String,
@ -561,6 +588,7 @@ pub struct GameStateResponse {
pub updated_time: Option<String>, pub updated_time: Option<String>,
} }
#[allow(dead_code)]
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
pub struct PlaceTokenResponse { pub struct PlaceTokenResponse {
pub r#type: String, pub r#type: String,
@ -568,12 +596,14 @@ pub struct PlaceTokenResponse {
pub board: String, pub board: String,
} }
#[allow(dead_code)]
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
pub struct SendEmoteRequestResponse { pub struct SendEmoteRequestResponse {
pub r#type: String, pub r#type: String,
pub status: String, pub status: String,
} }
#[allow(dead_code)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)] #[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum NetworkedGameState { pub enum NetworkedGameState {
CyanTurn, CyanTurn,
@ -587,6 +617,7 @@ pub enum NetworkedGameState {
UnknownID, UnknownID,
} }
#[allow(dead_code)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)] #[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum PlacedEnum { pub enum PlacedEnum {
Accepted, Accepted,
@ -595,6 +626,7 @@ pub enum PlacedEnum {
Other(NetworkedGameState), Other(NetworkedGameState),
} }
#[allow(dead_code)]
#[derive(Copy, Clone, PartialEq, Eq, Debug)] #[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum EmoteEnum { pub enum EmoteEnum {
Smile, Smile,

View file

@ -1589,6 +1589,7 @@ impl Component for Wrapper {
match networked_game_state { match networked_game_state {
NetworkedGameState::CyanTurn => { NetworkedGameState::CyanTurn => {
if current_game_state.get_current_turn() != Turn::CyanPlayer { if current_game_state.get_current_turn() != Turn::CyanPlayer {
self.board_updated_time.take();
current_game_state.set_networked_current_turn(Turn::CyanPlayer); current_game_state.set_networked_current_turn(Turn::CyanPlayer);
shared.game_state.replace(current_game_state.clone()); shared.game_state.replace(current_game_state.clone());
append_to_info_text( append_to_info_text(
@ -1613,6 +1614,7 @@ impl Component for Wrapper {
} }
NetworkedGameState::MagentaTurn => { NetworkedGameState::MagentaTurn => {
if current_game_state.get_current_turn() != Turn::MagentaPlayer { if current_game_state.get_current_turn() != Turn::MagentaPlayer {
self.board_updated_time.take();
current_game_state current_game_state
.set_networked_current_turn(Turn::MagentaPlayer); .set_networked_current_turn(Turn::MagentaPlayer);
shared.game_state.replace(current_game_state.clone()); shared.game_state.replace(current_game_state.clone());