Fix a few bugs

This commit is contained in:
Pierre HUBERT 2022-10-16 18:06:31 +02:00
parent 3c2b96f3a2
commit 04ee20dac2
5 changed files with 46 additions and 42 deletions

View File

@ -90,12 +90,12 @@ impl Client {
match Self::recv_next_msg(&mut stream).await {
Ok(msg) => {
if let Err(e) = sender.send(msg.clone()) {
log::error!("Failed to forward ws message! {} (msg={:?})", e, msg);
log::debug!("Failed to forward ws message! {} (msg={:?})", e, msg);
break;
}
}
Err(e) => {
log::error!("Failed receive next message from websocket! {}", e);
log::debug!("Failed receive next message from websocket! {}", e);
break;
}
}

View File

@ -14,7 +14,6 @@ use tui::Terminal;
use cli_player::cli_args::{cli_args, TestDevScreen};
use cli_player::client::Client;
use cli_player::server::start_server_if_missing;
use cli_player::ui_screens::configure_game_rules::GameRulesConfigurationScreen;
use cli_player::ui_screens::game_screen::GameScreen;
use cli_player::ui_screens::input_screen::InputScreen;
@ -22,7 +21,6 @@ use cli_player::ui_screens::popup_screen::PopupScreen;
use cli_player::ui_screens::select_play_mode_screen::{SelectPlayModeResult, SelectPlayModeScreen};
use cli_player::ui_screens::*;
use sea_battle_backend::data::GameRules;
use sea_battle_backend::human_player_ws::ServerMessage;
use sea_battle_backend::utils::Res;
/// Test code screens
@ -103,21 +101,11 @@ async fn run_app<B: Backend>(terminal: &mut Terminal<B>) -> Res {
}
}
match choice {
let client = match choice {
ScreenResult::Ok(SelectPlayModeResult::PlayRandom) => {
PopupScreen::new("Connecting...").show_once(terminal)?;
let client = Client::start_random_play(&username).await?;
PopupScreen::new("Waiting for opponent...").show_once(terminal)?;
// Wait for the server to become ready
while !matches!(
client.recv_next_message().await?,
ServerMessage::OpponentConnected
) {}
// Display game screen
GameScreen::new(client).show(terminal).await?;
Client::start_random_play(&username).await?
}
// Play against bot
@ -130,20 +118,14 @@ async fn run_app<B: Backend>(terminal: &mut Terminal<B>) -> Res {
// Then connect to server
PopupScreen::new("Connecting...").show_once(terminal)?;
let client = Client::start_bot_play(&rules).await?;
// Wait for the server to become ready
while !matches!(
client.recv_next_message().await?,
ServerMessage::OpponentConnected
) {}
// Display game screen
GameScreen::new(client).show(terminal).await?;
Client::start_bot_play(&rules).await?
}
ScreenResult::Canceled | ScreenResult::Ok(SelectPlayModeResult::Exit) => return Ok(()),
}
};
// Display game screen
GameScreen::new(client).show(terminal).await?;
}
}
@ -151,8 +133,6 @@ async fn run_app<B: Backend>(terminal: &mut Terminal<B>) -> Res {
pub async fn main() -> Result<(), Box<dyn Error>> {
env_logger::Builder::from_env(Env::default()).init();
start_server_if_missing().await;
// setup terminal
enable_raw_mode()?;
let mut stdout = io::stdout();

View File

@ -26,5 +26,7 @@ pub async fn start_server_if_missing() {
.expect("Failed to run local server!")
}));
});
network_utils::wait_for_port(cli_args().listen_port()).await;
}
}

View File

@ -26,9 +26,11 @@ use crate::ui_widgets::game_map_widget::{ColoredCells, GameMapWidget};
type CoordinatesMapper = HashMap<Coordinates, Coordinates>;
#[derive(Eq, PartialEq)]
#[derive(Eq, PartialEq, Ord, PartialOrd)]
enum GameStatus {
Pending,
Connecting,
WaitingForAnotherPlayer,
OpponentConnected,
WaitingForOpponentBoatsConfig,
OpponentReady,
Starting,
@ -45,14 +47,14 @@ enum GameStatus {
impl GameStatus {
pub fn can_show_game_maps(&self) -> bool {
self != &GameStatus::Pending
&& self != &GameStatus::WaitingForOpponentBoatsConfig
&& self != &GameStatus::OpponentReady
self > &GameStatus::Starting
}
pub fn status_text(&self) -> &str {
match self {
GameStatus::Pending => "Game is pending...",
GameStatus::Connecting => "Connecting...",
GameStatus::WaitingForAnotherPlayer => "Waiting for another player...",
GameStatus::OpponentConnected => "Opponent connected!",
GameStatus::WaitingForOpponentBoatsConfig => "Waiting for ### boats configuration",
GameStatus::OpponentReady => "### is ready!",
GameStatus::Starting => "Game is starting...",
@ -90,6 +92,7 @@ impl Buttons {
pub struct GameScreen {
client: Client,
invite_code: Option<String>,
status: GameStatus,
opponent_name: Option<String>,
game: CurrentGameStatus,
@ -102,7 +105,8 @@ impl GameScreen {
pub fn new(client: Client) -> Self {
Self {
client,
status: GameStatus::Pending,
invite_code: None,
status: GameStatus::Connecting,
opponent_name: None,
game: Default::default(),
curr_shoot_position: Coordinates::new(0, 0),
@ -214,10 +218,23 @@ impl GameScreen {
// Handle incoming messages
while let Some(msg) = self.client.try_recv_next_message().await? {
match msg {
ServerMessage::SetInviteCode { .. } => unimplemented!(),
ServerMessage::InvalidInviteCode => unimplemented!(),
ServerMessage::WaitingForAnotherPlayer => unimplemented!(),
ServerMessage::OpponentConnected => unimplemented!(),
ServerMessage::SetInviteCode { code } => {
self.status = GameStatus::WaitingForAnotherPlayer;
self.invite_code = Some(code);
}
ServerMessage::InvalidInviteCode => {
PopupScreen::new("Invalid invite code!").show(terminal)?;
return Ok(ScreenResult::Ok(()));
}
ServerMessage::WaitingForAnotherPlayer => {
self.status = GameStatus::WaitingForAnotherPlayer;
}
ServerMessage::OpponentConnected => {
self.status = GameStatus::OpponentConnected;
}
ServerMessage::SetOpponentName { name } => self.opponent_name = Some(name),
@ -427,13 +444,19 @@ impl GameScreen {
}
fn ui<B: Backend>(&mut self, f: &mut Frame<B>) -> CoordinatesMapper {
let status_text = self
let mut status_text = self
.status
.status_text()
.replace("###", self.opponent_name());
// If the game is in a state where game maps can not be shown
if !self.status.can_show_game_maps() {
if self.status == GameStatus::WaitingForAnotherPlayer {
if let Some(code) = &self.invite_code {
status_text.push_str(&format!("\n Invite code: {}", code));
}
}
PopupScreen::new(&status_text).show_in_frame(f);
return HashMap::default();
}

View File

@ -89,7 +89,6 @@ impl Handler<CreateInvite> for DispatcherActor {
msg.1.do_send(ServerMessage::SetInviteCode {
code: invite_code.clone(),
});
msg.1.do_send(ServerMessage::WaitingForAnotherPlayer);
self.with_invite.insert(
invite_code,
PendingPlayer {