From 1fdea3e4543cdd2696a0b8c95df6f00e1b64e80f Mon Sep 17 00:00:00 2001 From: Tangent Wantwight Date: Sat, 13 Feb 2021 22:23:24 -0500 Subject: [PATCH] Move client message processing into client agent --- src/net/agent.rs | 23 +++++++++++++++++++---- src/net/server.rs | 25 ++++++++++--------------- 2 files changed, 29 insertions(+), 19 deletions(-) diff --git a/src/net/agent.rs b/src/net/agent.rs index 519b2c5..5c6ac44 100644 --- a/src/net/agent.rs +++ b/src/net/agent.rs @@ -6,11 +6,26 @@ use super::*; pub struct ClientAgent { server: Handle, + player_id: PlayerId, } impl ClientAgent { pub fn new(server: Handle) -> ClientAgent { - ClientAgent { server } + ClientAgent { + server, + player_id: 0, + } + } + + async fn process_message(&self, msg: ClientMessage) { + trace!("Client#{} message: {:?}", self.player_id, &msg); + + match msg { + ClientMessage::Input { local_input } => self.server.lock().await.input(self.player_id, local_input), + // for now, anybody can set the state + ClientMessage::SetState { new_state } => self.server.lock().await.set_state(new_state), + ClientMessage::GetState { .. } => {} + } } pub async fn run( @@ -23,7 +38,7 @@ impl ClientAgent { let (sender, mut receiver) = channel(CHANNEL_BUFFER); // register player - let player_id = self + self.player_id = self .server .lock() .await @@ -37,7 +52,7 @@ impl ClientAgent { client_message = socket.next() => { match client_message { Some(msg) => - self.server.lock().await.process_message(player_id, msg?), + self.process_message(msg?).await, None => break Ok(()), } }, @@ -51,7 +66,7 @@ impl ClientAgent { .await; // deregister player, whether normally or due to error - self.server.lock().await.remove_player(player_id); + self.server.lock().await.remove_player(self.player_id); result } diff --git a/src/net/server.rs b/src/net/server.rs index 5f72e48..a523c83 100644 --- a/src/net/server.rs +++ b/src/net/server.rs @@ -96,24 +96,19 @@ impl Server { Ok(player_id) } - pub fn process_message(&mut self, player: PlayerId, msg: ClientMessage) { - trace!("Client#{} message: {:?}", player, &msg); - - match msg { - ClientMessage::Input { local_input } => { - if let Some(Some(player)) = self.players.get_mut(player) { - player.input = local_input; - } - } - // for now, anybody can set the state - ClientMessage::SetState { new_state } => self.broadcast(ServerMessage::SetState { - player_id: None, - state: new_state, - }), - ClientMessage::GetState { .. } => {} + pub fn input(&mut self, player: PlayerId, local_input: Value) { + if let Some(Some(player)) = self.players.get_mut(player) { + player.input = local_input; } } + pub fn set_state(&mut self, new_state: Value) { + self.broadcast(ServerMessage::SetState { + player_id: None, + state: new_state, + }) + } + fn tick(&mut self, tick: Instant) { trace!("Tick {:?}", tick);