From 0f010aca2957468c46cd849284873cb26f3a0df3 Mon Sep 17 00:00:00 2001 From: stale Date: Fri, 13 May 2022 17:49:36 -0300 Subject: laying the groundwork for rooms --- src/types.rs | 88 +++++++++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 76 insertions(+), 12 deletions(-) (limited to 'src/types.rs') diff --git a/src/types.rs b/src/types.rs index 54a93bc..86f1e32 100644 --- a/src/types.rs +++ b/src/types.rs @@ -1,7 +1,12 @@ use std::{ collections::HashMap, net::SocketAddr, - sync::Arc, + sync::{ + Arc, + atomic::{ AtomicUsize, Ordering }, + }, + fmt::Display, + ops::{ Deref, DerefMut }, }; use warp::ws::Message; use tokio::sync::RwLock; @@ -15,10 +20,28 @@ pub struct Config { pub socket_addr: SocketAddr, } -#[derive(Debug, Clone)] -pub struct State { - pub conf: Config, - pub peers: PeerMap, +#[derive(Debug, Clone, Copy)] +pub struct BoardConf { + pub w: usize, + pub h: usize, + /// tiles to mines, expressed as (numerator, denominator) + pub mine_ratio: (usize,usize), +} + +impl Display for BoardConf { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}x{} {}/{}", self.w, self.h, self.mine_ratio.0, self.mine_ratio.1) + } +} + +#[derive(Debug)] +pub struct Room { + pub name: String, + pub players: PlayerMap, + pub peer_limit: u32, + pub driver: tokio::task::JoinHandle<()>, + pub cmd_stream: CmdTx, + pub board_conf: BoardConf, } #[derive(Debug)] @@ -29,19 +52,60 @@ pub enum MetaMove { } #[derive(Debug)] -pub struct Peer { +pub struct Conn { pub tx: tokio::sync::mpsc::UnboundedSender, - pub seq_id: usize, + pub addr: SocketAddr, +} + +#[derive(Debug)] +pub struct Player { + pub conn: Conn, + pub uid: usize, pub name: String, pub clr: String, pub position: (usize, usize), } -pub struct ConnData { - pub cmd_tx: CmdTx, - pub remote_addr: SocketAddr, - pub peers: PeerMap, +impl Display for Player { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "\"{}\"@{}", self.name, self.conn.addr) + } } pub type CmdTx = tokio::sync::mpsc::UnboundedSender; -pub type PeerMap = Arc>>; +pub type PlayerMapData = Arc>>; +#[derive(Debug)] +pub struct PlayerMap { + inner: PlayerMapData, + uid_counter: AtomicUsize, +} + +impl Deref for PlayerMap { + type Target = Arc>>; + fn deref(&self) -> &Self::Target { + &self.inner + } +} +impl DerefMut for PlayerMap { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.inner + } +} +impl Default for PlayerMap { + fn default() -> Self { + Self { inner: Arc::new(RwLock::new(HashMap::new())), uid_counter: 0.into() } + } +} + +impl PlayerMap { + pub async fn insert_conn(&mut self, conn: Conn, name: String, clr: String) -> usize { + let mut map = self.write().await; + let uid = self.uid_counter.fetch_add(1, Ordering::Relaxed); + map.insert( + conn.addr, + Player { conn, uid, name, clr, position: (0,0) }, + ); + uid + } +} + -- cgit v1.2.3