diff --git a/src/game.rs b/src/game.rs index 22fac56..6d620f4 100644 --- a/src/game.rs +++ b/src/game.rs @@ -1,17 +1,18 @@ use std::sync::Arc; -use tokio::sync::{ mpsc, Mutex}; +use tokio::sync::{ mpsc, Mutex }; +use tokio::sync::mpsc::error::TryRecvError; use crate::message::Message; #[derive(Clone)] pub struct GameController { - pub channels: Arc>>, + pub channels: Arc>, } impl std::default::Default for GameController { fn default() -> Self { - let channels = Arc::new(Mutex::new(Vec::new())); + let channels = Arc::new(Mutex::new(Channels::default())); GameController { channels } } } @@ -21,6 +22,29 @@ pub struct Channel { pub rx: mpsc::Receiver, } +#[derive(Default)] +pub struct Channels(Vec); + +impl Channels { + pub fn try_recv(&mut self) -> Result { + for channel in self.0.iter_mut() { + let res = channel.rx.try_recv(); + if !(res == Err(TryRecvError::Empty)) { + return res + } + } + Err(TryRecvError::Empty) + } + pub async fn broadcast(&mut self, msg: Message) { + for channel in self.0.iter_mut() { + channel.tx.send(msg.clone()).await.unwrap(); + } + } + pub fn push(&mut self, channel: Channel) { + self.0.push(channel); + } +} + pub fn channel_pair() -> (Channel, Channel) { let (atx, brx) = mpsc::channel(32); let (btx, arx) = mpsc::channel(32); @@ -29,6 +53,18 @@ pub fn channel_pair() -> (Channel, Channel) { impl GameController { pub async fn run_loop(&self) { - todo!(); + loop { + let mut channels = self.channels.lock().await; + if let Ok(msg) = channels.try_recv() { + dispatch(&mut channels, msg).await; + } + } } } + +async fn dispatch(channels: &mut Channels, msg: Message) { + match msg.command.as_str() { + "CHAT" => channels.broadcast(msg).await, + _ => () + }; +} diff --git a/src/message.rs b/src/message.rs index 99720f9..dba1ab0 100644 --- a/src/message.rs +++ b/src/message.rs @@ -5,7 +5,7 @@ use lazy_static::lazy_static; use tokio::net::TcpStream; use tokio_tungstenite::{tungstenite::Message as WsMessage, WebSocketStream}; -#[derive(PartialEq, Debug)] +#[derive(PartialEq, Debug, Clone)] pub struct Message { pub command: String, pub args: Vec,