Refactor code to utilize TurnActions on player moves

This commit is contained in:
Joel Therrien 2023-09-14 18:53:47 -07:00
parent 8fd250170b
commit ef4506b55e
3 changed files with 26 additions and 28 deletions

View file

@ -199,7 +199,7 @@ impl Game {
&self.dictionary &self.dictionary
} }
pub fn receive_play(&mut self, tray_tile_locations: Vec<Option<PlayedTile>>, commit_move: bool) -> Result<ScoreResult, String> { pub fn receive_play(&mut self, tray_tile_locations: Vec<Option<PlayedTile>>, commit_move: bool) -> Result<TurnAction, String> {
let player = self.current_player_name(); let player = self.current_player_name();
@ -230,7 +230,7 @@ impl Game {
.collect(); .collect();
if commit_move { if commit_move {
let mut player_state = self.player_states.get_player_state_mut(&player).unwrap(); let player_state = self.player_states.get_player_state_mut(&player).unwrap();
player_state.score += total_score; player_state.score += total_score;
player_state.tray = tray; player_state.tray = tray;
@ -241,13 +241,15 @@ impl Game {
self.increment_turn(); self.increment_turn();
} }
Ok(ScoreResult { Ok(TurnAction::PlayTiles {
result: ScoreResult {
words, words,
total: total_score, total: total_score,
},
}) })
} }
pub fn exchange_tiles(&mut self, tray_tile_locations: Vec<bool>) -> Result<Tray, String> { pub fn exchange_tiles(&mut self, tray_tile_locations: Vec<bool>) -> Result<(Tray, TurnAction), String> {
let player = self.current_player_name(); let player = self.current_player_name();
let tray = match self.player_states.get_tray_mut(&player) { let tray = match self.player_states.get_tray_mut(&player) {
None => {return Err(format!("Player {} not found", player))} None => {return Err(format!("Player {} not found", player))}
@ -259,6 +261,7 @@ impl Game {
} }
let tile_pool = &mut self.tile_pool; let tile_pool = &mut self.tile_pool;
let mut tiles_exchanged = 0;
for (i, played_tile) in tray_tile_locations.iter().enumerate() { for (i, played_tile) in tray_tile_locations.iter().enumerate() {
if *played_tile { if *played_tile {
@ -266,6 +269,7 @@ impl Game {
if letter.is_some() { if letter.is_some() {
tile_pool.push(letter.unwrap().clone()); tile_pool.push(letter.unwrap().clone());
*letter = None; *letter = None;
tiles_exchanged += 1;
} }
} }
} }
@ -277,7 +281,7 @@ impl Game {
self.increment_turn(); self.increment_turn();
Ok(tray) Ok((tray, TurnAction::ExchangeTiles { tiles_exchanged }))
} }
@ -308,7 +312,6 @@ impl Game {
None => { None => {
// no available moves; exchange all tiles // no available moves; exchange all tiles
let mut to_exchange = Vec::with_capacity(TRAY_LENGTH as usize); let mut to_exchange = Vec::with_capacity(TRAY_LENGTH as usize);
let mut tiles_exchanged = 0;
for tile_spot in tray.letters.iter() { for tile_spot in tray.letters.iter() {
match tile_spot { match tile_spot {
None => { None => {
@ -316,21 +319,21 @@ impl Game {
}, },
Some(_) => { Some(_) => {
to_exchange.push(true); to_exchange.push(true);
tiles_exchanged += 1;
} }
} }
} }
if self.tile_pool.is_empty(){ if self.tile_pool.is_empty(){
self.increment_turn();
Ok(TurnAdvanceResult::AIMove { Ok(TurnAdvanceResult::AIMove {
name: current_player, name: current_player,
action: TurnAction::Pass, action: TurnAction::Pass,
}) })
} else { } else {
self.exchange_tiles(to_exchange)?; let (_, action) = self.exchange_tiles(to_exchange)?;
Ok(TurnAdvanceResult::AIMove { Ok(TurnAdvanceResult::AIMove {
name: current_player, name: current_player,
action: TurnAction::ExchangeTiles{tiles_exchanged}, action,
}) })
} }
@ -338,16 +341,15 @@ impl Game {
} }
Some(best_move) => { Some(best_move) => {
let play = best_move.convert_to_play(tray); let play = best_move.convert_to_play(tray);
let score_result = self.receive_play(play, true)?; let action = self.receive_play(play, true)?;
Ok(TurnAdvanceResult::AIMove { Ok(TurnAdvanceResult::AIMove {
name: current_player, name: current_player,
action: TurnAction::PlayTiles{result: score_result}, action,
}) })
} }
} }
} else { } else {
Ok(TurnAdvanceResult::HumanInputRequired{name: self.current_player_name()}) Ok(TurnAdvanceResult::HumanInputRequired{name: self.current_player_name()})
} }
@ -407,6 +409,8 @@ mod tests {
let result = game.advance_turn(); let result = game.advance_turn();
println!("AI move is {result:?}"); println!("AI move is {result:?}");
assert_eq!(game.current_player_name(), "Player");
} }
} }

View file

@ -113,10 +113,10 @@ impl GameWasm {
let tray_tile_locations: Vec<bool> = serde_wasm_bindgen::from_value(tray_tile_locations)?; let tray_tile_locations: Vec<bool> = serde_wasm_bindgen::from_value(tray_tile_locations)?;
match self.0.exchange_tiles(tray_tile_locations) { match self.0.exchange_tiles(tray_tile_locations) {
Ok(tray) => { Ok((_, turn_action)) => {
serde_wasm_bindgen::to_value(&MyResult { serde_wasm_bindgen::to_value(&MyResult {
response_type: ResponseType::OK, response_type: ResponseType::OK,
value: tray value: turn_action
}) })
}, },
Err(e) => { Err(e) => {

View file

@ -6,7 +6,7 @@ import {
PlayedTile, PlayedTile,
PlayerAndScore, PlayerAndScore,
ScoreResult, ScoreResult,
Tray, TurnAdvanceResult Tray, TurnAction, TurnAdvanceResult
} from "word_grid"; } from "word_grid";
import { import {
LocationType, LocationType,
@ -117,20 +117,14 @@ export function Game(props: {
function exchangeFunction(selectedArray: Array<boolean>) { function exchangeFunction(selectedArray: Array<boolean>) {
let numSelected = 0; const result: MyResult<TurnAction | string> = props.wasm.exchange_tiles(selectedArray);
selectedArray.forEach((x) => {
if (x){
numSelected++;
}
})
const result: MyResult<Tray | string> = props.wasm.exchange_tiles(selectedArray);
console.log({result}); console.log({result});
if(result.response_type === "ERR") { if(result.response_type === "ERR") {
logDispatch(<div><em>{(result.value as string)}</em></div>); logDispatch(<div><em>{(result.value as string)}</em></div>);
} else { } else {
logDispatch(<div><em>You exchanged {numSelected} tiles.</em></div>); const action = result.value as {type: "ExchangeTiles"; tiles_exchanged: number;};
logDispatch(<div><em>You exchanged {action.tiles_exchanged} tiles.</em></div>);
setTurnCount(turnCount + 1); setTurnCount(turnCount + 1);
} }
@ -181,7 +175,7 @@ export function Game(props: {
return null; return null;
}); });
const result: MyResult<ScoreResult | string> = props.wasm.receive_play(playedTiles, confirmedScorePoints > -1); const result: MyResult<{ type: "PlayTiles"; result: ScoreResult } | string> = props.wasm.receive_play(playedTiles, confirmedScorePoints > -1);
console.log({result}); console.log({result});
if(result.response_type === "ERR") { if(result.response_type === "ERR") {
@ -196,7 +190,7 @@ export function Game(props: {
} else { } else {
const score_result = result.value as ScoreResult; const score_result = (result.value as { type: "PlayTiles"; result: ScoreResult }).result;
const total_points = score_result.total; const total_points = score_result.total;
let msg: string; let msg: string;