]> git.seodisparate.com - EN605.607.81.SP22_ASDM_Project/commitdiff
Refactorings, fix bug where board doesn't update
authorStephen Seo <seo.disparate@gmail.com>
Tue, 3 May 2022 04:17:54 +0000 (13:17 +0900)
committerStephen Seo <seo.disparate@gmail.com>
Tue, 3 May 2022 04:18:07 +0000 (13:18 +0900)
Also silence warnings related to unused code since the front-end and
back-end share some code.

back_end/src/db_handler.rs
front_end/src/ai.rs
front_end/src/constants.rs
front_end/src/html_helper.rs
front_end/src/state.rs
front_end/src/yew_components.rs

index 54204737f41eb73859d2860c67c0b51a469ac3e5..c79bb100863f5242852f596906941d0c8f6ba453 100644 (file)
@@ -683,7 +683,8 @@ impl DBHandler {
         }
 
         // 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;",
             [player_id],
             |row| {
index b7293238ab079879e6c8fab44ebc164f36115bac..1ba76edea1660054cdd34354ce3d274aadee8adf 100644 (file)
@@ -15,6 +15,7 @@ use crate::state::{board_deep_clone, BoardState, BoardType, Turn};
 
 const AI_THIRD_MAX_UTILITY: f64 = 0.89;
 
+#[allow(dead_code)]
 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
 pub enum AIDifficulty {
     Easy,
index 6f59509acc26d26f5430ece1ec6af8fbdf69a836..b693223e3888121e14634dac6a0b46b828e9e8be 100644 (file)
@@ -9,25 +9,36 @@
 pub const ROWS: u8 = 8;
 pub const COLS: u8 = 7;
 
+#[allow(dead_code)]
 pub const INFO_TEXT_MAX_ITEMS: u32 = 100;
 
 pub const AI_EASY_MAX_CHOICES: usize = 5;
 pub const AI_NORMAL_MAX_CHOICES: usize = 3;
+#[allow(dead_code)]
 pub const AI_CHOICE_DURATION_MILLIS: i32 = 1000;
 
+#[allow(dead_code)]
 pub const PLAYER_COUNT_LIMIT: usize = 1000;
+#[allow(dead_code)]
 pub const TURN_SECONDS: u64 = 25;
+#[allow(dead_code)]
 pub const GAME_CLEANUP_TIMEOUT: u64 = (TURN_SECONDS + 1) * ((ROWS * COLS) as u64 + 5u64);
+#[allow(dead_code)]
 pub const PLAYER_CLEANUP_TIMEOUT: u64 = 300;
 
+#[allow(dead_code)]
 pub const BACKEND_TICK_DURATION_MILLIS: i32 = 500;
+#[allow(dead_code)]
 pub const BACKEND_CLEANUP_INTERVAL_SECONDS: u64 = 120;
 
+#[allow(dead_code)]
 pub const BACKEND_PHRASE_MAX_LENGTH: usize = 128;
 
 // TODO: Change this to "https://asdm.seodisparate.com/api" when backend is installed
+#[allow(dead_code)]
 #[cfg(debug_assertions)]
 pub const BACKEND_URL: &str = "http://testlocalhost/api";
 
+#[allow(dead_code)]
 #[cfg(not(debug_assertions))]
 pub const BACKEND_URL: &str = "https://asdm.seodisparate.com/api";
index 18683dc4531a8e9b30bb87a186f0cf849e09a212..6809b19b266c0e52a36be7191249321d01cb2a09 100644 (file)
@@ -10,7 +10,7 @@ use js_sys::{Function, JsString, Promise};
 use std::collections::HashMap;
 use wasm_bindgen::{JsCast, JsValue};
 use wasm_bindgen_futures::JsFuture;
-use web_sys::{window, Document, Request, RequestInit, Window};
+use web_sys::{window, Document, Window};
 
 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))
 }
 
