Can request for boats configuration
This commit is contained in:
parent
33426a6cd6
commit
6e7a0799eb
87
Cargo.lock
generated
87
Cargo.lock
generated
@ -2,6 +2,30 @@
|
|||||||
# It is not intended for manual editing.
|
# It is not intended for manual editing.
|
||||||
version = 3
|
version = 3
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "actix"
|
||||||
|
version = "0.13.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f728064aca1c318585bf4bb04ffcfac9e75e508ab4e8b1bd9ba5dfe04e2cbed5"
|
||||||
|
dependencies = [
|
||||||
|
"actix-rt",
|
||||||
|
"actix_derive",
|
||||||
|
"bitflags",
|
||||||
|
"bytes",
|
||||||
|
"crossbeam-channel",
|
||||||
|
"futures-core",
|
||||||
|
"futures-sink",
|
||||||
|
"futures-task",
|
||||||
|
"futures-util",
|
||||||
|
"log",
|
||||||
|
"once_cell",
|
||||||
|
"parking_lot",
|
||||||
|
"pin-project-lite",
|
||||||
|
"smallvec",
|
||||||
|
"tokio",
|
||||||
|
"tokio-util",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "actix-codec"
|
name = "actix-codec"
|
||||||
version = "0.5.0"
|
version = "0.5.0"
|
||||||
@ -101,6 +125,7 @@ version = "2.7.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "7ea16c295198e958ef31930a6ef37d0fb64e9ca3b6116e6b93a8bdae96ee1000"
|
checksum = "7ea16c295198e958ef31930a6ef37d0fb64e9ca3b6116e6b93a8bdae96ee1000"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"actix-macros",
|
||||||
"futures-core",
|
"futures-core",
|
||||||
"tokio",
|
"tokio",
|
||||||
]
|
]
|
||||||
@ -184,6 +209,23 @@ dependencies = [
|
|||||||
"url",
|
"url",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "actix-web-actors"
|
||||||
|
version = "4.1.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "31efe7896f3933ce03dd4710be560254272334bb321a18fd8ff62b1a557d9d19"
|
||||||
|
dependencies = [
|
||||||
|
"actix",
|
||||||
|
"actix-codec",
|
||||||
|
"actix-http",
|
||||||
|
"actix-web",
|
||||||
|
"bytes",
|
||||||
|
"bytestring",
|
||||||
|
"futures-core",
|
||||||
|
"pin-project-lite",
|
||||||
|
"tokio",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "actix-web-codegen"
|
name = "actix-web-codegen"
|
||||||
version = "4.0.1"
|
version = "4.0.1"
|
||||||
@ -196,6 +238,17 @@ dependencies = [
|
|||||||
"syn",
|
"syn",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "actix_derive"
|
||||||
|
version = "0.6.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "6d44b8fee1ced9671ba043476deddef739dd0959bf77030b26b738cc591737a7"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "adler"
|
name = "adler"
|
||||||
version = "1.0.2"
|
version = "1.0.2"
|
||||||
@ -400,6 +453,26 @@ dependencies = [
|
|||||||
"cfg-if",
|
"cfg-if",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "crossbeam-channel"
|
||||||
|
version = "0.5.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c2dd04ddaf88237dc3b8d8f9a3c1004b506b54b3313403944054d23c0870c521"
|
||||||
|
dependencies = [
|
||||||
|
"cfg-if",
|
||||||
|
"crossbeam-utils",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "crossbeam-utils"
|
||||||
|
version = "0.8.11"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "51887d4adc7b564537b15adcfb307936f8075dfcd5f00dde9a9f1d29383682bc"
|
||||||
|
dependencies = [
|
||||||
|
"cfg-if",
|
||||||
|
"once_cell",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "crypto-common"
|
name = "crypto-common"
|
||||||
version = "0.1.6"
|
version = "0.1.6"
|
||||||
@ -938,12 +1011,17 @@ checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd"
|
|||||||
name = "sea_battle_backend"
|
name = "sea_battle_backend"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"actix",
|
||||||
"actix-cors",
|
"actix-cors",
|
||||||
|
"actix-rt",
|
||||||
"actix-web",
|
"actix-web",
|
||||||
|
"actix-web-actors",
|
||||||
"clap",
|
"clap",
|
||||||
"env_logger",
|
"env_logger",
|
||||||
"log",
|
"log",
|
||||||
"serde",
|
"serde",
|
||||||
|
"serde_json",
|
||||||
|
"uuid",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@ -1198,6 +1276,15 @@ dependencies = [
|
|||||||
"percent-encoding",
|
"percent-encoding",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "uuid"
|
||||||
|
version = "1.1.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "dd6469f4314d5f1ffec476e05f17cc9a78bc7a27a6a857842170bdf8d6f98d2f"
|
||||||
|
dependencies = [
|
||||||
|
"getrandom",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "version_check"
|
name = "version_check"
|
||||||
version = "0.9.4"
|
version = "0.9.4"
|
||||||
|
@ -10,5 +10,10 @@ clap = { version = "3.2.17", features = ["derive"] }
|
|||||||
log = "0.4.17"
|
log = "0.4.17"
|
||||||
env_logger = "0.9.0"
|
env_logger = "0.9.0"
|
||||||
serde = { version = "1.0.144", features = ["derive"] }
|
serde = { version = "1.0.144", features = ["derive"] }
|
||||||
|
serde_json = "1.0.85"
|
||||||
actix-web = "4.1.0"
|
actix-web = "4.1.0"
|
||||||
actix-cors = "0.6.2"
|
actix-cors = "0.6.2"
|
||||||
|
actix = "0.13.0"
|
||||||
|
actix-web-actors = "4.1.0"
|
||||||
|
actix-rt = "2.7.0"
|
||||||
|
uuid = { version = "1.1.2", features = ["v4"] }
|
45
src/data.rs
45
src/data.rs
@ -1,5 +1,16 @@
|
|||||||
use crate::consts::*;
|
use crate::consts::*;
|
||||||
|
|
||||||
|
#[derive(serde::Serialize, serde::Deserialize, Debug, Copy, Clone)]
|
||||||
|
pub enum BotType {
|
||||||
|
Random,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Serialize)]
|
||||||
|
struct BotDescription {
|
||||||
|
r#type: BotType,
|
||||||
|
description: String,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize)]
|
#[derive(serde::Serialize)]
|
||||||
pub struct PlayConfiguration {
|
pub struct PlayConfiguration {
|
||||||
min_boat_len: usize,
|
min_boat_len: usize,
|
||||||
@ -10,6 +21,7 @@ pub struct PlayConfiguration {
|
|||||||
max_map_height: usize,
|
max_map_height: usize,
|
||||||
min_boats_number: usize,
|
min_boats_number: usize,
|
||||||
max_boats_number: usize,
|
max_boats_number: usize,
|
||||||
|
bot_types: Vec<BotDescription>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for PlayConfiguration {
|
impl Default for PlayConfiguration {
|
||||||
@ -23,17 +35,22 @@ impl Default for PlayConfiguration {
|
|||||||
max_map_height: MAX_MAP_HEIGHT,
|
max_map_height: MAX_MAP_HEIGHT,
|
||||||
min_boats_number: MIN_BOATS_NUMBER,
|
min_boats_number: MIN_BOATS_NUMBER,
|
||||||
max_boats_number: MAX_BOATS_NUMBER,
|
max_boats_number: MAX_BOATS_NUMBER,
|
||||||
|
bot_types: vec![BotDescription {
|
||||||
|
r#type: BotType::Random,
|
||||||
|
description: "Random strike. All the time.".to_string(),
|
||||||
|
}],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
|
||||||
pub struct GameRules {
|
pub struct GameRules {
|
||||||
pub map_width: usize,
|
pub map_width: usize,
|
||||||
pub map_height: usize,
|
pub map_height: usize,
|
||||||
pub boats: Vec<usize>,
|
pub boats_str: String,
|
||||||
pub boats_can_touch: bool,
|
pub boats_can_touch: bool,
|
||||||
pub player_continue_on_hit: bool,
|
pub player_continue_on_hit: bool,
|
||||||
|
pub bot_type: BotType,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl GameRules {
|
impl GameRules {
|
||||||
@ -41,12 +58,24 @@ impl GameRules {
|
|||||||
Self {
|
Self {
|
||||||
map_width: MULTI_PLAYER_MAP_WIDTH,
|
map_width: MULTI_PLAYER_MAP_WIDTH,
|
||||||
map_height: MULTI_PLAYER_MAP_HEIGHT,
|
map_height: MULTI_PLAYER_MAP_HEIGHT,
|
||||||
boats: MULTI_PLAYER_PLAYER_BOATS.to_vec(),
|
boats_str: MULTI_PLAYER_PLAYER_BOATS
|
||||||
|
.iter()
|
||||||
|
.map(usize::to_string)
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(","),
|
||||||
boats_can_touch: MULTI_PLAYER_BOATS_CAN_TOUCH,
|
boats_can_touch: MULTI_PLAYER_BOATS_CAN_TOUCH,
|
||||||
player_continue_on_hit: MULTI_PLAYER_PLAYER_CAN_CONTINUE_AFTER_HIT,
|
player_continue_on_hit: MULTI_PLAYER_PLAYER_CAN_CONTINUE_AFTER_HIT,
|
||||||
|
bot_type: BotType::Random,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn boats(&self) -> Vec<usize> {
|
||||||
|
self.boats_str
|
||||||
|
.split(',')
|
||||||
|
.map(|s| s.parse::<usize>().unwrap_or_default())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
pub fn get_errors(&self) -> Vec<&str> {
|
pub fn get_errors(&self) -> Vec<&str> {
|
||||||
let config = PlayConfiguration::default();
|
let config = PlayConfiguration::default();
|
||||||
|
|
||||||
@ -60,10 +89,18 @@ impl GameRules {
|
|||||||
errors.push("Map height is outside bounds!");
|
errors.push("Map height is outside bounds!");
|
||||||
}
|
}
|
||||||
|
|
||||||
if self.boats.len() < config.min_boat_len || self.boats.len() > config.max_boat_len {
|
if self.boats().len() < config.min_boats_number
|
||||||
|
|| self.boats().len() > config.max_boats_number
|
||||||
|
{
|
||||||
errors.push("Number of boats is invalid!");
|
errors.push("Number of boats is invalid!");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
for boat in self.boats() {
|
||||||
|
if boat < config.min_boat_len || boat > config.max_boat_len {
|
||||||
|
errors.push("A boat has an invalid length");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
errors
|
errors
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
83
src/game.rs
Normal file
83
src/game.rs
Normal file
@ -0,0 +1,83 @@
|
|||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use crate::data::GameRules;
|
||||||
|
use crate::human_player::HumanPlayer;
|
||||||
|
use crate::random_bot::RandomBot;
|
||||||
|
use actix::prelude::*;
|
||||||
|
use actix::{Actor, Context, Handler};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
pub trait Player {
|
||||||
|
fn get_name(&self) -> &str;
|
||||||
|
|
||||||
|
fn get_uid(&self) -> Uuid;
|
||||||
|
|
||||||
|
fn query_boats_layout(&self, rules: &GameRules);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub enum PlayerWrapper {
|
||||||
|
Human(Arc<HumanPlayer>),
|
||||||
|
RandomBot(RandomBot),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PlayerWrapper {
|
||||||
|
fn extract(self) -> Arc<dyn Player> {
|
||||||
|
match self {
|
||||||
|
PlayerWrapper::Human(h) => h,
|
||||||
|
PlayerWrapper::RandomBot(r) => Arc::new(r),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default, Eq, PartialEq, Debug, Copy, Clone)]
|
||||||
|
enum GameStatus {
|
||||||
|
#[default]
|
||||||
|
Created,
|
||||||
|
WaitingForBoatsDisposition,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Game {
|
||||||
|
rules: GameRules,
|
||||||
|
players: Vec<Arc<dyn Player>>,
|
||||||
|
status: GameStatus,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Game {
|
||||||
|
pub fn new(rules: GameRules) -> Self {
|
||||||
|
Self {
|
||||||
|
rules,
|
||||||
|
players: vec![],
|
||||||
|
status: GameStatus::Created,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Once the two player has been registered, the game may start
|
||||||
|
fn start_game(&mut self) {
|
||||||
|
assert_eq!(self.status, GameStatus::Created);
|
||||||
|
self.status = GameStatus::WaitingForBoatsDisposition;
|
||||||
|
self.players[0].query_boats_layout(&self.rules);
|
||||||
|
self.players[1].query_boats_layout(&self.rules);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Actor for Game {
|
||||||
|
type Context = Context<Self>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Message)]
|
||||||
|
#[rtype(result = "()")]
|
||||||
|
pub struct AddPlayer(pub PlayerWrapper);
|
||||||
|
|
||||||
|
impl Handler<AddPlayer> for Game {
|
||||||
|
type Result = ();
|
||||||
|
|
||||||
|
/// Add a new player to the game
|
||||||
|
fn handle(&mut self, msg: AddPlayer, _ctx: &mut Self::Context) -> Self::Result {
|
||||||
|
assert!(self.players.len() < 2);
|
||||||
|
self.players.push(msg.0.extract());
|
||||||
|
|
||||||
|
if self.players.len() == 2 {
|
||||||
|
self.start_game();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
34
src/human_player.rs
Normal file
34
src/human_player.rs
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
use crate::data::GameRules;
|
||||||
|
use actix::Addr;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use crate::game::{Game, Player};
|
||||||
|
use crate::human_player_ws::{ClientMessage, HumanPlayerWS, ServerMessage};
|
||||||
|
|
||||||
|
pub struct HumanPlayer {
|
||||||
|
pub name: String,
|
||||||
|
pub game: Addr<Game>,
|
||||||
|
pub player: Addr<HumanPlayerWS>,
|
||||||
|
pub uuid: Uuid,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Player for HumanPlayer {
|
||||||
|
fn get_name(&self) -> &str {
|
||||||
|
&self.name
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_uid(&self) -> Uuid {
|
||||||
|
self.uuid
|
||||||
|
}
|
||||||
|
|
||||||
|
fn query_boats_layout(&self, rules: &GameRules) {
|
||||||
|
self.player
|
||||||
|
.do_send(ServerMessage::QueryBoatsLayout(rules.clone()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HumanPlayer {
|
||||||
|
pub fn handle_client_message(&self, msg: ClientMessage) {
|
||||||
|
log::info!("Got message from client: {:?}", msg);
|
||||||
|
}
|
||||||
|
}
|
126
src/human_player_ws.rs
Normal file
126
src/human_player_ws.rs
Normal file
@ -0,0 +1,126 @@
|
|||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use actix::prelude::*;
|
||||||
|
use actix::{Actor, Handler, StreamHandler};
|
||||||
|
use actix_web_actors::ws;
|
||||||
|
use actix_web_actors::ws::{CloseCode, CloseReason, Message, ProtocolError, WebsocketContext};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use crate::data::{BotType, GameRules};
|
||||||
|
use crate::game::{AddPlayer, Game, PlayerWrapper};
|
||||||
|
use crate::human_player::HumanPlayer;
|
||||||
|
use crate::random_bot::RandomBot;
|
||||||
|
|
||||||
|
#[derive(Default, Debug)]
|
||||||
|
pub enum StartMode {
|
||||||
|
Bot(GameRules),
|
||||||
|
|
||||||
|
#[default]
|
||||||
|
AgainstHuman,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Deserialize, Debug)]
|
||||||
|
pub enum ClientMessage {
|
||||||
|
StopGame,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Message)]
|
||||||
|
#[rtype(result = "()")]
|
||||||
|
#[derive(serde::Serialize, Debug)]
|
||||||
|
pub enum ServerMessage {
|
||||||
|
WaitingForOtherPlayer,
|
||||||
|
QueryBoatsLayout(GameRules),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct HumanPlayerWS {
|
||||||
|
inner: Option<Arc<HumanPlayer>>,
|
||||||
|
pub start_mode: StartMode,
|
||||||
|
// TODO : add heartbeat stuff
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HumanPlayerWS {
|
||||||
|
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) {
|
||||||
|
self.send_message(ServerMessage::WaitingForOtherPlayer, ctx);
|
||||||
|
|
||||||
|
// Start game, according to appropriate start mode
|
||||||
|
match &self.start_mode {
|
||||||
|
StartMode::Bot(rules) => {
|
||||||
|
let game = Game::new(rules.clone()).start();
|
||||||
|
|
||||||
|
let bot = match rules.bot_type {
|
||||||
|
BotType::Random => PlayerWrapper::RandomBot(RandomBot::new(game.clone())),
|
||||||
|
};
|
||||||
|
game.do_send(AddPlayer(bot));
|
||||||
|
|
||||||
|
let player = Arc::new(HumanPlayer {
|
||||||
|
name: "Human".to_string(),
|
||||||
|
game: game.clone(),
|
||||||
|
player: ctx.address(),
|
||||||
|
uuid: Uuid::new_v4(),
|
||||||
|
});
|
||||||
|
self.inner = Some(player.clone());
|
||||||
|
game.do_send(AddPlayer(PlayerWrapper::Human(player)));
|
||||||
|
}
|
||||||
|
|
||||||
|
StartMode::AgainstHuman => {
|
||||||
|
unimplemented!();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn stopped(&mut self, _ctx: &mut Self::Context) {
|
||||||
|
if let Some(player) = &self.inner {
|
||||||
|
player.handle_client_message(ClientMessage::StopGame);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for HumanPlayerWS {
|
||||||
|
fn handle(&mut self, msg: Result<Message, ProtocolError>, ctx: &mut Self::Context) {
|
||||||
|
match msg {
|
||||||
|
Ok(Message::Ping(msg)) => ctx.pong(&msg),
|
||||||
|
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");
|
||||||
|
// TODO : handle pong message
|
||||||
|
}
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
}
|
@ -1,2 +1,6 @@
|
|||||||
pub mod consts;
|
pub mod consts;
|
||||||
pub mod data;
|
pub mod data;
|
||||||
|
pub mod game;
|
||||||
|
pub mod human_player;
|
||||||
|
pub mod human_player_ws;
|
||||||
|
pub mod random_bot;
|
||||||
|
35
src/main.rs
35
src/main.rs
@ -1,9 +1,11 @@
|
|||||||
use actix_cors::Cors;
|
use actix_cors::Cors;
|
||||||
use actix_web::{App, HttpResponse, HttpServer, Responder, web};
|
use actix_web::{web, App, HttpRequest, HttpResponse, HttpServer, Responder};
|
||||||
|
use actix_web_actors::ws;
|
||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use env_logger::Env;
|
use env_logger::Env;
|
||||||
|
|
||||||
use sea_battle_backend::data::{GameRules, PlayConfiguration};
|
use sea_battle_backend::data::{GameRules, PlayConfiguration};
|
||||||
|
use sea_battle_backend::human_player_ws::{HumanPlayerWS, StartMode};
|
||||||
|
|
||||||
/// Simple sea battle server
|
/// Simple sea battle server
|
||||||
#[derive(Parser, Debug, Clone)]
|
#[derive(Parser, Debug, Clone)]
|
||||||
@ -33,12 +35,30 @@ async fn bot_configuration() -> impl Responder {
|
|||||||
HttpResponse::Ok().json(PlayConfiguration::default())
|
HttpResponse::Ok().json(PlayConfiguration::default())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Start bot game
|
||||||
|
async fn start_bot_play(
|
||||||
|
req: HttpRequest,
|
||||||
|
stream: web::Payload,
|
||||||
|
query: web::Query<GameRules>,
|
||||||
|
) -> Result<HttpResponse, actix_web::Error> {
|
||||||
|
let errors = query.0.get_errors();
|
||||||
|
if !errors.is_empty() {
|
||||||
|
return Ok(HttpResponse::BadRequest().json(errors));
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut player_ws = HumanPlayerWS::default();
|
||||||
|
player_ws.start_mode = StartMode::Bot(query.0.clone());
|
||||||
|
|
||||||
|
let resp = ws::start(player_ws, &req, stream);
|
||||||
|
log::info!("New bot play with configuration: {:?}", &query.0);
|
||||||
|
resp
|
||||||
|
}
|
||||||
|
|
||||||
/// Multi-players configuration
|
/// Multi-players configuration
|
||||||
async fn multi_players_config() -> impl Responder {
|
async fn multi_players_config() -> impl Responder {
|
||||||
HttpResponse::Ok().json(GameRules::multi_players_rules())
|
HttpResponse::Ok().json(GameRules::multi_players_rules())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
#[actix_web::main]
|
#[actix_web::main]
|
||||||
async fn main() -> std::io::Result<()> {
|
async fn main() -> std::io::Result<()> {
|
||||||
env_logger::Builder::from_env(Env::default().default_filter_or("info")).init();
|
env_logger::Builder::from_env(Env::default().default_filter_or("info")).init();
|
||||||
@ -47,7 +67,6 @@ async fn main() -> std::io::Result<()> {
|
|||||||
let args_clone = args.clone();
|
let args_clone = args.clone();
|
||||||
|
|
||||||
HttpServer::new(move || {
|
HttpServer::new(move || {
|
||||||
|
|
||||||
let mut cors = Cors::default();
|
let mut cors = Cors::default();
|
||||||
match args_clone.cors.as_deref() {
|
match args_clone.cors.as_deref() {
|
||||||
Some("*") => cors = cors.allow_any_origin(),
|
Some("*") => cors = cors.allow_any_origin(),
|
||||||
@ -57,15 +76,13 @@ async fn main() -> std::io::Result<()> {
|
|||||||
|
|
||||||
App::new()
|
App::new()
|
||||||
.wrap(cors)
|
.wrap(cors)
|
||||||
|
|
||||||
.route("/bot/config", web::get().to(bot_configuration))
|
.route("/bot/config", web::get().to(bot_configuration))
|
||||||
|
.route("/bot/play", web::get().to(start_bot_play))
|
||||||
.route("/random/config", web::get().to(multi_players_config))
|
.route("/random/config", web::get().to(multi_players_config))
|
||||||
|
|
||||||
.route("/", web::get().to(index))
|
.route("/", web::get().to(index))
|
||||||
.route("{tail:.*}", web::get().to(not_found))
|
.route("{tail:.*}", web::get().to(not_found))
|
||||||
})
|
})
|
||||||
.bind(args.listen_address)?
|
.bind(args.listen_address)?
|
||||||
.run()
|
.run()
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
34
src/random_bot.rs
Normal file
34
src/random_bot.rs
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
use crate::data::GameRules;
|
||||||
|
use actix::Addr;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use crate::game::{Game, Player};
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct RandomBot {
|
||||||
|
game: Addr<Game>,
|
||||||
|
uuid: Uuid,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RandomBot {
|
||||||
|
pub fn new(game: Addr<Game>) -> Self {
|
||||||
|
Self {
|
||||||
|
game,
|
||||||
|
uuid: Uuid::new_v4(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Player for RandomBot {
|
||||||
|
fn get_name(&self) -> &str {
|
||||||
|
"Random Bot"
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_uid(&self) -> Uuid {
|
||||||
|
self.uuid
|
||||||
|
}
|
||||||
|
|
||||||
|
fn query_boats_layout(&self, rules: &GameRules) {
|
||||||
|
log::info!("Player requested boats configuration!");
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user