cg_game_server/
server.rs

1//! This module helps implement a `GameServer` for the WebSocket endpoints to communicate via.
2//!
3//! For examples see [the official games](https://github.com/orgs/code-game-project/teams/games/repositories)
4
5use crate::events::{Connect, Disconnect, EventWrapper, Join, Leave};
6use actix::{Actor, Addr, Handler};
7use std::collections::{HashMap, HashSet};
8
9/// A type to indicate that this is not just any string but a `GameID`
10pub type GameID = String;
11/// A type to indicate that this is not just any string but a `SocketID`
12pub type SocketID = String;
13/// A `HashMap` of `SocketID`s and their corresponding `Addr`s
14pub type SocketsMap<C> = HashMap<SocketID, Addr<C>>;
15/// A `HashMap` of `GameID`s and the playing `SocketID`s
16pub type GamesMap = HashMap<GameID, HashSet<SocketID>>;
17
18/// A constant id to be used as as the `from` property in `events::EventWrapper` when the server is the sender
19pub const SERVER_ID: &str = "server";
20
21/// A generic game server that can be implemented and extended to fit any game's needs
22///
23/// A struct that implements `GameServer` should have a bare minimum of two fields:
24/// `sockets: SocketsMap<SomeSocket>` and `games: GamesMap`
25pub trait GameServer<C, S>
26where
27	Self: Actor,
28	Self: Handler<EventWrapper<S>>,
29	Self: Handler<EventWrapper<Connect<C>>>,
30	Self: Handler<EventWrapper<Disconnect>>,
31	Self: Handler<EventWrapper<Join>>,
32	Self: Handler<EventWrapper<Leave>>,
33	C: Actor,
34{
35	/// Creates a new instance of `GameServer`
36	fn new() -> Self;
37	/// Inserts an `Addr` and its `id` into the `SocketsMap`
38	fn connect(&mut self, id: SocketID, addr: Addr<C>);
39	/// Removes an `Addr` from the `SocketsMap`
40	fn disconnect(&mut self, id: &SocketID);
41	/// Creates a new game by adding a new game key to the `GamesMap`
42	fn new_game(&mut self, game_id: GameID);
43	/// Ends and removes a game by removing it from the `GamesMap`
44	fn end_game(&mut self, game_id: &GameID);
45	/// Associates a `SocketID` with a game in the `GamesMap`
46	fn join_game(&mut self, id: SocketID, event: Join);
47	/// Disassociates a `SocketID` with a game in the `GamesMap`
48	fn leave_game(&mut self, id: &SocketID, event: Leave);
49	/// Matches the `event.to: EventTarget` and emits the event to the correct destination
50	fn emit(&self, event: EventWrapper<S>);
51	/// Emits an event to all sockets in a particular game
52	fn emit_to_game(&self, game_id: &GameID, event: EventWrapper<S>);
53	/// Emits an event to a particular socket
54	fn emit_to_socket(&self, id: &SocketID, event: EventWrapper<S>);
55}