use serde::{Deserialize, Serialize}; use serde_wasm_bindgen::Error; use tsify::Tsify; use wasm_bindgen::JsValue; use wasm_bindgen::prelude::wasm_bindgen; use crate::board::{CellType, Letter}; use crate::game::{Game, PlayedTile}; #[wasm_bindgen] pub struct GameWasm(Game); #[derive(Serialize, Deserialize, Tsify)] #[tsify(from_wasm_abi)] pub enum ResponseType { OK, ERR, } #[derive(Serialize, Deserialize, Tsify)] #[tsify(from_wasm_abi)] pub struct MyResult { response_type: ResponseType, value: E, } #[wasm_bindgen] impl GameWasm { #[wasm_bindgen(constructor)] pub fn new(seed: u64, dictionary_text: &str) -> GameWasm { GameWasm(Game::new(seed, dictionary_text, vec!["Player".to_string(), "AI".to_string()])) } pub fn get_tray(&self, name: &str) -> Result { let tray = self.0.get_tray(name); serde_wasm_bindgen::to_value(&tray) } pub fn get_board_cell_types(&self) -> Result { let board = self.0.get_board(); let cell_types: Vec = board.cells.iter().map(|cell| -> CellType { cell.cell_type.clone() }).collect(); serde_wasm_bindgen::to_value(&cell_types) } pub fn get_board_letters(&self) -> Result { let board = self.0.get_board(); let letters: Vec> = board.cells.iter().map(|cell| -> Option { cell.value.clone() }).collect(); serde_wasm_bindgen::to_value(&letters) } pub fn receive_play(&mut self, player: &str, tray_tile_locations: JsValue, commit_move: bool) -> Result { let tray_tile_locations: Vec> = serde_wasm_bindgen::from_value(tray_tile_locations)?; let result = self.0.receive_play(player, tray_tile_locations, commit_move); match result { Ok(x) => { serde_wasm_bindgen::to_value(&MyResult { response_type: ResponseType::OK, value: x }) }, Err(e) => { serde_wasm_bindgen::to_value(&MyResult { response_type: ResponseType::ERR, value: e }) } } } pub fn get_scores(&self) -> Result { #[derive(Serialize, Deserialize, Tsify)] #[tsify(from_wasm_abi)] pub struct PlayerAndScore { name: String, score: u32, } let scores: Vec = self.0.player_states.iter() .map(|player_state| { PlayerAndScore { name: player_state.player.get_name().to_string(), score: player_state.score, } }) .collect(); Ok(serde_wasm_bindgen::to_value(&scores)?) } }