Remove complex PlayerWrapper structure

This commit is contained in:
Pierre HUBERT 2022-09-11 16:58:40 +02:00
parent d8bf2165a8
commit 481f36752d
2 changed files with 13 additions and 25 deletions

View File

@ -1,8 +1,6 @@
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;
@ -15,20 +13,6 @@ pub trait Player {
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]
@ -66,15 +50,18 @@ impl Actor for Game {
#[derive(Message)]
#[rtype(result = "()")]
pub struct AddPlayer(pub PlayerWrapper);
pub struct AddPlayer<E>(pub E);
impl Handler<AddPlayer> for Game {
impl<E> Handler<AddPlayer<Arc<E>>> for Game
where
E: Player + 'static,
{
type Result = ();
/// Add a new player to the game
fn handle(&mut self, msg: AddPlayer, _ctx: &mut Self::Context) -> Self::Result {
fn handle(&mut self, msg: AddPlayer<Arc<E>>, _ctx: &mut Self::Context) -> Self::Result {
assert!(self.players.len() < 2);
self.players.push(msg.0.extract());
self.players.push(msg.0);
if self.players.len() == 2 {
self.query_boats_disposition();

View File

@ -7,7 +7,7 @@ use actix_web_actors::ws::{CloseCode, CloseReason, Message, ProtocolError, Webso
use uuid::Uuid;
use crate::data::{BotType, GameRules};
use crate::game::{AddPlayer, Game, PlayerWrapper};
use crate::game::{AddPlayer, Game};
use crate::human_player::HumanPlayer;
use crate::random_bot::RandomBot;
@ -56,10 +56,11 @@ impl Actor for HumanPlayerWS {
StartMode::Bot(rules) => {
let game = Game::new(rules.clone()).start();
let bot = match rules.bot_type {
BotType::Random => PlayerWrapper::RandomBot(RandomBot::new(game.clone())),
match rules.bot_type {
BotType::Random => {
game.do_send(AddPlayer(Arc::new(RandomBot::new(game.clone()))));
}
};
game.do_send(AddPlayer(bot));
let player = Arc::new(HumanPlayer {
name: "Human".to_string(),
@ -68,7 +69,7 @@ impl Actor for HumanPlayerWS {
uuid: Uuid::new_v4(),
});
self.inner = Some(player.clone());
game.do_send(AddPlayer(PlayerWrapper::Human(player)));
game.do_send(AddPlayer(player));
}
StartMode::AgainstHuman => {