-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> {
     let mut send_json_string = String::from("{");
     for (key, value) in entries {
index d2808f450694125ef45cb3bf4c8bdb6d13ebb990..be8954ccf561c07ce3ad17eb799a991381157cd7 100644 (file)
@@ -17,6 +17,7 @@ use std::collections::hash_set::HashSet;
 use std::fmt::Display;
 use std::rc::Rc;
 
+#[allow(dead_code)]
 #[derive(Clone, Debug, PartialEq, Eq)]
 pub enum GameState {
     MainMenu,
@@ -32,6 +33,7 @@ pub enum GameState {
 }
 
 impl GameState {
+    #[allow(dead_code)]
     pub fn is_networked_multiplayer(&self) -> bool {
         matches!(
             *self,
@@ -44,6 +46,7 @@ impl GameState {
         )
     }
 
+    #[allow(dead_code)]
     pub fn set_networked_paired(&mut self) {
         if let GameState::NetworkedMultiplayer {
             ref mut paired,
@@ -56,6 +59,7 @@ impl GameState {
         }
     }
 
+    #[allow(dead_code)]
     pub fn get_networked_current_side(&self) -> Option<Turn> {
         if let GameState::NetworkedMultiplayer {
             paired: _,
@@ -70,6 +74,7 @@ impl GameState {
         }
     }
 
+    #[allow(dead_code)]
     pub fn set_networked_current_side(&mut self, side: Option<Turn>) {
         if let GameState::NetworkedMultiplayer {
             paired: _,
@@ -82,6 +87,7 @@ impl GameState {
         }
     }
 
+    #[allow(dead_code)]
     pub fn get_current_turn(&self) -> Turn {
         if let GameState::SinglePlayer(turn, _) = *self {
             turn
@@ -98,6 +104,7 @@ impl GameState {
         }
     }
 
+    #[allow(dead_code)]
     pub fn set_networked_current_turn(&mut self, turn: Turn) {
         if let GameState::NetworkedMultiplayer {
             paired: _,
@@ -110,6 +117,7 @@ impl GameState {
         }
     }
 
+    #[allow(dead_code)]
     pub fn get_phrase(&self) -> Option<String> {
         if let GameState::NetworkedMultiplayer {
             paired: _,
@@ -124,6 +132,7 @@ impl GameState {
         }
     }
 
+    #[allow(dead_code)]
     pub fn get_singleplayer_current_side(&self) -> Option<Turn> {
         if let GameState::SinglePlayer(turn, _) = *self {
             Some(turn)
@@ -154,6 +163,7 @@ impl From<MainMenuMessage> for GameState {
     }
 }
 
+#[allow(dead_code)]
 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
 pub enum BoardState {
     Empty,
@@ -191,10 +201,12 @@ impl From<Turn> for BoardState {
 }
 
 impl BoardState {
+    #[allow(dead_code)]
     pub fn is_empty(&self) -> bool {
         *self == BoardState::Empty
     }
 
+    #[allow(dead_code)]
     pub fn is_win(self) -> bool {
         match self {
             BoardState::Empty | BoardState::Cyan | BoardState::Magenta => false,
@@ -202,6 +214,7 @@ impl BoardState {
         }
     }
 
+    #[allow(dead_code)]
     pub fn into_win(self) -> Self {
         match self {
             BoardState::Empty => BoardState::Empty,
@@ -210,8 +223,9 @@ impl BoardState {
         }
     }
 
-    pub fn from_win(&self) -> Self {
-        match *self {
+    #[allow(dead_code, clippy::wrong_self_convention)]
+    pub fn from_win(self) -> Self {
+        match self {
             BoardState::Empty => BoardState::Empty,
             BoardState::Cyan | BoardState::CyanWin => BoardState::Cyan,
             BoardState::Magenta | BoardState::MagentaWin => BoardState::Magenta,
@@ -219,6 +233,7 @@ impl BoardState {
     }
 }
 
+#[allow(dead_code)]
 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
 pub enum Turn {
     CyanPlayer,
@@ -244,6 +259,7 @@ impl From<BoardState> for Turn {
 }
 
 impl Turn {
+    #[allow(dead_code)]
     pub fn get_color(&self) -> &str {
         match *self {
             Turn::CyanPlayer => "cyan",
@@ -261,6 +277,7 @@ impl Turn {
 
 pub type BoardType = [Rc<Cell<BoardState>>; 56];
 
+#[allow(dead_code)]
 pub fn new_empty_board() -> BoardType {
     [
         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 {
     let cloned_board = new_empty_board();
     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];
 
+#[allow(dead_code)]
 pub fn new_placed() -> PlacedType {
     [
         Rc::new(Cell::new(false)),
@@ -394,6 +413,7 @@ pub fn new_placed() -> PlacedType {
     ]
 }
 
+#[allow(dead_code)]
 #[derive(Clone, Debug, PartialEq)]
 pub struct SharedState {
     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
 // dependencies on the yew_components module
+#[allow(dead_code)]
 #[derive(Clone, Debug, PartialEq, Eq)]
 pub enum MainMenuMessage {
     SinglePlayer(Turn, AIDifficulty),
@@ -423,6 +444,7 @@ pub enum MainMenuMessage {
     NetworkedMultiplayer(Option<String>),
 }
 
+#[allow(dead_code)]
 pub fn new_string_board() -> String {
     let mut board = String::with_capacity(56);
     for _i in 0..56 {
@@ -431,6 +453,7 @@ pub fn new_string_board() -> String {
     board
 }
 
+#[allow(dead_code)]
 pub fn board_from_string(board_string: String) -> BoardType {
     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
 /// 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>) {
     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)]
 pub struct PairingRequestResponse {
     pub r#type: String,
@@ -545,6 +570,7 @@ pub struct PairingRequestResponse {
     pub color: Option<String>,
 }
 
+#[allow(dead_code)]
 #[derive(Debug, Serialize, Deserialize)]
 pub struct PairingStatusResponse {
     pub r#type: String,
@@ -552,6 +578,7 @@ pub struct PairingStatusResponse {
     pub color: Option<String>,
 }
 
+#[allow(dead_code)]
 #[derive(Debug, Serialize, Deserialize)]
 pub struct GameStateResponse {
     pub r#type: String,
@@ -561,6 +588,7 @@ pub struct GameStateResponse {
     pub updated_time: Option<String>,
 }
 
+#[allow(dead_code)]
 #[derive(Debug, Serialize, Deserialize)]
 pub struct PlaceTokenResponse {
     pub r#type: String,
@@ -568,12 +596,14 @@ pub struct PlaceTokenResponse {
     pub board: String,
 }
 
+#[allow(dead_code)]
 #[derive(Debug, Serialize, Deserialize)]
 pub struct SendEmoteRequestResponse {
     pub r#type: String,
     pub status: String,
 }
 
+#[allow(dead_code)]
 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
 pub enum NetworkedGameState {
     CyanTurn,
@@ -587,6 +617,7 @@ pub enum NetworkedGameState {
     UnknownID,
 }
 
+#[allow(dead_code)]
 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
 pub enum PlacedEnum {
     Accepted,
@@ -595,6 +626,7 @@ pub enum PlacedEnum {
     Other(NetworkedGameState),
 }
 
+#[allow(dead_code)]
 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
 pub enum EmoteEnum {
     Smile,
index a8b07ea9076efccf5705d8508160c7fd403d1947..e2c05ae7450c6b357eec56d9ce20278d203c482f 100644 (file)
@@ -1589,6 +1589,7 @@ impl Component for Wrapper {
                         match networked_game_state {
                             NetworkedGameState::CyanTurn => {
                                 if current_game_state.get_current_turn() != Turn::CyanPlayer {
+                                    self.board_updated_time.take();
                                     current_game_state.set_networked_current_turn(Turn::CyanPlayer);
                                     shared.game_state.replace(current_game_state.clone());
                                     append_to_info_text(
@@ -1613,6 +1614,7 @@ impl Component for Wrapper {
                             }
                             NetworkedGameState::MagentaTurn => {
                                 if current_game_state.get_current_turn() != Turn::MagentaPlayer {
+                                    self.board_updated_time.take();
                                     current_game_state
                                         .set_networked_current_turn(Turn::MagentaPlayer);
                                     shared.game_state.replace(current_game_state.clone());