use rand::prelude::SliceRandom; use rand::rngs::SmallRng; use rand::SeedableRng; use serde::{Deserialize, Serialize}; use tsify::Tsify; use crate::board::{Board, Coordinates, Letter}; use crate::constants::{standard_tile_pool, TRAY_LENGTH}; use crate::dictionary::{Dictionary, DictionaryImpl}; use crate::player_interaction::ai::{AI, CompleteMove, Difficulty}; use crate::player_interaction::Tray; pub enum Player { Human(String), AI{ name: String, difficulty: Difficulty, object: AI, } } impl Player { pub fn get_name(&self) -> &str { match &self { Player::Human(name) => {name} Player::AI { name, .. } => {name} } } } pub struct PlayerState { pub player: Player, pub score: u32, pub tray: Tray } #[derive(Deserialize, Tsify, Copy, Clone, Debug)] #[tsify(from_wasm_abi)] pub struct PlayedTile { pub index: usize, pub character: Option, // we only set this if PlayedTile is a blank } #[derive(Debug, Serialize, Deserialize, Tsify)] #[tsify(from_wasm_abi)] pub struct WordResult { word: String, score: u32, } #[derive(Debug, Serialize, Deserialize, Tsify)] #[tsify(from_wasm_abi)] pub struct ScoreResult { words: Vec, total: u32, } pub struct PlayerStates(pub Vec); impl PlayerStates { fn get_player_name_by_turn_id(&self, id: usize) -> &str { let id_mod = id % self.0.len(); let state = self.0.get(id_mod).unwrap(); state.player.get_name() } pub fn get_player_state(&self, name: &str) -> Option<&PlayerState> { self.0.iter() .filter(|state| state.player.get_name().eq(name)) .nth(0) } pub fn get_player_state_mut(&mut self, name: &str) -> Option<&mut PlayerState> { self.0.iter_mut() .filter(|state| state.player.get_name().eq(name)) .nth(0) } pub fn get_tray(&self, name: &str) -> Option<&Tray> { let player = self.get_player_state(name)?; Some(&player.tray) } pub fn get_tray_mut(&mut self, name: &str) -> Option<&mut Tray> { let player = self.get_player_state_mut(name)?; Some(&mut player.tray) } } pub struct Game{ pub tile_pool: Vec, rng: SmallRng, board: Board, pub player_states: PlayerStates, dictionary: DictionaryImpl, turn_order: usize, } impl Game { pub fn new(seed: u64, dictionary_text: &str, player_names: Vec, ai_difficulties: Vec) -> Self { let mut rng = SmallRng::seed_from_u64(seed); let mut letters = standard_tile_pool(Some(&mut rng)); let dictionary = DictionaryImpl::create_from_str(dictionary_text); let mut player_states: Vec = player_names.iter() .map(|name| { let mut tray = Tray::new(TRAY_LENGTH); tray.fill(&mut letters); PlayerState { player: Player::Human(name.clone()), score: 0, tray, } }) .collect(); for (i, ai_difficulty) in ai_difficulties.into_iter().enumerate() { let ai = AI::new(ai_difficulty, &dictionary); let mut tray = Tray::new(TRAY_LENGTH); tray.fill(&mut letters); player_states.push(PlayerState { player: Player::AI { name: format!("AI {}", i), difficulty: ai_difficulty, object: ai, }, score: 0, tray, }); } // let's shuffle player_states so that humans don't always go first player_states.shuffle(&mut rng); Game { tile_pool: letters, rng, board: Board::new(), player_states: PlayerStates(player_states), dictionary, turn_order: 0, } } pub fn get_board(&self) -> &Board {&self.board} pub fn set_board(&mut self, new_board: Board) { self.board = new_board; } pub fn fill_trays(&mut self){ for state in self.player_states.0.iter_mut() { let tray = &mut state.tray; tray.fill(&mut self.tile_pool); } } pub fn get_dictionary(&self) -> &DictionaryImpl { &self.dictionary } pub fn receive_play(&mut self, tray_tile_locations: Vec>, commit_move: bool) -> Result { let player = self.current_player_name(); let mut board_instance = self.get_board().clone(); let mut tray = self.player_states.get_tray(&player).unwrap().clone(); let mut played_letters: Vec<(Letter, Coordinates)> = Vec::new(); for (i, played_tile) in tray_tile_locations.iter().enumerate() { if played_tile.is_some() { let played_tile = played_tile.unwrap(); let mut letter: Letter = tray.letters.get(i).unwrap().unwrap(); *tray.letters.get_mut(i).unwrap() = None; let coord = Coordinates::new_from_index(played_tile.index); if letter.is_blank { match played_tile.character { None => { panic!("You can't play a blank character without providing a letter value") } Some(x) => { // TODO - check that x is a valid alphabet letter letter.text = x; } } } played_letters.push((letter, coord)); } } board_instance.receive_play(played_letters)?; let x = board_instance.calculate_scores(self.get_dictionary())?; let total_score = x.1; let words: Vec = x.0.iter() .map(|(word, score)| { WordResult { word: word.to_string(), score: *score } }) .collect(); if commit_move { let mut player_state = self.player_states.get_player_state_mut(&player).unwrap(); player_state.score += total_score; player_state.tray = tray; board_instance.fix_tiles(); self.set_board(board_instance); self.fill_trays(); self.increment_turn(); } Ok(ScoreResult { words, total: total_score, }) } pub fn exchange_tiles(&mut self, tray_tile_locations: Vec) -> Result { let player = self.current_player_name(); let tray = match self.player_states.get_tray_mut(&player) { None => {return Err(format!("Player {} not found", player))} Some(x) => {x} }; if tray.letters.len() != tray_tile_locations.len() { return Err("Incoming tray and existing tray have different lengths".to_string()); } let tile_pool = &mut self.tile_pool; for (i, played_tile) in tray_tile_locations.iter().enumerate() { if *played_tile { let letter = tray.letters.get_mut(i).unwrap(); if letter.is_some() { tile_pool.push(letter.unwrap().clone()); *letter = None; } } } tile_pool.shuffle(&mut self.rng); tray.fill(&mut self.tile_pool); let tray = tray.clone(); self.increment_turn(); Ok(tray) } pub fn add_word(&mut self, word: String) { let word = word.to_uppercase(); self.dictionary.insert(word, -1.0); } pub fn increment_turn(&mut self) { self.turn_order += 1; } pub fn current_player_name(&self) -> String { self.player_states.get_player_name_by_turn_id(self.turn_order).to_string() } pub fn advance_turn(&mut self) -> TurnAdvanceResult { let current_player = self.current_player_name(); let state = self.player_states.get_player_state_mut(¤t_player).unwrap(); if let Player::AI {object, .. } = &mut state.player { let tray = &mut state.tray; let best_move = object.find_best_move(tray, &self.board, &mut self.rng); match best_move { None => { // no available moves; exchange all tiles let mut to_exchange = Vec::with_capacity(TRAY_LENGTH as usize); let mut tiles_exchanged = 0; for tile_spot in tray.letters.iter() { match tile_spot { None => { to_exchange.push(false); }, Some(_) => { to_exchange.push(true); tiles_exchanged += 1; } } } if self.tile_pool.is_empty(){ TurnAdvanceResult::AIMove { name: current_player, action: TurnAction::Pass, } } else { self.exchange_tiles(to_exchange).unwrap(); TurnAdvanceResult::AIMove { name: current_player, action: TurnAction::ExchangeTiles(tiles_exchanged), } } } Some(best_move) => { let play = best_move.convert_to_play(tray); let score_result = self.receive_play(play, true).unwrap(); TurnAdvanceResult::AIMove { name: current_player, action: TurnAction::PlayTiles(score_result), } } } } else { TurnAdvanceResult::HumanInputRequired(self.current_player_name()) } } } #[derive(Deserialize, Tsify, Copy, Clone)] #[tsify(from_wasm_abi)] pub enum TurnAction { Pass, ExchangeTiles(usize), PlayTiles(ScoreResult), } #[derive(Deserialize, Tsify, Copy, Clone)] #[tsify(from_wasm_abi)] pub enum TurnAdvanceResult { HumanInputRequired(String), AIMove{ name: String, action: TurnAction, } }