SeaBattle/sea_battle_backend/src/human_player_ws.rs

271 lines
8.2 KiB
Rust
Raw Normal View History

2022-09-11 14:48:20 +00:00
use std::sync::Arc;
2022-09-15 15:45:52 +00:00
use std::time::{Duration, Instant};
2022-09-11 14:48:20 +00:00
2022-09-15 15:45:52 +00:00
use actix::prelude::*;
2022-09-15 16:04:22 +00:00
use actix::{Actor, Handler, StreamHandler};
2022-09-11 14:48:20 +00:00
use actix_web_actors::ws;
use actix_web_actors::ws::{CloseCode, CloseReason, Message, ProtocolError, WebsocketContext};
use uuid::Uuid;
2022-09-22 15:53:25 +00:00
use crate::bots::intermediate_bot::IntermediateBot;
2022-09-19 17:29:11 +00:00
use crate::bots::linear_bot::LinearBot;
2022-09-17 10:02:13 +00:00
use crate::bots::random_bot::RandomBot;
2022-09-22 16:12:23 +00:00
use crate::bots::smart_bot::SmartBot;
2022-09-19 17:29:11 +00:00
use crate::data::{BoatsLayout, BotType, Coordinates, CurrentGameStatus, FireResult, GameRules};
2022-09-24 09:46:12 +00:00
use crate::dispatcher_actor::{AcceptInvite, CreateInvite, DispatcherActor};
use crate::game::{AddPlayer, Game};
2022-09-11 14:48:20 +00:00
use crate::human_player::HumanPlayer;
2022-09-15 15:45:52 +00:00
/// How often heartbeat pings are sent
const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(10);
/// How long before lack of client response causes a timeout
const CLIENT_TIMEOUT: Duration = Duration::from_secs(120);
2022-09-24 09:46:12 +00:00
#[derive(Debug)]
2022-09-11 14:48:20 +00:00
pub enum StartMode {
Bot(GameRules),
2022-09-24 09:46:12 +00:00
CreateInvite(GameRules),
AcceptInvite { code: String },
// TODO : random human
2022-09-11 14:48:20 +00:00
}
2022-09-14 16:02:11 +00:00
#[derive(serde::Deserialize, serde::Serialize, Debug)]
2022-09-11 15:03:13 +00:00
#[serde(tag = "type")]
2022-09-11 14:48:20 +00:00
pub enum ClientMessage {
StopGame,
2022-09-14 16:02:11 +00:00
BoatsLayout { layout: BoatsLayout },
2022-09-14 16:30:33 +00:00
Fire { location: Coordinates },
2022-09-16 14:55:29 +00:00
RequestRematch,
AcceptRematch,
RejectRematch,
2022-09-11 14:48:20 +00:00
}
#[derive(Message)]
#[rtype(result = "()")]
2022-09-17 10:02:13 +00:00
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
2022-09-11 15:03:13 +00:00
#[serde(tag = "type")]
2022-09-11 14:48:20 +00:00
pub enum ServerMessage {
2022-09-24 09:46:12 +00:00
SetInviteCode {
code: String,
},
InvalidInviteCode,
2022-09-12 14:38:14 +00:00
WaitingForAnotherPlayer,
2022-09-15 18:13:06 +00:00
SetOpponentName {
name: String,
},
2022-09-15 15:37:26 +00:00
QueryBoatsLayout {
rules: GameRules,
},
2022-09-15 16:04:22 +00:00
RejectedBoatsLayout {
errors: Vec<String>,
},
2022-09-12 14:38:14 +00:00
WaitingForOtherPlayerConfiguration,
2022-09-16 14:55:29 +00:00
OpponentReady,
GameStarting,
2022-09-16 14:55:29 +00:00
OpponentMustFire {
2022-09-15 15:37:26 +00:00
status: CurrentGameStatus,
},
RequestFire {
status: CurrentGameStatus,
},
2022-09-22 15:53:25 +00:00
FireResult {
2022-09-15 15:37:26 +00:00
pos: Coordinates,
result: FireResult,
},
2022-09-22 15:53:25 +00:00
OpponentFireResult {
2022-09-15 15:37:26 +00:00
pos: Coordinates,
result: FireResult,
},
LostGame {
2022-09-19 17:29:11 +00:00
status: CurrentGameStatus,
2022-09-15 15:37:26 +00:00
},
WonGame {
2022-09-19 17:29:11 +00:00
status: CurrentGameStatus,
2022-09-15 15:37:26 +00:00
},
2022-09-16 14:55:29 +00:00
OpponentRequestedRematch,
OpponentAcceptedRematch,
OpponentRejectedRematch,
OpponentLeftGame,
OpponentReplacedByBot,
2022-09-11 14:48:20 +00:00
}
2022-09-24 09:46:12 +00:00
#[derive(Message)]
#[rtype(result = "()")]
pub struct SetGame(pub Addr<Game>);
#[derive(Message)]
#[rtype(result = "()")]
pub struct CloseConnection;
2022-09-11 14:48:20 +00:00
pub struct HumanPlayerWS {
inner: Option<Arc<HumanPlayer>>,
pub start_mode: StartMode,
2022-09-15 15:45:52 +00:00
hb: Instant,
2022-09-24 09:46:12 +00:00
dispatcher: Addr<DispatcherActor>,
name: String,
2022-09-15 15:45:52 +00:00
}
2022-09-24 09:46:12 +00:00
impl HumanPlayerWS {
pub fn new(start_mode: StartMode, dispatcher: &Addr<DispatcherActor>, name: String) -> Self {
2022-09-15 15:45:52 +00:00
Self {
inner: None,
2022-09-24 09:46:12 +00:00
start_mode,
2022-09-15 15:45:52 +00:00
hb: Instant::now(),
2022-09-24 09:46:12 +00:00
dispatcher: dispatcher.clone(),
name,
2022-09-15 15:45:52 +00:00
}
}
2022-09-11 14:48:20 +00:00
2022-09-15 15:45:52 +00:00
/// helper method that sends ping to client every second.
///
/// also this method checks heartbeats from client
fn hb(&self, ctx: &mut <Self as Actor>::Context) {
ctx.run_interval(HEARTBEAT_INTERVAL, |act, ctx| {
// check client heartbeats
if Instant::now().duration_since(act.hb) > CLIENT_TIMEOUT {
// heartbeat timed out
println!("Websocket Client heartbeat failed, disconnecting!");
// stop actor
ctx.stop();
// don't try to send a ping
return;
}
ctx.ping(b"");
});
}
2022-09-11 14:48:20 +00:00
fn send_message(&self, msg: ServerMessage, ctx: &mut <HumanPlayerWS as Actor>::Context) {
ctx.text(serde_json::to_string(&msg).unwrap());
}
}
impl Actor for HumanPlayerWS {
type Context = WebsocketContext<Self>;
fn started(&mut self, ctx: &mut Self::Context) {
2022-09-15 15:45:52 +00:00
self.hb(ctx);
2022-09-12 14:38:14 +00:00
self.send_message(ServerMessage::WaitingForAnotherPlayer, ctx);
2022-09-11 14:48:20 +00:00
// Start game, according to appropriate start mode
match &self.start_mode {
StartMode::Bot(rules) => {
2022-09-13 17:12:16 +00:00
log::debug!("Start play with a bot");
2022-09-11 14:48:20 +00:00
let game = Game::new(rules.clone()).start();
match rules.bot_type {
BotType::Random => {
game.do_send(AddPlayer(Arc::new(RandomBot::new(game.clone()))));
}
2022-09-17 10:02:13 +00:00
BotType::Linear => {
game.do_send(AddPlayer(Arc::new(LinearBot::new(game.clone()))));
}
2022-09-22 15:53:25 +00:00
BotType::Intermediate => {
game.do_send(AddPlayer(Arc::new(IntermediateBot::new(game.clone()))));
}
2022-09-22 16:12:23 +00:00
BotType::Smart => {
game.do_send(AddPlayer(Arc::new(SmartBot::new(game.clone()))));
}
2022-09-11 14:48:20 +00:00
};
let player = Arc::new(HumanPlayer {
2022-09-24 09:46:12 +00:00
name: self.name.to_string(),
2022-09-11 14:48:20 +00:00
game: game.clone(),
player: ctx.address(),
uuid: Uuid::new_v4(),
});
self.inner = Some(player.clone());
game.do_send(AddPlayer(player));
2022-09-11 14:48:20 +00:00
}
2022-09-24 09:46:12 +00:00
StartMode::CreateInvite(rules) => {
log::info!("Create new play invite");
self.dispatcher
.do_send(CreateInvite(rules.clone(), ctx.address()));
}
StartMode::AcceptInvite { code } => {
log::info!("Accept play invite {}", code);
self.dispatcher
.do_send(AcceptInvite(code.clone(), ctx.address()));
2022-09-11 14:48:20 +00:00
}
}
}
fn stopped(&mut self, _ctx: &mut Self::Context) {
if let Some(player) = &self.inner {
player.handle_client_message(ClientMessage::StopGame);
}
}
}
2022-09-15 15:37:26 +00:00
impl StreamHandler<Result<ws::Message, ProtocolError>> for HumanPlayerWS {
2022-09-11 14:48:20 +00:00
fn handle(&mut self, msg: Result<Message, ProtocolError>, ctx: &mut Self::Context) {
match msg {
2022-09-15 15:45:52 +00:00
Ok(Message::Ping(msg)) => {
self.hb = Instant::now();
ctx.pong(&msg);
}
2022-09-11 14:48:20 +00:00
Ok(Message::Binary(_bin)) => log::warn!("Got unsupported binary message!"),
Ok(Message::Text(msg)) => match serde_json::from_str::<ClientMessage>(&msg) {
Ok(msg) => match &self.inner {
None => {
log::error!("Client tried to send message without game!");
ctx.text("No game yet!");
}
Some(p) => p.handle_client_message(msg),
},
Err(e) => log::warn!("Got invalid message from client! {:?}", e),
},
Ok(Message::Nop) => log::warn!("Got WS nop"),
Ok(Message::Continuation(_)) => {
log::warn!("Got unsupported continuation message!");
}
Ok(Message::Pong(_)) => {
log::info!("Got pong message");
2022-09-15 15:45:52 +00:00
self.hb = Instant::now();
2022-09-11 14:48:20 +00:00
}
Ok(Message::Close(reason)) => {
log::info!("Client asked to close this socket! reason={:?}", reason);
ctx.close(Some(CloseReason::from(CloseCode::Away)));
}
Err(e) => log::warn!("Websocket protocol error! {:?}", e),
}
}
}
impl Handler<ServerMessage> for HumanPlayerWS {
type Result = ();
fn handle(&mut self, msg: ServerMessage, ctx: &mut Self::Context) -> Self::Result {
ctx.text(serde_json::to_string(&msg).unwrap());
}
}
2022-09-24 09:46:12 +00:00
impl Handler<SetGame> for HumanPlayerWS {
type Result = ();
fn handle(&mut self, msg: SetGame, ctx: &mut Self::Context) -> Self::Result {
let game = msg.0;
let player = Arc::new(HumanPlayer {
name: self.name.clone(),
game: game.clone(),
player: ctx.address(),
uuid: Uuid::new_v4(),
});
self.inner = Some(player.clone());
game.do_send(AddPlayer(player));
}
}
impl Handler<CloseConnection> for HumanPlayerWS {
type Result = ();
fn handle(&mut self, _msg: CloseConnection, ctx: &mut Self::Context) -> Self::Result {
ctx.close(None)
}
}