chore: Misc. fixes & tweaks

This commit is contained in:
Joel Therrien 2024-12-27 14:30:06 -08:00
parent f85b3be2f3
commit 710499b664
8 changed files with 23 additions and 30 deletions

View file

@ -17,10 +17,7 @@ pub fn escape_characters(x: &str) -> String {
x x
} }
#[derive(Clone, Debug, Serialize, PartialEq)] pub type Player = String;
pub struct Player {
pub name: String,
}
#[derive(Clone, Serialize, Debug)] #[derive(Clone, Serialize, Debug)]
pub struct PartyInfo { pub struct PartyInfo {

View file

@ -53,7 +53,7 @@ async fn incoming_message_handler<E: std::fmt::Display>(
.party_info .party_info
.players .players
.iter() .iter()
.filter(|p| !p.name.eq(&player.name)) .filter(|p| !p.eq(&player))
.map(|p| p.clone()) .map(|p| p.clone())
.collect_vec(); .collect_vec();
room.party_info.players = new_vec; room.party_info.players = new_vec;
@ -77,7 +77,7 @@ async fn incoming_message_handler<E: std::fmt::Display>(
let message: ClientToServerMessage = serde_json::from_str(message).unwrap(); let message: ClientToServerMessage = serde_json::from_str(message).unwrap();
// TODO // TODO
println!("Received {message:#?} from client {}", player.name); println!("Received {message:#?} from client {player}");
match message { match message {
ClientToServerMessage::Load => { ClientToServerMessage::Load => {
return !game_load(player, None, room, stream).await return !game_load(player, None, room, stream).await
@ -87,7 +87,7 @@ async fn incoming_message_handler<E: std::fmt::Display>(
if room.game.is_some() { if room.game.is_some() {
eprintln!( eprintln!(
"Player {} is trying to start an already started game", "Player {} is trying to start an already started game",
player.name player
); );
} else { } else {
let rng = SmallRng::from_entropy(); let rng = SmallRng::from_entropy();
@ -96,7 +96,7 @@ async fn incoming_message_handler<E: std::fmt::Display>(
.party_info .party_info
.players .players
.iter() .iter()
.map(|p| p.name.clone()) .map(|p| p.clone())
.collect_vec(); .collect_vec();
let game = Game::new_specific( let game = Game::new_specific(
rng, rng,
@ -116,23 +116,23 @@ async fn incoming_message_handler<E: std::fmt::Display>(
let mut room = room.write().await; let mut room = room.write().await;
if room.game.is_none() { if room.game.is_none() {
let event = ServerToClientMessage::Invalid { let event = ServerToClientMessage::Invalid {
reason: format!("Game hasn't been started yet"), reason: "Game hasn't been started yet".to_string(),
}; };
let event = serde_json::to_string(&event).unwrap(); let event = serde_json::to_string(&event).unwrap();
let _ = stream.send(event.into()).await; let _ = stream.send(event.into()).await;
} else { } else {
let game = room.game.as_mut().unwrap(); let game = room.game.as_mut().unwrap();
let result = match r#move { let result = match r#move {
GameMove::Pass => game.pass(&player.name), GameMove::Pass => game.pass(&player),
GameMove::Exchange { tiles } => { GameMove::Exchange { tiles } => {
game.exchange(&player.name, tiles) game.exchange(&player, tiles)
} }
GameMove::Play { GameMove::Play {
played_tiles, played_tiles,
commit_move, commit_move,
} => { } => {
let result = let result =
game.play(&player.name, played_tiles, commit_move); game.play(&player, played_tiles, commit_move);
if result.is_ok() & !commit_move { if result.is_ok() & !commit_move {
let event = ServerToClientMessage::GameEvent { let event = ServerToClientMessage::GameEvent {
event: GameEvent::TurnAction { event: GameEvent::TurnAction {
@ -147,7 +147,7 @@ async fn incoming_message_handler<E: std::fmt::Display>(
result result
} }
GameMove::AddToDictionary { word } => { GameMove::AddToDictionary { word } => {
game.add_to_dictionary(&player.name, &word) game.add_to_dictionary(&player, &word)
} }
}; };
match result { match result {
@ -216,7 +216,7 @@ async fn game_load(
// The game object was modified; we need to trigger a load from this player's perspective // The game object was modified; we need to trigger a load from this player's perspective
let mut room = room.write().await; let mut room = room.write().await;
let mut state = room.game.as_mut().unwrap().load(&player.name).unwrap(); let mut state = room.game.as_mut().unwrap().load(&player).unwrap();
state.update = update; state.update = update;
let event = ServerToClientMessage::GameEvent { let event = ServerToClientMessage::GameEvent {
event: GameEvent::TurnAction { event: GameEvent::TurnAction {
@ -261,15 +261,13 @@ async fn room(
ws: ws::WebSocket, ws: ws::WebSocket,
rooms: &State<Mutex<RoomMap>>, rooms: &State<Mutex<RoomMap>>,
) -> ws::Channel<'static> { ) -> ws::Channel<'static> {
let id = escape_characters(id); let id = escape_characters(id).to_lowercase();
let player_name = escape_characters(player_name); let player_name = escape_characters(player_name);
let mut rooms = rooms.lock().await; let mut rooms = rooms.lock().await;
let room = rooms.get(&id); let room = rooms.get(&id);
let player = Player { let player = player_name.to_string();
name: player_name.to_string(),
};
fn make_join_event(room: &Room, player: &Player) -> ServerToClientMessage { fn make_join_event(room: &Room, player: &Player) -> ServerToClientMessage {
ServerToClientMessage::RoomChange { ServerToClientMessage::RoomChange {
@ -310,11 +308,11 @@ async fn room(
let mut room = d.write().await; let mut room = d.write().await;
// check if player is already in the room. If they are, don't allow the new connection // check if player is already in the room. If they are, don't allow the new connection
if room.party_info.players.contains(&player) { if room.party_info.players.iter().map(|f| f.to_lowercase()).contains(&player.to_lowercase()) {
return reject_websocket_with_reason( return reject_websocket_with_reason(
ws, ws,
CloseCode::Protocol, CloseCode::Protocol,
format!("{} is already in the room", player.name), format!("{player} is already in the room"),
); );
} }
@ -322,7 +320,7 @@ async fn room(
if game if game
.0 .0
.player_states .player_states
.get_player_state(&player.name) .get_player_state(&player)
.is_none() .is_none()
{ {
// Game is in progress and our new player isn't a member // Game is in progress and our new player isn't a member

View file

@ -404,7 +404,7 @@ export function Game(props: {
const playerAndScores = api_state.public_information.players; const playerAndScores = api_state.public_information.players;
const remainingTiles = api_state.public_information.remaining_tiles; const remainingTiles = api_state.public_information.remaining_tiles;
const isPlayersTurn = api_state.public_information.current_player == props.settings.playerName; const isPlayersTurn = api_state.public_information.current_player.toLowerCase() == props.settings.playerName.toLowerCase();
return <> return <>
<TileExchangeModal <TileExchangeModal

View file

@ -42,7 +42,7 @@ export function Menu(): React.JSX.Element {
return <div><p>Connecting to {roomName}</p></div> return <div><p>Connecting to {roomName}</p></div>
} else if (partyInfo != null) { } else if (partyInfo != null) {
const players = partyInfo.players.map((x) => { const players = partyInfo.players.map((x) => {
return <li key={x.name}>{x.name}</li>; return <li key={x}>{x}</li>;
}); });
const ais = partyInfo.ais.map((x, i) => { const ais = partyInfo.ais.map((x, i) => {
return <li key={i} className="side-grid"> return <li key={i} className="side-grid">

View file

@ -1,8 +1,6 @@
import {API, APIState, Difficulty, PlayedTile} from "./api"; import {API, APIState, Difficulty, PlayedTile} from "./api";
export interface Player { export type Player = string;
name: string
}
export interface AI { export interface AI {
proportion: number proportion: number

View file

@ -58,7 +58,7 @@ impl APIGame {
} }
fn is_players_turn(&self, player: &str) -> bool { fn is_players_turn(&self, player: &str) -> bool {
self.0.current_player_name().eq(player) self.0.current_player_name().eq_ignore_ascii_case(player)
} }
fn player_exists(&self, player: &str) -> bool { fn player_exists(&self, player: &str) -> bool {

View file

@ -84,7 +84,7 @@ mod tests {
fn test_dictionary() { fn test_dictionary() {
let dictionary = HashMap::create_from_path("../resources/dictionary.csv"); let dictionary = HashMap::create_from_path("../resources/dictionary.csv");
assert_eq!(dictionary.len(), 279429); assert_eq!(dictionary.len(), 279426);
assert!(dictionary.contains_key("AA")); assert!(dictionary.contains_key("AA"));
assert!(dictionary.contains_key("AARDVARK")); assert!(dictionary.contains_key("AARDVARK"));

View file

@ -158,14 +158,14 @@ impl PlayerStates {
pub fn get_player_state(&self, name: &str) -> Option<&PlayerState> { pub fn get_player_state(&self, name: &str) -> Option<&PlayerState> {
self.0 self.0
.iter() .iter()
.filter(|state| state.player.get_name().eq(name)) .filter(|state| state.player.get_name().eq_ignore_ascii_case(name))
.nth(0) .nth(0)
} }
pub fn get_player_state_mut(&mut self, name: &str) -> Option<&mut PlayerState> { pub fn get_player_state_mut(&mut self, name: &str) -> Option<&mut PlayerState> {
self.0 self.0
.iter_mut() .iter_mut()
.filter(|state| state.player.get_name().eq(name)) .filter(|state| state.player.get_name().eq_ignore_ascii_case(name))
.nth(0) .nth(0)
} }