use crate::{ messages::{ClientMessage, ServerMessage}, network::{NetworkMessage, NetworkPayload}, }; use async_std::sync::Arc; use async_std::sync::RwLock; use async_std::sync::{Receiver, Sender}; use shipyard::{error, World}; use std::collections::HashMap; macro_rules! send { ($g:ident, $id:expr, $e:expr) => { $g.write() .await .net_out .send(NetworkMessage { conn_id: $id, data: $e, }) .await }; } pub struct Player {} pub struct Game { world: World, players: HashMap, net_out: Sender>, } impl Game { pub fn new(net_out: Sender>) -> Self { // Create world let world = World::default(); // Create init workload world.run(|| { //todo }); // Create update workload world.add_workload("update").build(); Game { world, players: HashMap::new(), net_out, } } pub fn update(&self) -> Result<(), error::RunWorkload> { self.world.try_run_workload("update") } pub async fn read_loop( game: Arc>, net_in: Receiver>, ) { loop { let message = net_in.recv().await.expect("could not read from channel"); match message.data { NetworkPayload::Connected => { log::info!("[{:?}] connected", &message.conn_id); game.write() .await .players .insert(message.conn_id, Player {}); // Say hellO! send!( game, message.conn_id, NetworkPayload::Message(ServerMessage::Hello( "unnamed-server".to_string(), "odynet-a1".to_string() )) ); } NetworkPayload::Disconnected => { log::info!("[{:?}] disconnected", &message.conn_id); } NetworkPayload::Message(msg) => { log::info!("[{:?}] said {:?}", &message.conn_id, msg); } NetworkPayload::InvalidFormat(err) => send!( game, message.conn_id, NetworkPayload::Message(ServerMessage::Error(err)) ), } } } }