odyssey-server/src/game.rs

94 lines
1.9 KiB
Rust
Raw Normal View History

2020-10-05 13:11:41 +00:00
use crate::{
messages::{ClientMessage, ServerMessage},
network::{NetworkMessage, NetworkPayload},
};
2020-10-05 00:24:23 +00:00
use async_std::sync::Arc;
use async_std::sync::RwLock;
2020-10-04 02:14:23 +00:00
use async_std::sync::{Receiver, Sender};
2020-10-04 15:26:42 +00:00
use shipyard::{error, World};
2020-10-04 02:14:23 +00:00
use std::collections::HashMap;
2020-10-05 13:11:41 +00:00
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<usize, Player>,
2020-10-05 13:11:41 +00:00
net_out: Sender<NetworkMessage<ServerMessage>>,
}
impl Game {
2020-10-05 13:11:41 +00:00
pub fn new(net_out: Sender<NetworkMessage<ServerMessage>>) -> Self {
// Create world
let world = World::default();
2020-10-05 00:24:23 +00:00
// Create init workload
world.run(|| {
//todo
});
// Create update workload
world.add_workload("update").build();
Game {
world,
players: HashMap::new(),
2020-10-04 02:14:23 +00:00
net_out,
}
}
2020-10-04 15:26:42 +00:00
pub fn update(&self) -> Result<(), error::RunWorkload> {
self.world.try_run_workload("update")
}
2020-10-05 13:11:41 +00:00
pub async fn read_loop(
game: Arc<RwLock<Self>>,
net_in: Receiver<NetworkMessage<ClientMessage>>,
) {
2020-10-04 02:14:23 +00:00
loop {
let message = net_in.recv().await.expect("could not read from channel");
2020-10-05 00:24:23 +00:00
match message.data {
NetworkPayload::Connected => {
log::info!("[{:?}] connected", &message.conn_id);
game.write()
.await
.players
.insert(message.conn_id, Player {});
2020-10-05 13:11:41 +00:00
// 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);
2020-10-05 00:24:23 +00:00
}
NetworkPayload::Message(msg) => {
log::info!("[{:?}] said {:?}", &message.conn_id, msg);
}
2020-10-05 13:11:41 +00:00
NetworkPayload::InvalidFormat(err) => send!(
game,
message.conn_id,
NetworkPayload::Message(ServerMessage::Error(err))
),
2020-10-05 00:24:23 +00:00
}
2020-10-04 02:14:23 +00:00
}
}
}