Compare commits
31 Commits
b1145cc362
...
0.2.0
Author | SHA1 | Date | |
---|---|---|---|
e88d64ff63 | |||
3ca6c43c9a | |||
d4223be8b4 | |||
83d0780954 | |||
6be3eae863 | |||
c763a24ca9 | |||
10c099e03b | |||
eea2ecbf63 | |||
915426849b | |||
be454cce03 | |||
a91a4c5ef6 | |||
02477e6728 | |||
e389b59ab9 | |||
dfaa5ce30b | |||
cf1d77f445 | |||
0280daf6d2 | |||
38656661b4 | |||
5b228de285 | |||
d8f96f732a | |||
e760bcbe33 | |||
ccb3d36fae | |||
fcc7f30e10 | |||
171c88f303 | |||
9162c5eb24 | |||
b4772aa88e | |||
42b0d84f9d | |||
ba1ed84b33 | |||
8c1a3f2c5f | |||
25871de084 | |||
9a38a634eb | |||
8990badaa4 |
14
README.md
14
README.md
@@ -1,5 +1,17 @@
|
|||||||
# SeaBattle
|
# SeaBattle
|
||||||
|
[](https://drone.communiquons.org/pierre/SeaBattle)
|
||||||
|
|
||||||
|
|
||||||
Full stack sea battle game.
|
Full stack sea battle game.
|
||||||
|
|
||||||
Current status: working on backend, and then building web ui...
|
|
||||||
|
## Implementations
|
||||||
|
Current implementations:
|
||||||
|
- [x] Rust shell implementations ([server](rust/sea_battle_backend) and [client](rust/sea_battle_cli_player))
|
||||||
|
- [ ] web implementation
|
||||||
|
- [ ] mobile implementation
|
||||||
|
|
||||||
|
## Screenshots
|
||||||
|
|
||||||
|
### Shell implementation
|
||||||
|

|
||||||
|
134
rust/Cargo.lock
generated
134
rust/Cargo.lock
generated
@@ -421,9 +421,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "clap"
|
name = "clap"
|
||||||
version = "4.0.15"
|
version = "4.0.16"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "6bf8832993da70a4c6d13c581f4463c2bdda27b9bf1c5498dc4365543abe6d6f"
|
checksum = "2ef582e2c00a63a0c0aa1fb4a4870781c4f5729f51196d3537fa7c1c1992eaa3"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"atty",
|
"atty",
|
||||||
"bitflags",
|
"bitflags",
|
||||||
@@ -456,31 +456,6 @@ dependencies = [
|
|||||||
"os_str_bytes",
|
"os_str_bytes",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "cli_player"
|
|
||||||
version = "0.1.0"
|
|
||||||
dependencies = [
|
|
||||||
"clap",
|
|
||||||
"crossterm",
|
|
||||||
"env_logger",
|
|
||||||
"futures",
|
|
||||||
"hostname",
|
|
||||||
"hyper-rustls",
|
|
||||||
"lazy_static",
|
|
||||||
"log",
|
|
||||||
"num",
|
|
||||||
"num-derive",
|
|
||||||
"num-traits",
|
|
||||||
"rustls",
|
|
||||||
"sea_battle_backend",
|
|
||||||
"serde_json",
|
|
||||||
"serde_urlencoded",
|
|
||||||
"textwrap",
|
|
||||||
"tokio",
|
|
||||||
"tokio-tungstenite",
|
|
||||||
"tui",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "codespan-reporting"
|
name = "codespan-reporting"
|
||||||
version = "0.11.1"
|
version = "0.11.1"
|
||||||
@@ -965,6 +940,7 @@ dependencies = [
|
|||||||
"futures-channel",
|
"futures-channel",
|
||||||
"futures-core",
|
"futures-core",
|
||||||
"futures-util",
|
"futures-util",
|
||||||
|
"h2",
|
||||||
"http",
|
"http",
|
||||||
"http-body",
|
"http-body",
|
||||||
"httparse",
|
"httparse",
|
||||||
@@ -1044,6 +1020,12 @@ dependencies = [
|
|||||||
"serde",
|
"serde",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "ipnet"
|
||||||
|
version = "2.5.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "879d54834c8c76457ef4293a689b2a8c59b076067ad77b15efafbb05f92a592b"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "itoa"
|
name = "itoa"
|
||||||
version = "1.0.4"
|
version = "1.0.4"
|
||||||
@@ -1446,6 +1428,45 @@ version = "0.6.27"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "a3f87b73ce11b1619a3c6332f45341e0047173771e8b8b73f87bfeefb7b56244"
|
checksum = "a3f87b73ce11b1619a3c6332f45341e0047173771e8b8b73f87bfeefb7b56244"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "reqwest"
|
||||||
|
version = "0.11.12"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "431949c384f4e2ae07605ccaa56d1d9d2ecdb5cadd4f9577ccfab29f2e5149fc"
|
||||||
|
dependencies = [
|
||||||
|
"base64",
|
||||||
|
"bytes",
|
||||||
|
"encoding_rs",
|
||||||
|
"futures-core",
|
||||||
|
"futures-util",
|
||||||
|
"h2",
|
||||||
|
"http",
|
||||||
|
"http-body",
|
||||||
|
"hyper",
|
||||||
|
"hyper-rustls",
|
||||||
|
"ipnet",
|
||||||
|
"js-sys",
|
||||||
|
"log",
|
||||||
|
"mime",
|
||||||
|
"once_cell",
|
||||||
|
"percent-encoding",
|
||||||
|
"pin-project-lite",
|
||||||
|
"rustls",
|
||||||
|
"rustls-pemfile",
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
|
"serde_urlencoded",
|
||||||
|
"tokio",
|
||||||
|
"tokio-rustls",
|
||||||
|
"tower-service",
|
||||||
|
"url",
|
||||||
|
"wasm-bindgen",
|
||||||
|
"wasm-bindgen-futures",
|
||||||
|
"web-sys",
|
||||||
|
"webpki-roots",
|
||||||
|
"winreg",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ring"
|
name = "ring"
|
||||||
version = "0.16.20"
|
version = "0.16.20"
|
||||||
@@ -1543,7 +1564,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "sea_battle_backend"
|
name = "sea_battle_backend"
|
||||||
version = "0.1.0"
|
version = "0.2.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"actix",
|
"actix",
|
||||||
"actix-cors",
|
"actix-cors",
|
||||||
@@ -1555,6 +1576,7 @@ dependencies = [
|
|||||||
"futures",
|
"futures",
|
||||||
"log",
|
"log",
|
||||||
"rand",
|
"rand",
|
||||||
|
"semver",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"serde_urlencoded",
|
"serde_urlencoded",
|
||||||
@@ -1564,6 +1586,32 @@ dependencies = [
|
|||||||
"uuid",
|
"uuid",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "sea_battle_cli_player"
|
||||||
|
version = "0.2.0"
|
||||||
|
dependencies = [
|
||||||
|
"clap",
|
||||||
|
"crossterm",
|
||||||
|
"env_logger",
|
||||||
|
"futures",
|
||||||
|
"hostname",
|
||||||
|
"hyper-rustls",
|
||||||
|
"lazy_static",
|
||||||
|
"log",
|
||||||
|
"num",
|
||||||
|
"num-derive",
|
||||||
|
"num-traits",
|
||||||
|
"reqwest",
|
||||||
|
"rustls",
|
||||||
|
"sea_battle_backend",
|
||||||
|
"serde_json",
|
||||||
|
"serde_urlencoded",
|
||||||
|
"textwrap",
|
||||||
|
"tokio",
|
||||||
|
"tokio-tungstenite",
|
||||||
|
"tui",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "security-framework"
|
name = "security-framework"
|
||||||
version = "2.7.0"
|
version = "2.7.0"
|
||||||
@@ -2111,6 +2159,18 @@ dependencies = [
|
|||||||
"wasm-bindgen-shared",
|
"wasm-bindgen-shared",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "wasm-bindgen-futures"
|
||||||
|
version = "0.4.33"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "23639446165ca5a5de86ae1d8896b737ae80319560fbaa4c2887b7da6e7ebd7d"
|
||||||
|
dependencies = [
|
||||||
|
"cfg-if",
|
||||||
|
"js-sys",
|
||||||
|
"wasm-bindgen",
|
||||||
|
"web-sys",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "wasm-bindgen-macro"
|
name = "wasm-bindgen-macro"
|
||||||
version = "0.2.83"
|
version = "0.2.83"
|
||||||
@@ -2160,6 +2220,15 @@ dependencies = [
|
|||||||
"untrusted",
|
"untrusted",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "webpki-roots"
|
||||||
|
version = "0.22.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "368bfe657969fb01238bb756d351dcade285e0f6fcbd36dcb23359a5169975be"
|
||||||
|
dependencies = [
|
||||||
|
"webpki",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "winapi"
|
name = "winapi"
|
||||||
version = "0.3.9"
|
version = "0.3.9"
|
||||||
@@ -2234,6 +2303,15 @@ version = "0.36.1"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "c811ca4a8c853ef420abd8592ba53ddbbac90410fab6903b3e79972a631f7680"
|
checksum = "c811ca4a8c853ef420abd8592ba53ddbbac90410fab6903b3e79972a631f7680"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "winreg"
|
||||||
|
version = "0.10.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d"
|
||||||
|
dependencies = [
|
||||||
|
"winapi",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "zstd"
|
name = "zstd"
|
||||||
version = "0.11.2+zstd.1.5.2"
|
version = "0.11.2+zstd.1.5.2"
|
||||||
|
@@ -2,5 +2,5 @@
|
|||||||
|
|
||||||
members = [
|
members = [
|
||||||
"sea_battle_backend",
|
"sea_battle_backend",
|
||||||
"cli_player"
|
"sea_battle_cli_player"
|
||||||
]
|
]
|
||||||
|
@@ -1,167 +0,0 @@
|
|||||||
use std::error::Error;
|
|
||||||
use std::io;
|
|
||||||
use std::io::ErrorKind;
|
|
||||||
|
|
||||||
use crossterm::event::DisableMouseCapture;
|
|
||||||
use crossterm::event::EnableMouseCapture;
|
|
||||||
use crossterm::execute;
|
|
||||||
use crossterm::terminal::EnterAlternateScreen;
|
|
||||||
use crossterm::terminal::LeaveAlternateScreen;
|
|
||||||
use crossterm::terminal::{disable_raw_mode, enable_raw_mode};
|
|
||||||
use env_logger::Env;
|
|
||||||
use tui::backend::{Backend, CrosstermBackend};
|
|
||||||
use tui::Terminal;
|
|
||||||
|
|
||||||
use cli_player::cli_args::{cli_args, TestDevScreen};
|
|
||||||
use cli_player::client::Client;
|
|
||||||
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;
|
|
||||||
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::consts::{MAX_PLAYER_NAME_LENGTH, MIN_PLAYER_NAME_LENGTH};
|
|
||||||
use sea_battle_backend::data::GameRules;
|
|
||||||
use sea_battle_backend::utils::Res;
|
|
||||||
|
|
||||||
/// Test code screens
|
|
||||||
async fn run_dev<B: Backend>(
|
|
||||||
terminal: &mut Terminal<B>,
|
|
||||||
d: TestDevScreen,
|
|
||||||
) -> Result<(), Box<dyn Error>> {
|
|
||||||
let res = match d {
|
|
||||||
TestDevScreen::Popup => popup_screen::PopupScreen::new("Welcome there!!")
|
|
||||||
.show(terminal)?
|
|
||||||
.as_string(),
|
|
||||||
TestDevScreen::Input => input_screen::InputScreen::new("What it your name ?")
|
|
||||||
.set_title("A custom title")
|
|
||||||
.show(terminal)?
|
|
||||||
.as_string(),
|
|
||||||
TestDevScreen::Confirm => {
|
|
||||||
confirm_dialog_screen::ConfirmDialogScreen::new("Do you really want to quit game?")
|
|
||||||
.show(terminal)?
|
|
||||||
.as_string()
|
|
||||||
}
|
|
||||||
TestDevScreen::SelectBotType => select_bot_type_screen::SelectBotTypeScreen::default()
|
|
||||||
.show(terminal)?
|
|
||||||
.as_string(),
|
|
||||||
TestDevScreen::SelectPlayMode => select_play_mode_screen::SelectPlayModeScreen::default()
|
|
||||||
.show(terminal)?
|
|
||||||
.as_string(),
|
|
||||||
TestDevScreen::SetBoatsLayout => {
|
|
||||||
let rules = GameRules {
|
|
||||||
boats_can_touch: true,
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
|
|
||||||
set_boats_layout_screen::SetBoatsLayoutScreen::new(&rules)
|
|
||||||
.show(terminal)?
|
|
||||||
.as_string()
|
|
||||||
}
|
|
||||||
TestDevScreen::ConfigureGameRules => {
|
|
||||||
configure_game_rules::GameRulesConfigurationScreen::new(GameRules::default())
|
|
||||||
.show(terminal)?
|
|
||||||
.as_string()
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
Err(io::Error::new(
|
|
||||||
ErrorKind::Other,
|
|
||||||
format!("DEV result: {:?}", res),
|
|
||||||
))?
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Ask the user to specify its username
|
|
||||||
fn query_username<B: Backend>(terminal: &mut Terminal<B>) -> Res<String> {
|
|
||||||
let mut hostname = hostname::get()?.to_string_lossy().to_string();
|
|
||||||
if hostname.len() > MAX_PLAYER_NAME_LENGTH {
|
|
||||||
hostname = hostname[0..MAX_PLAYER_NAME_LENGTH].to_string();
|
|
||||||
}
|
|
||||||
|
|
||||||
let res =
|
|
||||||
InputScreen::new("Please specify the name to which other players should identify you:")
|
|
||||||
.set_title("Player name")
|
|
||||||
.set_value(&hostname)
|
|
||||||
.set_min_length(MIN_PLAYER_NAME_LENGTH)
|
|
||||||
.set_max_length(MAX_PLAYER_NAME_LENGTH)
|
|
||||||
.show(terminal)?;
|
|
||||||
|
|
||||||
Ok(res.value().unwrap_or(hostname))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn run_app<B: Backend>(terminal: &mut Terminal<B>) -> Res {
|
|
||||||
if let Some(d) = cli_args().dev_screen {
|
|
||||||
return run_dev(terminal, d).await;
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut rules = GameRules::default();
|
|
||||||
|
|
||||||
let mut username = "".to_string();
|
|
||||||
|
|
||||||
loop {
|
|
||||||
let choice = SelectPlayModeScreen::default().show(terminal)?;
|
|
||||||
|
|
||||||
if let ScreenResult::Ok(c) = choice {
|
|
||||||
if c.need_user_name() && username.is_empty() {
|
|
||||||
username = query_username(terminal)?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let client = match choice {
|
|
||||||
ScreenResult::Ok(SelectPlayModeResult::PlayRandom) => {
|
|
||||||
PopupScreen::new("Connecting...").show_once(terminal)?;
|
|
||||||
|
|
||||||
Client::start_random_play(&username).await?
|
|
||||||
}
|
|
||||||
|
|
||||||
// Play against bot
|
|
||||||
ScreenResult::Ok(SelectPlayModeResult::PlayAgainstBot) => {
|
|
||||||
// First, ask for custom rules
|
|
||||||
rules = match GameRulesConfigurationScreen::new(rules.clone()).show(terminal)? {
|
|
||||||
ScreenResult::Ok(r) => r,
|
|
||||||
ScreenResult::Canceled => continue,
|
|
||||||
};
|
|
||||||
|
|
||||||
// Then connect to server
|
|
||||||
PopupScreen::new("Connecting...").show_once(terminal)?;
|
|
||||||
Client::start_bot_play(&rules).await?
|
|
||||||
}
|
|
||||||
|
|
||||||
ScreenResult::Canceled | ScreenResult::Ok(SelectPlayModeResult::Exit) => return Ok(()),
|
|
||||||
};
|
|
||||||
|
|
||||||
// Display game screen
|
|
||||||
GameScreen::new(client).show(terminal).await?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::main]
|
|
||||||
pub async fn main() -> Result<(), Box<dyn Error>> {
|
|
||||||
env_logger::Builder::from_env(Env::default()).init();
|
|
||||||
cli_args(); // Avoid a crash if help argument is triggered
|
|
||||||
|
|
||||||
// setup terminal
|
|
||||||
enable_raw_mode()?;
|
|
||||||
let mut stdout = io::stdout();
|
|
||||||
execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
|
|
||||||
let backend = CrosstermBackend::new(stdout);
|
|
||||||
let mut terminal = Terminal::new(backend)?;
|
|
||||||
|
|
||||||
// create app and run it
|
|
||||||
let res = run_app(&mut terminal).await;
|
|
||||||
|
|
||||||
// restore terminal
|
|
||||||
disable_raw_mode()?;
|
|
||||||
execute!(
|
|
||||||
terminal.backend_mut(),
|
|
||||||
LeaveAlternateScreen,
|
|
||||||
DisableMouseCapture
|
|
||||||
)?;
|
|
||||||
terminal.show_cursor()?;
|
|
||||||
|
|
||||||
if let Err(err) = res {
|
|
||||||
println!("{:?}", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
@@ -1,12 +1,18 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "sea_battle_backend"
|
name = "sea_battle_backend"
|
||||||
version = "0.1.0"
|
version = "0.2.0"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
license = "GPL-2.0-or-later"
|
||||||
|
description = "A Sea Battle game backend server"
|
||||||
|
repository = "https://gitea.communiquons.org/pierre/SeaBattle"
|
||||||
|
readme = "README.md"
|
||||||
|
authors = ["Pierre Hubert <pierre.git@communiquons.org>"]
|
||||||
|
categories = [ "games" ]
|
||||||
|
|
||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
clap = { version = "4.0.15", features = ["derive"] }
|
clap = { version = "4.0.16", features = ["derive"] }
|
||||||
log = "0.4.17"
|
log = "0.4.17"
|
||||||
env_logger = "0.9.0"
|
env_logger = "0.9.0"
|
||||||
serde = { version = "1.0.145", features = ["derive"] }
|
serde = { version = "1.0.145", features = ["derive"] }
|
||||||
@@ -20,6 +26,7 @@ uuid = { version = "1.1.2", features = ["v4"] }
|
|||||||
rand = "0.8.5"
|
rand = "0.8.5"
|
||||||
serde_with = "2.0.1"
|
serde_with = "2.0.1"
|
||||||
tokio = { version = "1", features = ["full"] }
|
tokio = { version = "1", features = ["full"] }
|
||||||
|
semver = "1.0.14"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
#reqwest = { version = "0.11.11", default-features = false, features = ["json", "rustls-tls"] }
|
#reqwest = { version = "0.11.11", default-features = false, features = ["json", "rustls-tls"] }
|
||||||
|
30
rust/sea_battle_backend/README.md
Normal file
30
rust/sea_battle_backend/README.md
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
# Sea battle backend
|
||||||
|
[](https://drone.communiquons.org/pierre/SeaBattle)
|
||||||
|
[](https://crates.io/crates/sea_battle_backend)
|
||||||
|
[](https://docs.rs/sea_battle_backend/)
|
||||||
|
|
||||||
|
A backend HTTP server for the Sea Battle game. The binary included in
|
||||||
|
this crate can be used to deploy a server that will allow players to
|
||||||
|
connect to play together.
|
||||||
|
|
||||||
|
The `actix-web` library is used to spawn HTTP server. The games are encapsulated
|
||||||
|
inside websockets.
|
||||||
|
|
||||||
|
An official server is running at https://seabattleapi.communiquons.org/
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
You can install the backend using the following command:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cargo install sea_battle_backend
|
||||||
|
```
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
```bash
|
||||||
|
sea_battle_backend -l 0.0.0.0:7000
|
||||||
|
```
|
||||||
|
|
||||||
|
> Note: a reverse-proxy must be used to protect
|
||||||
|
|
||||||
|
## Client
|
||||||
|
A command-line client is available in the [sea_battle_cli_player](https://crates.io/crates/sea_battle_cli_player) crate.
|
@@ -12,3 +12,14 @@ pub struct Args {
|
|||||||
#[clap(short, long, value_parser)]
|
#[clap(short, long, value_parser)]
|
||||||
pub cors: Option<String>,
|
pub cors: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod test {
|
||||||
|
use crate::args::Args;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn verify_cli() {
|
||||||
|
use clap::CommandFactory;
|
||||||
|
Args::command().debug_assert()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@@ -1,5 +1,8 @@
|
|||||||
//! # Project constants
|
//! # Project constants
|
||||||
|
|
||||||
|
pub const MIN_REQUIRED_VERSION: &str = "0.1.0";
|
||||||
|
pub const CURRENT_VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||||
|
|
||||||
pub const MIN_BOATS_NUMBER: usize = 1;
|
pub const MIN_BOATS_NUMBER: usize = 1;
|
||||||
pub const MAX_BOATS_NUMBER: usize = 10;
|
pub const MAX_BOATS_NUMBER: usize = 10;
|
||||||
|
|
||||||
@@ -24,3 +27,6 @@ pub const INVITE_CODE_LENGTH: usize = 5;
|
|||||||
|
|
||||||
pub const MIN_PLAYER_NAME_LENGTH: usize = 1;
|
pub const MIN_PLAYER_NAME_LENGTH: usize = 1;
|
||||||
pub const MAX_PLAYER_NAME_LENGTH: usize = 10;
|
pub const MAX_PLAYER_NAME_LENGTH: usize = 10;
|
||||||
|
|
||||||
|
pub const MIN_STRIKE_TIMEOUT: u64 = 5;
|
||||||
|
pub const MAX_STRIKE_TIMEOUT: u64 = 90;
|
||||||
|
@@ -361,7 +361,7 @@ impl BoatsLayout {
|
|||||||
mod test {
|
mod test {
|
||||||
use crate::data::boats_layout::{BoatDirection, BoatPosition, BoatsLayout, Coordinates};
|
use crate::data::boats_layout::{BoatDirection, BoatPosition, BoatsLayout, Coordinates};
|
||||||
use crate::data::game_map::GameMap;
|
use crate::data::game_map::GameMap;
|
||||||
use crate::data::{BotType, GameRules, PlayConfiguration, PrintableMap};
|
use crate::data::*;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn dist_coordinates_eq() {
|
fn dist_coordinates_eq() {
|
||||||
@@ -488,8 +488,7 @@ mod test {
|
|||||||
map_height: 5,
|
map_height: 5,
|
||||||
boats_str: "1,1".to_string(),
|
boats_str: "1,1".to_string(),
|
||||||
boats_can_touch: false,
|
boats_can_touch: false,
|
||||||
player_continue_on_hit: false,
|
..Default::default()
|
||||||
bot_type: BotType::Random,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut boats = BoatsLayout(vec![
|
let mut boats = BoatsLayout(vec![
|
||||||
|
@@ -78,6 +78,7 @@ impl PrintableMap for PrintableCurrentGameMapStatus {
|
|||||||
|
|
||||||
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, Default)]
|
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, Default)]
|
||||||
pub struct CurrentGameStatus {
|
pub struct CurrentGameStatus {
|
||||||
|
pub remaining_time_for_strike: Option<u64>,
|
||||||
pub rules: GameRules,
|
pub rules: GameRules,
|
||||||
pub your_map: CurrentGameMapStatus,
|
pub your_map: CurrentGameMapStatus,
|
||||||
pub opponent_map: CurrentGameMapStatus,
|
pub opponent_map: CurrentGameMapStatus,
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
use crate::consts::*;
|
use crate::consts::*;
|
||||||
use crate::data::{BotType, PlayConfiguration};
|
use crate::data::{BotType, PlayConfiguration};
|
||||||
use serde_with::{serde_as, DisplayFromStr};
|
use serde_with::{serde_as, DisplayFromStr, NoneAsEmptyString};
|
||||||
|
|
||||||
#[serde_as]
|
#[serde_as]
|
||||||
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq)]
|
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq)]
|
||||||
@@ -15,6 +15,8 @@ pub struct GameRules {
|
|||||||
pub boats_can_touch: bool,
|
pub boats_can_touch: bool,
|
||||||
#[serde_as(as = "DisplayFromStr")]
|
#[serde_as(as = "DisplayFromStr")]
|
||||||
pub player_continue_on_hit: bool,
|
pub player_continue_on_hit: bool,
|
||||||
|
#[serde_as(as = "NoneAsEmptyString")]
|
||||||
|
pub strike_timeout: Option<u64>,
|
||||||
pub bot_type: BotType,
|
pub bot_type: BotType,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -36,6 +38,7 @@ impl GameRules {
|
|||||||
.join(","),
|
.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,
|
||||||
|
strike_timeout: Some(30),
|
||||||
bot_type: BotType::Smart,
|
bot_type: BotType::Smart,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -50,6 +53,11 @@ impl GameRules {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn with_strike_timeout(mut self, timeout: u64) -> Self {
|
||||||
|
self.strike_timeout = Some(timeout);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
/// Set the list of boats for this configuration
|
/// Set the list of boats for this configuration
|
||||||
pub fn set_boats_list(&mut self, boats: &[usize]) {
|
pub fn set_boats_list(&mut self, boats: &[usize]) {
|
||||||
self.boats_str = boats
|
self.boats_str = boats
|
||||||
@@ -121,6 +129,16 @@ impl GameRules {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if let Some(timeout) = self.strike_timeout {
|
||||||
|
if timeout < config.min_strike_timeout {
|
||||||
|
errors.push("Strike timeout is too short!");
|
||||||
|
}
|
||||||
|
|
||||||
|
if timeout > config.max_strike_timeout {
|
||||||
|
errors.push("Strike timeout is too long!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
errors
|
errors
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -4,6 +4,7 @@ pub use game_map::*;
|
|||||||
pub use game_rules::*;
|
pub use game_rules::*;
|
||||||
pub use play_config::*;
|
pub use play_config::*;
|
||||||
pub use printable_map::*;
|
pub use printable_map::*;
|
||||||
|
pub use version::*;
|
||||||
|
|
||||||
mod boats_layout;
|
mod boats_layout;
|
||||||
mod current_game_status;
|
mod current_game_status;
|
||||||
@@ -11,3 +12,4 @@ mod game_map;
|
|||||||
mod game_rules;
|
mod game_rules;
|
||||||
mod play_config;
|
mod play_config;
|
||||||
mod printable_map;
|
mod printable_map;
|
||||||
|
mod version;
|
||||||
|
@@ -59,6 +59,8 @@ pub struct PlayConfiguration {
|
|||||||
pub ordinate_alphabet: &'static str,
|
pub ordinate_alphabet: &'static str,
|
||||||
pub min_player_name_len: usize,
|
pub min_player_name_len: usize,
|
||||||
pub max_player_name_len: usize,
|
pub max_player_name_len: usize,
|
||||||
|
pub min_strike_timeout: u64,
|
||||||
|
pub max_strike_timeout: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for PlayConfiguration {
|
impl Default for PlayConfiguration {
|
||||||
@@ -76,6 +78,8 @@ impl Default for PlayConfiguration {
|
|||||||
ordinate_alphabet: ALPHABET,
|
ordinate_alphabet: ALPHABET,
|
||||||
min_player_name_len: MIN_PLAYER_NAME_LENGTH,
|
min_player_name_len: MIN_PLAYER_NAME_LENGTH,
|
||||||
max_player_name_len: MAX_PLAYER_NAME_LENGTH,
|
max_player_name_len: MAX_PLAYER_NAME_LENGTH,
|
||||||
|
min_strike_timeout: MIN_STRIKE_TIMEOUT,
|
||||||
|
max_strike_timeout: MAX_STRIKE_TIMEOUT,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
32
rust/sea_battle_backend/src/data/version.rs
Normal file
32
rust/sea_battle_backend/src/data/version.rs
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
//! # Version Info
|
||||||
|
//!
|
||||||
|
//! Contains server version requirements information
|
||||||
|
|
||||||
|
use crate::consts;
|
||||||
|
use crate::utils::res_utils::Res;
|
||||||
|
use semver::Version;
|
||||||
|
|
||||||
|
#[derive(serde::Serialize, serde::Deserialize)]
|
||||||
|
pub struct VersionInfo {
|
||||||
|
current: String,
|
||||||
|
min_required: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VersionInfo {
|
||||||
|
pub fn load_static() -> Self {
|
||||||
|
Self {
|
||||||
|
current: consts::CURRENT_VERSION.to_string(),
|
||||||
|
min_required: consts::MIN_REQUIRED_VERSION.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check if builtin version is compatible with a remote version or not
|
||||||
|
pub fn is_compatible_with_static_version(&self) -> Res<bool> {
|
||||||
|
let static_version = Self::load_static();
|
||||||
|
|
||||||
|
let local_current = Version::parse(&static_version.current)?;
|
||||||
|
let min_required = Version::parse(&self.min_required)?;
|
||||||
|
|
||||||
|
Ok(min_required <= local_current)
|
||||||
|
}
|
||||||
|
}
|
@@ -1,4 +1,5 @@
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
use actix::prelude::*;
|
use actix::prelude::*;
|
||||||
use actix::{Actor, Context, Handler};
|
use actix::{Actor, Context, Handler};
|
||||||
@@ -6,6 +7,7 @@ use uuid::Uuid;
|
|||||||
|
|
||||||
use crate::bot_player::BotPlayer;
|
use crate::bot_player::BotPlayer;
|
||||||
use crate::data::*;
|
use crate::data::*;
|
||||||
|
use crate::utils::time_utils::time;
|
||||||
|
|
||||||
pub trait Player {
|
pub trait Player {
|
||||||
fn get_name(&self) -> &str;
|
fn get_name(&self) -> &str;
|
||||||
@@ -51,6 +53,9 @@ pub trait Player {
|
|||||||
fn opponent_replaced_by_bot(&self);
|
fn opponent_replaced_by_bot(&self);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// How often strike timeout controller is run
|
||||||
|
const STRIKE_TIMEOUT_CONTROL: Duration = Duration::from_secs(1);
|
||||||
|
|
||||||
fn opponent(index: usize) -> usize {
|
fn opponent(index: usize) -> usize {
|
||||||
match index {
|
match index {
|
||||||
0 => 1,
|
0 => 1,
|
||||||
@@ -85,6 +90,7 @@ pub struct Game {
|
|||||||
map_0: Option<GameMap>,
|
map_0: Option<GameMap>,
|
||||||
map_1: Option<GameMap>,
|
map_1: Option<GameMap>,
|
||||||
turn: usize,
|
turn: usize,
|
||||||
|
curr_strike_request_started: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Game {
|
impl Game {
|
||||||
@@ -96,6 +102,7 @@ impl Game {
|
|||||||
map_0: None,
|
map_0: None,
|
||||||
map_1: None,
|
map_1: None,
|
||||||
turn: 0,
|
turn: 0,
|
||||||
|
curr_strike_request_started: 0,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -130,10 +137,14 @@ impl Game {
|
|||||||
self.turn
|
self.turn
|
||||||
);
|
);
|
||||||
|
|
||||||
self.request_fire();
|
self.request_fire(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn request_fire(&self) {
|
fn request_fire(&mut self, reset_counter: bool) {
|
||||||
|
if reset_counter {
|
||||||
|
self.curr_strike_request_started = time();
|
||||||
|
}
|
||||||
|
|
||||||
self.players[self.turn].request_fire(self.get_game_status_for_player(self.turn));
|
self.players[self.turn].request_fire(self.get_game_status_for_player(self.turn));
|
||||||
self.players[opponent(self.turn)]
|
self.players[opponent(self.turn)]
|
||||||
.opponent_must_fire(self.get_game_status_for_player(opponent(self.turn)));
|
.opponent_must_fire(self.get_game_status_for_player(opponent(self.turn)));
|
||||||
@@ -148,6 +159,27 @@ impl Game {
|
|||||||
.unwrap()
|
.unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Replace user for a fire in case of timeout
|
||||||
|
fn force_fire_in_case_of_timeout(&mut self) {
|
||||||
|
if self.status != GameStatus::Started || self.rules.strike_timeout.is_none() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let timeout = self.rules.strike_timeout.unwrap_or_default();
|
||||||
|
|
||||||
|
if time() <= self.curr_strike_request_started + timeout {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Determine target of fire
|
||||||
|
let target = self
|
||||||
|
.get_game_status_for_player(self.turn)
|
||||||
|
.find_fire_coordinates_for_bot_type(self.rules.bot_type);
|
||||||
|
|
||||||
|
// Fire as player
|
||||||
|
self.handle_fire(target);
|
||||||
|
}
|
||||||
|
|
||||||
fn player_map_mut(&mut self, id: usize) -> &mut GameMap {
|
fn player_map_mut(&mut self, id: usize) -> &mut GameMap {
|
||||||
match id {
|
match id {
|
||||||
0 => self.map_0.as_mut(),
|
0 => self.map_0.as_mut(),
|
||||||
@@ -166,7 +198,7 @@ impl Game {
|
|||||||
// Easiest case : player missed his fire
|
// Easiest case : player missed his fire
|
||||||
if result == FireResult::Missed {
|
if result == FireResult::Missed {
|
||||||
self.turn = opponent(self.turn);
|
self.turn = opponent(self.turn);
|
||||||
self.request_fire();
|
self.request_fire(true);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -188,7 +220,9 @@ impl Game {
|
|||||||
self.turn = opponent(self.turn);
|
self.turn = opponent(self.turn);
|
||||||
}
|
}
|
||||||
|
|
||||||
self.request_fire();
|
self.request_fire(
|
||||||
|
result != FireResult::AlreadyTargetedPosition && result != FireResult::Rejected,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn handle_request_rematch(&mut self, player_id: Uuid) {
|
fn handle_request_rematch(&mut self, player_id: Uuid) {
|
||||||
@@ -223,6 +257,9 @@ impl Game {
|
|||||||
/// Get current game status for a specific player
|
/// Get current game status for a specific player
|
||||||
fn get_game_status_for_player(&self, id: usize) -> CurrentGameStatus {
|
fn get_game_status_for_player(&self, id: usize) -> CurrentGameStatus {
|
||||||
CurrentGameStatus {
|
CurrentGameStatus {
|
||||||
|
remaining_time_for_strike: self.rules.strike_timeout.map(|v| {
|
||||||
|
((self.curr_strike_request_started + v) as i64 - time() as i64).max(0) as u64
|
||||||
|
}),
|
||||||
rules: self.rules.clone(),
|
rules: self.rules.clone(),
|
||||||
your_map: self.player_map(id).current_map_status(false),
|
your_map: self.player_map(id).current_map_status(false),
|
||||||
opponent_map: self
|
opponent_map: self
|
||||||
@@ -234,6 +271,14 @@ impl Game {
|
|||||||
|
|
||||||
impl Actor for Game {
|
impl Actor for Game {
|
||||||
type Context = Context<Self>;
|
type Context = Context<Self>;
|
||||||
|
|
||||||
|
fn started(&mut self, ctx: &mut Self::Context) {
|
||||||
|
if self.rules.strike_timeout.is_some() {
|
||||||
|
ctx.run_interval(STRIKE_TIMEOUT_CONTROL, |act, _ctx| {
|
||||||
|
act.force_fire_in_case_of_timeout();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Message)]
|
#[derive(Message)]
|
||||||
@@ -387,7 +432,7 @@ impl Handler<PlayerLeftGame> for Game {
|
|||||||
|
|
||||||
// Re-do current action
|
// Re-do current action
|
||||||
if self.status == GameStatus::Started {
|
if self.status == GameStatus::Started {
|
||||||
self.request_fire();
|
self.request_fire(true);
|
||||||
} else if self.status == GameStatus::WaitingForBoatsDisposition {
|
} else if self.status == GameStatus::WaitingForBoatsDisposition {
|
||||||
self.players[offline_player].query_boats_layout(&self.rules);
|
self.players[offline_player].query_boats_layout(&self.rules);
|
||||||
}
|
}
|
||||||
|
@@ -152,6 +152,7 @@ impl Actor for HumanPlayerWS {
|
|||||||
fn started(&mut self, ctx: &mut Self::Context) {
|
fn started(&mut self, ctx: &mut Self::Context) {
|
||||||
// Check player name length
|
// Check player name length
|
||||||
if self.name.len() < MIN_PLAYER_NAME_LENGTH || self.name.len() > MAX_PLAYER_NAME_LENGTH {
|
if self.name.len() < MIN_PLAYER_NAME_LENGTH || self.name.len() > MAX_PLAYER_NAME_LENGTH {
|
||||||
|
log::error!("Close connection due to invalid user name!");
|
||||||
ctx.stop();
|
ctx.stop();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
@@ -4,7 +4,7 @@ use actix_web::{web, App, HttpRequest, HttpResponse, HttpServer, Responder};
|
|||||||
use actix_web_actors::ws;
|
use actix_web_actors::ws;
|
||||||
|
|
||||||
use crate::args::Args;
|
use crate::args::Args;
|
||||||
use crate::data::{GameRules, PlayConfiguration};
|
use crate::data::{BoatsLayout, GameRules, PlayConfiguration, VersionInfo};
|
||||||
use crate::dispatcher_actor::DispatcherActor;
|
use crate::dispatcher_actor::DispatcherActor;
|
||||||
use crate::human_player_ws::{HumanPlayerWS, StartMode};
|
use crate::human_player_ws::{HumanPlayerWS, StartMode};
|
||||||
|
|
||||||
@@ -18,11 +18,45 @@ async fn not_found() -> impl Responder {
|
|||||||
HttpResponse::NotFound().json("You missed your strike lol")
|
HttpResponse::NotFound().json("You missed your strike lol")
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get bot configuration
|
/// Get version information
|
||||||
|
async fn version_information() -> impl Responder {
|
||||||
|
HttpResponse::Ok().json(VersionInfo::load_static())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get game configuration
|
||||||
async fn game_configuration() -> impl Responder {
|
async fn game_configuration() -> impl Responder {
|
||||||
HttpResponse::Ok().json(PlayConfiguration::default())
|
HttpResponse::Ok().json(PlayConfiguration::default())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Get default game rules
|
||||||
|
async fn default_game_rules() -> impl Responder {
|
||||||
|
HttpResponse::Ok().json(GameRules::random_players_rules())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Validate game rules
|
||||||
|
async fn validate_game_rules(rules: web::Json<GameRules>) -> impl Responder {
|
||||||
|
HttpResponse::Ok().json(rules.get_errors())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Generate random boats layout
|
||||||
|
async fn gen_boats_layout(rules: web::Json<GameRules>) -> impl Responder {
|
||||||
|
let errors = rules.get_errors();
|
||||||
|
if !errors.is_empty() {
|
||||||
|
return HttpResponse::BadRequest().json(errors);
|
||||||
|
}
|
||||||
|
match BoatsLayout::gen_random_for_rules(&rules) {
|
||||||
|
Ok(l) => HttpResponse::Ok().json(l),
|
||||||
|
Err(e) => {
|
||||||
|
log::error!(
|
||||||
|
"Failed to generate boats layout for valid game rules: {} ! / Rules: {:?}",
|
||||||
|
e,
|
||||||
|
rules
|
||||||
|
);
|
||||||
|
HttpResponse::InternalServerError().json("Failed to generate random layout!")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug)]
|
#[derive(serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug)]
|
||||||
pub struct BotPlayQuery {
|
pub struct BotPlayQuery {
|
||||||
#[serde(flatten)]
|
#[serde(flatten)]
|
||||||
@@ -130,6 +164,7 @@ async fn start_random(
|
|||||||
log::info!("New random play");
|
log::info!("New random play");
|
||||||
resp
|
resp
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn start_server(args: Args) -> std::io::Result<()> {
|
pub async fn start_server(args: Args) -> std::io::Result<()> {
|
||||||
log::info!("Start to listen on {}", args.listen_address);
|
log::info!("Start to listen on {}", args.listen_address);
|
||||||
|
|
||||||
@@ -148,7 +183,11 @@ pub async fn start_server(args: Args) -> std::io::Result<()> {
|
|||||||
App::new()
|
App::new()
|
||||||
.app_data(web::Data::new(dispatcher_actor.clone()))
|
.app_data(web::Data::new(dispatcher_actor.clone()))
|
||||||
.wrap(cors)
|
.wrap(cors)
|
||||||
|
.route("/version", web::get().to(version_information))
|
||||||
.route("/config", web::get().to(game_configuration))
|
.route("/config", web::get().to(game_configuration))
|
||||||
|
.route("/game_rules/default", web::get().to(default_game_rules))
|
||||||
|
.route("/game_rules/validate", web::post().to(validate_game_rules))
|
||||||
|
.route("/generate_boats_layout", web::post().to(gen_boats_layout))
|
||||||
.route("/play/bot", web::get().to(start_bot_play))
|
.route("/play/bot", web::get().to(start_bot_play))
|
||||||
.route("/play/create_invite", web::get().to(start_create_invite))
|
.route("/play/create_invite", web::get().to(start_create_invite))
|
||||||
.route("/play/accept_invite", web::get().to(start_accept_invite))
|
.route("/play/accept_invite", web::get().to(start_accept_invite))
|
||||||
@@ -163,6 +202,7 @@ pub async fn start_server(args: Args) -> std::io::Result<()> {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod test {
|
mod test {
|
||||||
|
use crate::data::GameRules;
|
||||||
use crate::server::BotPlayQuery;
|
use crate::server::BotPlayQuery;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -177,4 +217,20 @@ mod test {
|
|||||||
|
|
||||||
assert_eq!(query, des)
|
assert_eq!(query, des)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn simple_bot_request_serialize_deserialize_no_timeout() {
|
||||||
|
let query = BotPlayQuery {
|
||||||
|
rules: GameRules {
|
||||||
|
strike_timeout: None,
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
player_name: "Player".to_string(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let string = serde_urlencoded::to_string(&query).unwrap();
|
||||||
|
let des = serde_urlencoded::from_str(&string).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(query, des)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@@ -39,7 +39,7 @@ pub struct BotClient {
|
|||||||
requested_rules: GameRules,
|
requested_rules: GameRules,
|
||||||
layout: Option<BoatsLayout>,
|
layout: Option<BoatsLayout>,
|
||||||
number_plays: usize,
|
number_plays: usize,
|
||||||
server_msg_callback: Option<Box<dyn FnMut(&ServerMessage)>>,
|
server_msg_callback: Option<Box<dyn FnMut(&mut ServerMessage)>>,
|
||||||
play_as_bot_type: BotType,
|
play_as_bot_type: BotType,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -81,7 +81,7 @@ impl BotClient {
|
|||||||
|
|
||||||
pub fn with_server_msg_callback<F>(mut self, cb: F) -> Self
|
pub fn with_server_msg_callback<F>(mut self, cb: F) -> Self
|
||||||
where
|
where
|
||||||
F: FnMut(&ServerMessage) + 'static,
|
F: FnMut(&mut ServerMessage) + 'static,
|
||||||
{
|
{
|
||||||
self.server_msg_callback = Some(Box::new(cb));
|
self.server_msg_callback = Some(Box::new(cb));
|
||||||
self
|
self
|
||||||
@@ -152,7 +152,7 @@ impl BotClient {
|
|||||||
};
|
};
|
||||||
|
|
||||||
while let Some(chunk) = socket.next().await {
|
while let Some(chunk) = socket.next().await {
|
||||||
let message = match chunk? {
|
let mut message = match chunk? {
|
||||||
Message::Text(message) => {
|
Message::Text(message) => {
|
||||||
log::trace!("TEXT message from server: {}", message);
|
log::trace!("TEXT message from server: {}", message);
|
||||||
|
|
||||||
@@ -182,7 +182,7 @@ impl BotClient {
|
|||||||
};
|
};
|
||||||
|
|
||||||
if let Some(cb) = &mut self.server_msg_callback {
|
if let Some(cb) = &mut self.server_msg_callback {
|
||||||
(cb)(&message)
|
(cb)(&mut message)
|
||||||
}
|
}
|
||||||
|
|
||||||
match message {
|
match message {
|
||||||
|
@@ -9,7 +9,7 @@ use crate::test::play_utils::check_no_replay_on_hit;
|
|||||||
use crate::test::{bot_client, TestPort};
|
use crate::test::{bot_client, TestPort};
|
||||||
use crate::utils::network_utils::wait_for_port;
|
use crate::utils::network_utils::wait_for_port;
|
||||||
|
|
||||||
fn check_strikes_are_linear(msg: &ServerMessage) {
|
fn check_strikes_are_linear(msg: &mut ServerMessage) {
|
||||||
if let ServerMessage::RequestFire { status } = msg {
|
if let ServerMessage::RequestFire { status } = msg {
|
||||||
let mut in_fire_location = true;
|
let mut in_fire_location = true;
|
||||||
for y in 0..status.rules.map_height {
|
for y in 0..status.rules.map_height {
|
||||||
|
@@ -1,13 +1,16 @@
|
|||||||
use tokio::task;
|
use tokio::task;
|
||||||
|
|
||||||
use crate::args::Args;
|
use crate::args::Args;
|
||||||
|
use crate::consts::MIN_STRIKE_TIMEOUT;
|
||||||
use crate::data::{BoatsLayout, GameRules};
|
use crate::data::{BoatsLayout, GameRules};
|
||||||
|
use crate::human_player_ws::ServerMessage;
|
||||||
use crate::server::start_server;
|
use crate::server::start_server;
|
||||||
use crate::test::bot_client;
|
use crate::test::bot_client;
|
||||||
use crate::test::bot_client::ClientEndResult;
|
use crate::test::bot_client::ClientEndResult;
|
||||||
use crate::test::play_utils::check_no_replay_on_hit;
|
use crate::test::play_utils::check_no_replay_on_hit;
|
||||||
use crate::test::TestPort;
|
use crate::test::TestPort;
|
||||||
use crate::utils::network_utils::wait_for_port;
|
use crate::utils::network_utils::wait_for_port;
|
||||||
|
use crate::utils::time_utils::time;
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn invalid_port() {
|
async fn invalid_port() {
|
||||||
@@ -201,3 +204,37 @@ async fn full_game_no_replay_on_hit() {
|
|||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn check_fire_time_out() {
|
||||||
|
let _ = env_logger::builder().is_test(true).try_init();
|
||||||
|
|
||||||
|
let local_set = task::LocalSet::new();
|
||||||
|
local_set
|
||||||
|
.run_until(async move {
|
||||||
|
task::spawn_local(start_server(Args::for_test(TestPort::RandomCheckTimeout)));
|
||||||
|
wait_for_port(TestPort::RandomCheckTimeout.port()).await;
|
||||||
|
|
||||||
|
let start = time();
|
||||||
|
|
||||||
|
let mut did_skip_one = false;
|
||||||
|
let res = bot_client::BotClient::new(TestPort::RandomCheckTimeout.as_url())
|
||||||
|
.with_rules(
|
||||||
|
GameRules::random_players_rules().with_strike_timeout(MIN_STRIKE_TIMEOUT),
|
||||||
|
)
|
||||||
|
.with_server_msg_callback(move |msg| {
|
||||||
|
if matches!(msg, ServerMessage::RequestFire { .. }) && !did_skip_one {
|
||||||
|
*msg = ServerMessage::OpponentReplacedByBot;
|
||||||
|
did_skip_one = true;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.run_client()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert!(matches!(res, ClientEndResult::Finished { .. }));
|
||||||
|
|
||||||
|
assert!(time() - start >= MIN_STRIKE_TIMEOUT);
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
@@ -10,6 +10,7 @@ enum TestPort {
|
|||||||
RandomBotInvalidBoatsLayoutLenOfABoat,
|
RandomBotInvalidBoatsLayoutLenOfABoat,
|
||||||
RandomBotFullGameMultipleRematch,
|
RandomBotFullGameMultipleRematch,
|
||||||
RandomBotNoReplayOnHit,
|
RandomBotNoReplayOnHit,
|
||||||
|
RandomCheckTimeout,
|
||||||
LinearBotFullGame,
|
LinearBotFullGame,
|
||||||
LinearBotNoReplayOnHit,
|
LinearBotNoReplayOnHit,
|
||||||
IntermediateBotFullGame,
|
IntermediateBotFullGame,
|
||||||
|
@@ -1,7 +1,7 @@
|
|||||||
use crate::human_player_ws::ServerMessage;
|
use crate::human_player_ws::ServerMessage;
|
||||||
|
|
||||||
/// Make sure player can not replay after successful hit
|
/// Make sure player can not replay after successful hit
|
||||||
pub fn check_no_replay_on_hit(msg: &ServerMessage) {
|
pub fn check_no_replay_on_hit(msg: &mut ServerMessage) {
|
||||||
if let ServerMessage::OpponentMustFire { status } | ServerMessage::RequestFire { status } = msg
|
if let ServerMessage::OpponentMustFire { status } | ServerMessage::RequestFire { status } = msg
|
||||||
{
|
{
|
||||||
let diff =
|
let diff =
|
||||||
|
@@ -1,12 +1,4 @@
|
|||||||
use std::error::Error;
|
|
||||||
use std::fmt::Display;
|
|
||||||
use std::io::ErrorKind;
|
|
||||||
|
|
||||||
pub mod network_utils;
|
pub mod network_utils;
|
||||||
|
pub mod res_utils;
|
||||||
pub mod string_utils;
|
pub mod string_utils;
|
||||||
|
pub mod time_utils;
|
||||||
pub type Res<E = ()> = Result<E, Box<dyn Error>>;
|
|
||||||
|
|
||||||
pub fn boxed_error<D: Display>(msg: D) -> Box<dyn Error> {
|
|
||||||
Box::new(std::io::Error::new(ErrorKind::Other, msg.to_string()))
|
|
||||||
}
|
|
||||||
|
9
rust/sea_battle_backend/src/utils/res_utils.rs
Normal file
9
rust/sea_battle_backend/src/utils/res_utils.rs
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
use std::error::Error;
|
||||||
|
use std::fmt::Display;
|
||||||
|
use std::io::ErrorKind;
|
||||||
|
|
||||||
|
pub type Res<E = ()> = Result<E, Box<dyn Error>>;
|
||||||
|
|
||||||
|
pub fn boxed_error<D: Display>(msg: D) -> Box<dyn Error> {
|
||||||
|
Box::new(std::io::Error::new(ErrorKind::Other, msg.to_string()))
|
||||||
|
}
|
9
rust/sea_battle_backend/src/utils/time_utils.rs
Normal file
9
rust/sea_battle_backend/src/utils/time_utils.rs
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
/// Get the current time since epoch
|
||||||
|
pub fn time() -> u64 {
|
||||||
|
SystemTime::now()
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.unwrap()
|
||||||
|
.as_secs()
|
||||||
|
}
|
@@ -1,13 +1,19 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "cli_player"
|
name = "sea_battle_cli_player"
|
||||||
version = "0.1.0"
|
version = "0.2.0"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
license = "GPL-2.0-or-later"
|
||||||
|
description = "A Sea Battle game shell client"
|
||||||
|
repository = "https://gitea.communiquons.org/pierre/SeaBattle"
|
||||||
|
readme = "README.md"
|
||||||
|
authors = ["Pierre Hubert <pierre.git@communiquons.org>"]
|
||||||
|
categories = [ "games" ]
|
||||||
|
|
||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
sea_battle_backend = { path = "../sea_battle_backend" }
|
sea_battle_backend = { path = "../sea_battle_backend", version = "0.2.0" }
|
||||||
clap = { version = "4.0.15", features = ["derive"] }
|
clap = { version = "4.0.16", features = ["derive"] }
|
||||||
log = "0.4.17"
|
log = "0.4.17"
|
||||||
env_logger = "0.9.0"
|
env_logger = "0.9.0"
|
||||||
tui = "0.19.0"
|
tui = "0.19.0"
|
||||||
@@ -24,4 +30,5 @@ futures = "0.3.23"
|
|||||||
serde_json = "1.0.85"
|
serde_json = "1.0.85"
|
||||||
hostname = "0.3.1"
|
hostname = "0.3.1"
|
||||||
rustls = "0.20.6"
|
rustls = "0.20.6"
|
||||||
hyper-rustls = { version = "0.23.0", features = ["rustls-native-certs"] }
|
hyper-rustls = { version = "0.23.0", features = ["rustls-native-certs"] }
|
||||||
|
reqwest = { version = "0.11", features = ["json", "rustls-tls"], default-features = false }
|
41
rust/sea_battle_cli_player/README.md
Normal file
41
rust/sea_battle_cli_player/README.md
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
# Sea battle cli player
|
||||||
|
[](https://drone.communiquons.org/pierre/SeaBattle)
|
||||||
|
[](https://crates.io/crates/sea_battle_cli_player)
|
||||||
|
[](https://docs.rs/sea_battle_cli_player/)
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
A sea battle shell client player for the [sea_battle_backend](https://crates.io/crates/sea_battle_backend) crate, based on the [tui](https://crates.io/crates/tui) library.
|
||||||
|
|
||||||
|
## Available play modes
|
||||||
|
* 🤖 Play against bot (this mode does not require any Internet connection, a local server is automatically spawn)
|
||||||
|
* 🎲 Play against a random player
|
||||||
|
* ➕ Create play invite (online). In this mode, the server returns an invitation code to give to the opponent
|
||||||
|
* 🎫 Accept play invite (online)
|
||||||
|
|
||||||
|
For the 🤖 bot and ➕ create invite modes, game rules can be customized before starting the game.
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
You can install the backend using the following command:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cargo install sea_battle_cli_player
|
||||||
|
```
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
Simply launch using:
|
||||||
|
```bash
|
||||||
|
sea_battle_cli_player
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
## Offline LAN
|
||||||
|
If you want to run a local server to play offline LAN games, the cli player can also act as the server:
|
||||||
|
```bash
|
||||||
|
RUST_LOG=info sea_battle_cli_player -s -l 0.0.0.0:7000
|
||||||
|
```
|
||||||
|
|
||||||
|
Then all the players must specify the address of this server to use it instead of the default official one:
|
||||||
|
```bash
|
||||||
|
sea_battle_cli_player -r http://IP_OF_TARGET:7000
|
||||||
|
```
|
BIN
rust/sea_battle_cli_player/img/SeaBattleCli.png
Normal file
BIN
rust/sea_battle_cli_player/img/SeaBattleCli.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 27 KiB |
@@ -20,7 +20,7 @@ pub struct CliArgs {
|
|||||||
value_parser,
|
value_parser,
|
||||||
default_value = "https://seabattleapi.communiquons.org"
|
default_value = "https://seabattleapi.communiquons.org"
|
||||||
)]
|
)]
|
||||||
pub remote_server_uri: String,
|
pub remote_server: String,
|
||||||
|
|
||||||
/// Local server listen address
|
/// Local server listen address
|
||||||
#[clap(short, long, default_value = "127.0.0.1:5679")]
|
#[clap(short, long, default_value = "127.0.0.1:5679")]
|
||||||
@@ -28,6 +28,10 @@ pub struct CliArgs {
|
|||||||
|
|
||||||
#[clap(long, value_enum)]
|
#[clap(long, value_enum)]
|
||||||
pub dev_screen: Option<TestDevScreen>,
|
pub dev_screen: Option<TestDevScreen>,
|
||||||
|
|
||||||
|
/// Run as server instead of as client
|
||||||
|
#[clap(long, short)]
|
||||||
|
pub serve: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CliArgs {
|
impl CliArgs {
|
||||||
@@ -57,3 +61,14 @@ lazy_static::lazy_static! {
|
|||||||
pub fn cli_args() -> &'static CliArgs {
|
pub fn cli_args() -> &'static CliArgs {
|
||||||
&ARGS
|
&ARGS
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod test {
|
||||||
|
use crate::cli_args::CliArgs;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn verify_cli() {
|
||||||
|
use clap::CommandFactory;
|
||||||
|
CliArgs::command().debug_assert()
|
||||||
|
}
|
||||||
|
}
|
@@ -3,10 +3,13 @@ use crate::server;
|
|||||||
use futures::stream::{SplitSink, SplitStream};
|
use futures::stream::{SplitSink, SplitStream};
|
||||||
use futures::{SinkExt, StreamExt};
|
use futures::{SinkExt, StreamExt};
|
||||||
use hyper_rustls::ConfigBuilderExt;
|
use hyper_rustls::ConfigBuilderExt;
|
||||||
use sea_battle_backend::data::GameRules;
|
use sea_battle_backend::data::*;
|
||||||
use sea_battle_backend::human_player_ws::{ClientMessage, ServerMessage};
|
use sea_battle_backend::human_player_ws::{ClientMessage, ServerMessage};
|
||||||
use sea_battle_backend::server::{BotPlayQuery, PlayRandomQuery};
|
use sea_battle_backend::server::{
|
||||||
use sea_battle_backend::utils::{boxed_error, Res};
|
AcceptInviteQuery, BotPlayQuery, CreateInviteQuery, PlayRandomQuery,
|
||||||
|
};
|
||||||
|
use sea_battle_backend::utils::res_utils::{boxed_error, Res};
|
||||||
|
use std::error::Error;
|
||||||
use std::fmt::Display;
|
use std::fmt::Display;
|
||||||
use std::sync::mpsc::TryRecvError;
|
use std::sync::mpsc::TryRecvError;
|
||||||
use std::sync::{mpsc, Arc};
|
use std::sync::{mpsc, Arc};
|
||||||
@@ -16,6 +19,11 @@ use tokio_tungstenite::{MaybeTlsStream, WebSocketStream};
|
|||||||
|
|
||||||
type WsStream = WebSocketStream<MaybeTlsStream<TcpStream>>;
|
type WsStream = WebSocketStream<MaybeTlsStream<TcpStream>>;
|
||||||
|
|
||||||
|
pub enum GetRemoteVersionError {
|
||||||
|
ConnectionFailed,
|
||||||
|
Other(Box<dyn Error>),
|
||||||
|
}
|
||||||
|
|
||||||
/// Connection client
|
/// Connection client
|
||||||
///
|
///
|
||||||
/// This structure acts as a wrapper around websocket connection that handles automatically parsing
|
/// This structure acts as a wrapper around websocket connection that handles automatically parsing
|
||||||
@@ -26,6 +34,24 @@ pub struct Client {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Client {
|
impl Client {
|
||||||
|
/// Get remote server version
|
||||||
|
pub async fn get_server_version() -> Result<VersionInfo, GetRemoteVersionError> {
|
||||||
|
let url = format!("{}/version", cli_args().remote_server);
|
||||||
|
log::debug!("Getting remote information from {} ...", url);
|
||||||
|
|
||||||
|
let res = match reqwest::get(url).await {
|
||||||
|
Ok(r) => r,
|
||||||
|
Err(e) if e.is_timeout() || e.is_connect() => {
|
||||||
|
return Err(GetRemoteVersionError::ConnectionFailed)
|
||||||
|
}
|
||||||
|
Err(e) => return Err(GetRemoteVersionError::Other(Box::new(e))),
|
||||||
|
};
|
||||||
|
|
||||||
|
res.json()
|
||||||
|
.await
|
||||||
|
.map_err(|e| GetRemoteVersionError::Other(Box::new(e)))
|
||||||
|
}
|
||||||
|
|
||||||
/// Start to play against a bot
|
/// Start to play against a bot
|
||||||
///
|
///
|
||||||
/// When playing against a bot, local server is always used
|
/// When playing against a bot, local server is always used
|
||||||
@@ -49,7 +75,7 @@ impl Client {
|
|||||||
/// Start to play against a random player
|
/// Start to play against a random player
|
||||||
pub async fn start_random_play<D: Display>(player_name: D) -> Res<Self> {
|
pub async fn start_random_play<D: Display>(player_name: D) -> Res<Self> {
|
||||||
Self::connect_url(
|
Self::connect_url(
|
||||||
&cli_args().remote_server_uri,
|
&cli_args().remote_server,
|
||||||
&format!(
|
&format!(
|
||||||
"/play/random?{}",
|
"/play/random?{}",
|
||||||
serde_urlencoded::to_string(&PlayRandomQuery {
|
serde_urlencoded::to_string(&PlayRandomQuery {
|
||||||
@@ -61,6 +87,38 @@ impl Client {
|
|||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Start a play by creating an invite
|
||||||
|
pub async fn start_create_invite<D: Display>(rules: &GameRules, player_name: D) -> Res<Self> {
|
||||||
|
Self::connect_url(
|
||||||
|
&cli_args().remote_server,
|
||||||
|
&format!(
|
||||||
|
"/play/create_invite?{}",
|
||||||
|
serde_urlencoded::to_string(&CreateInviteQuery {
|
||||||
|
rules: rules.clone(),
|
||||||
|
player_name: player_name.to_string()
|
||||||
|
})
|
||||||
|
.unwrap()
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start a play by accepting an invite
|
||||||
|
pub async fn start_accept_invite<D: Display>(code: String, player_name: D) -> Res<Self> {
|
||||||
|
Self::connect_url(
|
||||||
|
&cli_args().remote_server,
|
||||||
|
&format!(
|
||||||
|
"/play/accept_invite?{}",
|
||||||
|
serde_urlencoded::to_string(&AcceptInviteQuery {
|
||||||
|
code,
|
||||||
|
player_name: player_name.to_string()
|
||||||
|
})
|
||||||
|
.unwrap()
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
/// Do connect to a server, returning
|
/// Do connect to a server, returning
|
||||||
async fn connect_url(server: &str, uri: &str) -> Res<Self> {
|
async fn connect_url(server: &str, uri: &str) -> Res<Self> {
|
||||||
let mut ws_url = server.replace("http", "ws");
|
let mut ws_url = server.replace("http", "ws");
|
@@ -2,7 +2,7 @@ extern crate core;
|
|||||||
|
|
||||||
pub mod cli_args;
|
pub mod cli_args;
|
||||||
pub mod client;
|
pub mod client;
|
||||||
pub mod constants;
|
pub mod consts;
|
||||||
pub mod server;
|
pub mod server;
|
||||||
pub mod ui_screens;
|
pub mod ui_screens;
|
||||||
pub mod ui_widgets;
|
pub mod ui_widgets;
|
231
rust/sea_battle_cli_player/src/main.rs
Normal file
231
rust/sea_battle_cli_player/src/main.rs
Normal file
@@ -0,0 +1,231 @@
|
|||||||
|
use std::error::Error;
|
||||||
|
use std::io;
|
||||||
|
use std::io::ErrorKind;
|
||||||
|
|
||||||
|
use crossterm::event::DisableMouseCapture;
|
||||||
|
use crossterm::event::EnableMouseCapture;
|
||||||
|
use crossterm::execute;
|
||||||
|
use crossterm::terminal::EnterAlternateScreen;
|
||||||
|
use crossterm::terminal::LeaveAlternateScreen;
|
||||||
|
use crossterm::terminal::{disable_raw_mode, enable_raw_mode};
|
||||||
|
use env_logger::Env;
|
||||||
|
use tui::backend::{Backend, CrosstermBackend};
|
||||||
|
use tui::Terminal;
|
||||||
|
|
||||||
|
use sea_battle_backend::consts::{
|
||||||
|
INVITE_CODE_LENGTH, MAX_PLAYER_NAME_LENGTH, MIN_PLAYER_NAME_LENGTH,
|
||||||
|
};
|
||||||
|
use sea_battle_backend::data::GameRules;
|
||||||
|
use sea_battle_backend::utils::res_utils::Res;
|
||||||
|
use sea_battle_cli_player::cli_args::{cli_args, TestDevScreen};
|
||||||
|
use sea_battle_cli_player::client::{Client, GetRemoteVersionError};
|
||||||
|
use sea_battle_cli_player::server::run_server;
|
||||||
|
use sea_battle_cli_player::ui_screens::configure_game_rules::GameRulesConfigurationScreen;
|
||||||
|
use sea_battle_cli_player::ui_screens::game_screen::GameScreen;
|
||||||
|
use sea_battle_cli_player::ui_screens::input_screen::InputScreen;
|
||||||
|
use sea_battle_cli_player::ui_screens::popup_screen::PopupScreen;
|
||||||
|
use sea_battle_cli_player::ui_screens::select_play_mode_screen::{
|
||||||
|
SelectPlayModeResult, SelectPlayModeScreen,
|
||||||
|
};
|
||||||
|
use sea_battle_cli_player::ui_screens::*;
|
||||||
|
|
||||||
|
/// Test code screens
|
||||||
|
async fn run_dev<B: Backend>(
|
||||||
|
terminal: &mut Terminal<B>,
|
||||||
|
d: TestDevScreen,
|
||||||
|
) -> Result<(), Box<dyn Error>> {
|
||||||
|
let res = match d {
|
||||||
|
TestDevScreen::Popup => PopupScreen::new("Welcome there!!")
|
||||||
|
.show(terminal)?
|
||||||
|
.as_string(),
|
||||||
|
TestDevScreen::Input => InputScreen::new("What it your name ?")
|
||||||
|
.set_title("A custom title")
|
||||||
|
.show(terminal)?
|
||||||
|
.as_string(),
|
||||||
|
TestDevScreen::Confirm => {
|
||||||
|
confirm_dialog_screen::ConfirmDialogScreen::new("Do you really want to quit game?")
|
||||||
|
.show(terminal)?
|
||||||
|
.as_string()
|
||||||
|
}
|
||||||
|
TestDevScreen::SelectBotType => select_bot_type_screen::SelectBotTypeScreen::default()
|
||||||
|
.show(terminal)?
|
||||||
|
.as_string(),
|
||||||
|
TestDevScreen::SelectPlayMode => {
|
||||||
|
SelectPlayModeScreen::default().show(terminal)?.as_string()
|
||||||
|
}
|
||||||
|
TestDevScreen::SetBoatsLayout => {
|
||||||
|
let rules = GameRules {
|
||||||
|
boats_can_touch: true,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
set_boats_layout_screen::SetBoatsLayoutScreen::new(&rules)
|
||||||
|
.show(terminal)?
|
||||||
|
.as_string()
|
||||||
|
}
|
||||||
|
TestDevScreen::ConfigureGameRules => {
|
||||||
|
GameRulesConfigurationScreen::new(GameRules::default())
|
||||||
|
.show(terminal)?
|
||||||
|
.as_string()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
Err(io::Error::new(
|
||||||
|
ErrorKind::Other,
|
||||||
|
format!("DEV result: {:?}", res),
|
||||||
|
))?
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ask the user to specify the name he should be identified with
|
||||||
|
fn query_player_name<B: Backend>(terminal: &mut Terminal<B>) -> Res<String> {
|
||||||
|
let mut hostname = hostname::get()?.to_string_lossy().to_string();
|
||||||
|
if hostname.len() > MAX_PLAYER_NAME_LENGTH {
|
||||||
|
hostname = hostname[0..MAX_PLAYER_NAME_LENGTH].to_string();
|
||||||
|
}
|
||||||
|
|
||||||
|
let res =
|
||||||
|
InputScreen::new("Please specify the name to which other players should identify you:")
|
||||||
|
.set_title("Player name")
|
||||||
|
.set_value(&hostname)
|
||||||
|
.set_min_length(MIN_PLAYER_NAME_LENGTH)
|
||||||
|
.set_max_length(MAX_PLAYER_NAME_LENGTH)
|
||||||
|
.show(terminal)?;
|
||||||
|
|
||||||
|
Ok(res.value().unwrap_or(hostname))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn run_app<B: Backend>(terminal: &mut Terminal<B>) -> Res {
|
||||||
|
if let Some(d) = cli_args().dev_screen {
|
||||||
|
return run_dev(terminal, d).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut checked_online_compatibility = false;
|
||||||
|
|
||||||
|
let mut rules = GameRules::default();
|
||||||
|
|
||||||
|
let mut username = "".to_string();
|
||||||
|
|
||||||
|
loop {
|
||||||
|
terminal.clear()?;
|
||||||
|
let choice = SelectPlayModeScreen::default().show(terminal)?;
|
||||||
|
|
||||||
|
if let ScreenResult::Ok(c) = choice {
|
||||||
|
// Check compatibility
|
||||||
|
if c.is_online_play_mode() && !checked_online_compatibility {
|
||||||
|
PopupScreen::new("🖥 Checking remote server version...").show_once(terminal)?;
|
||||||
|
let valid_version = match Client::get_server_version().await {
|
||||||
|
Ok(v) => v.is_compatible_with_static_version().unwrap_or(false),
|
||||||
|
Err(GetRemoteVersionError::ConnectionFailed) => {
|
||||||
|
PopupScreen::new("❌ Could not connect to remote server!")
|
||||||
|
.show(terminal)?;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Err(GetRemoteVersionError::Other(e)) => {
|
||||||
|
log::error!("Could not load remote server information! {:?}", e);
|
||||||
|
false
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if !valid_version {
|
||||||
|
PopupScreen::new("❌ Unfortunately, it seems that your version of Sea Battle Cli player is too old to be used online...\n\nPlease update it before trying to play online...").show(terminal)?;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
checked_online_compatibility = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if c.need_player_name() && username.is_empty() {
|
||||||
|
username = query_player_name(terminal)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
if c.need_custom_rules() {
|
||||||
|
rules = match GameRulesConfigurationScreen::new(rules.clone()).show(terminal)? {
|
||||||
|
ScreenResult::Ok(r) => r,
|
||||||
|
ScreenResult::Canceled => continue,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
PopupScreen::new("🔌 Connecting...").show_once(terminal)?;
|
||||||
|
|
||||||
|
let client = match choice {
|
||||||
|
ScreenResult::Ok(SelectPlayModeResult::PlayRandom) => {
|
||||||
|
Client::start_random_play(&username).await
|
||||||
|
}
|
||||||
|
|
||||||
|
// Play against bot
|
||||||
|
ScreenResult::Ok(SelectPlayModeResult::PlayAgainstBot) => {
|
||||||
|
Client::start_bot_play(&rules).await
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create invite
|
||||||
|
ScreenResult::Ok(SelectPlayModeResult::CreateInvite) => {
|
||||||
|
Client::start_create_invite(&rules, &username).await
|
||||||
|
}
|
||||||
|
|
||||||
|
// Join invite
|
||||||
|
ScreenResult::Ok(SelectPlayModeResult::AcceptInvite) => {
|
||||||
|
let code = match InputScreen::new("Invite code")
|
||||||
|
.set_min_length(INVITE_CODE_LENGTH)
|
||||||
|
.set_max_length(INVITE_CODE_LENGTH)
|
||||||
|
.show(terminal)?
|
||||||
|
.value()
|
||||||
|
{
|
||||||
|
None => continue,
|
||||||
|
Some(v) => v,
|
||||||
|
};
|
||||||
|
|
||||||
|
PopupScreen::new("🔌 Connecting...").show_once(terminal)?;
|
||||||
|
Client::start_accept_invite(code, &username).await
|
||||||
|
}
|
||||||
|
|
||||||
|
ScreenResult::Canceled | ScreenResult::Ok(SelectPlayModeResult::Exit) => return Ok(()),
|
||||||
|
};
|
||||||
|
|
||||||
|
match client {
|
||||||
|
Ok(client) => {
|
||||||
|
// Display game screen
|
||||||
|
GameScreen::new(client).show(terminal).await?;
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
log::error!("Failed to connect to server: {}", e);
|
||||||
|
PopupScreen::new("❌ Failed to connect to server!").show(terminal)?;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
pub async fn main() -> Result<(), Box<dyn Error>> {
|
||||||
|
env_logger::Builder::from_env(Env::default()).init();
|
||||||
|
|
||||||
|
if cli_args().serve {
|
||||||
|
run_server().await;
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
// setup terminal
|
||||||
|
enable_raw_mode()?;
|
||||||
|
let mut stdout = io::stdout();
|
||||||
|
execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
|
||||||
|
let backend = CrosstermBackend::new(stdout);
|
||||||
|
let mut terminal = Terminal::new(backend)?;
|
||||||
|
|
||||||
|
// create app and run it
|
||||||
|
let res = run_app(&mut terminal).await;
|
||||||
|
|
||||||
|
// restore terminal
|
||||||
|
disable_raw_mode()?;
|
||||||
|
execute!(
|
||||||
|
terminal.backend_mut(),
|
||||||
|
LeaveAlternateScreen,
|
||||||
|
DisableMouseCapture
|
||||||
|
)?;
|
||||||
|
terminal.show_cursor()?;
|
||||||
|
|
||||||
|
if let Err(err) = res {
|
||||||
|
println!("{:?}", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
@@ -6,6 +6,21 @@ use sea_battle_backend::utils::network_utils;
|
|||||||
|
|
||||||
use crate::cli_args::cli_args;
|
use crate::cli_args::cli_args;
|
||||||
|
|
||||||
|
pub async fn run_server() {
|
||||||
|
let local_set = task::LocalSet::new();
|
||||||
|
|
||||||
|
local_set
|
||||||
|
.run_until(async move {
|
||||||
|
sea_battle_backend::server::start_server(Args {
|
||||||
|
listen_address: cli_args().listen_address.clone(),
|
||||||
|
cors: None,
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("Failed to run local server!")
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn start_server_if_missing() {
|
pub async fn start_server_if_missing() {
|
||||||
if !network_utils::is_port_open(cli_args().listen_port()).await {
|
if !network_utils::is_port_open(cli_args().listen_port()).await {
|
||||||
log::info!(
|
log::info!(
|
||||||
@@ -15,16 +30,7 @@ pub async fn start_server_if_missing() {
|
|||||||
std::thread::spawn(move || {
|
std::thread::spawn(move || {
|
||||||
let rt = Builder::new_current_thread().enable_all().build().unwrap();
|
let rt = Builder::new_current_thread().enable_all().build().unwrap();
|
||||||
|
|
||||||
let local_set = task::LocalSet::new();
|
rt.block_on(run_server());
|
||||||
|
|
||||||
rt.block_on(local_set.run_until(async move {
|
|
||||||
sea_battle_backend::server::start_server(Args {
|
|
||||||
listen_address: cli_args().listen_address.clone(),
|
|
||||||
cors: None,
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.expect("Failed to run local server!")
|
|
||||||
}));
|
|
||||||
});
|
});
|
||||||
|
|
||||||
network_utils::wait_for_port(cli_args().listen_port()).await;
|
network_utils::wait_for_port(cli_args().listen_port()).await;
|
@@ -5,6 +5,9 @@ use std::time::{Duration, Instant};
|
|||||||
|
|
||||||
use crossterm::event;
|
use crossterm::event;
|
||||||
use crossterm::event::{Event, KeyCode};
|
use crossterm::event::{Event, KeyCode};
|
||||||
|
use sea_battle_backend::consts::{
|
||||||
|
MAX_BOATS_NUMBER, MAX_MAP_HEIGHT, MAX_MAP_WIDTH, MAX_STRIKE_TIMEOUT,
|
||||||
|
};
|
||||||
use tui::backend::Backend;
|
use tui::backend::Backend;
|
||||||
use tui::layout::{Constraint, Direction, Layout, Margin};
|
use tui::layout::{Constraint, Direction, Layout, Margin};
|
||||||
use tui::style::{Color, Style};
|
use tui::style::{Color, Style};
|
||||||
@@ -13,7 +16,8 @@ use tui::{Frame, Terminal};
|
|||||||
|
|
||||||
use sea_battle_backend::data::GameRules;
|
use sea_battle_backend::data::GameRules;
|
||||||
|
|
||||||
use crate::constants::{HIGHLIGHT_COLOR, TICK_RATE};
|
use crate::consts::{HIGHLIGHT_COLOR, TICK_RATE};
|
||||||
|
use crate::ui_screens::popup_screen::show_screen_too_small_popup;
|
||||||
use crate::ui_screens::select_bot_type_screen::SelectBotTypeScreen;
|
use crate::ui_screens::select_bot_type_screen::SelectBotTypeScreen;
|
||||||
use crate::ui_screens::utils::centered_rect_size;
|
use crate::ui_screens::utils::centered_rect_size;
|
||||||
use crate::ui_screens::ScreenResult;
|
use crate::ui_screens::ScreenResult;
|
||||||
@@ -26,6 +30,7 @@ enum EditingField {
|
|||||||
MapWidth = 0,
|
MapWidth = 0,
|
||||||
MapHeight,
|
MapHeight,
|
||||||
BoatsList,
|
BoatsList,
|
||||||
|
StrikeTimeout,
|
||||||
BoatsCanTouch,
|
BoatsCanTouch,
|
||||||
PlayerContinueOnHit,
|
PlayerContinueOnHit,
|
||||||
BotType,
|
BotType,
|
||||||
@@ -58,13 +63,13 @@ impl GameRulesConfigurationScreen {
|
|||||||
.checked_sub(last_tick.elapsed())
|
.checked_sub(last_tick.elapsed())
|
||||||
.unwrap_or_else(|| Duration::from_secs(0));
|
.unwrap_or_else(|| Duration::from_secs(0));
|
||||||
|
|
||||||
if crossterm::event::poll(timeout)? {
|
if event::poll(timeout)? {
|
||||||
let mut cursor_pos = self.curr_field as i32;
|
let mut cursor_pos = self.curr_field as i32;
|
||||||
|
|
||||||
if let Event::Key(key) = event::read()? {
|
if let Event::Key(key) = event::read()? {
|
||||||
match key.code {
|
match key.code {
|
||||||
// Quit app
|
// Quit app
|
||||||
KeyCode::Char('q') => return Ok(ScreenResult::Canceled),
|
KeyCode::Char('q') | KeyCode::Esc => return Ok(ScreenResult::Canceled),
|
||||||
|
|
||||||
// Navigate between fields
|
// Navigate between fields
|
||||||
KeyCode::Up | KeyCode::Left => cursor_pos -= 1,
|
KeyCode::Up | KeyCode::Left => cursor_pos -= 1,
|
||||||
@@ -114,24 +119,46 @@ impl GameRulesConfigurationScreen {
|
|||||||
{
|
{
|
||||||
self.rules.remove_last_boat();
|
self.rules.remove_last_boat();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if self.curr_field == EditingField::StrikeTimeout {
|
||||||
|
match self.rules.strike_timeout.unwrap_or(0) / 10 {
|
||||||
|
0 => self.rules.strike_timeout = None,
|
||||||
|
v => self.rules.strike_timeout = Some(v),
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
KeyCode::Char(c) if ('0'..='9').contains(&c) => {
|
KeyCode::Char(c) if ('0'..='9').contains(&c) => {
|
||||||
let val = c.to_string().parse::<usize>().unwrap_or_default();
|
let val = c.to_string().parse::<usize>().unwrap_or_default();
|
||||||
|
|
||||||
if self.curr_field == EditingField::MapWidth {
|
if self.curr_field == EditingField::MapWidth
|
||||||
|
&& self.rules.map_width <= MAX_MAP_WIDTH
|
||||||
|
{
|
||||||
self.rules.map_width *= 10;
|
self.rules.map_width *= 10;
|
||||||
self.rules.map_width += val;
|
self.rules.map_width += val;
|
||||||
}
|
}
|
||||||
|
|
||||||
if self.curr_field == EditingField::MapHeight {
|
if self.curr_field == EditingField::MapHeight
|
||||||
|
&& self.rules.map_height <= MAX_MAP_HEIGHT
|
||||||
|
{
|
||||||
self.rules.map_height *= 10;
|
self.rules.map_height *= 10;
|
||||||
self.rules.map_height += val;
|
self.rules.map_height += val;
|
||||||
}
|
}
|
||||||
|
|
||||||
if self.curr_field == EditingField::BoatsList {
|
if self.curr_field == EditingField::BoatsList
|
||||||
|
&& self.rules.boats_list().len() < MAX_BOATS_NUMBER
|
||||||
|
{
|
||||||
self.rules.add_boat(val);
|
self.rules.add_boat(val);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if self.curr_field == EditingField::StrikeTimeout {
|
||||||
|
let mut timeout = self.rules.strike_timeout.unwrap_or(0);
|
||||||
|
if timeout <= MAX_STRIKE_TIMEOUT {
|
||||||
|
timeout *= 10;
|
||||||
|
timeout += val as u64;
|
||||||
|
self.rules.strike_timeout = Some(timeout);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
_ => {}
|
_ => {}
|
||||||
@@ -153,19 +180,29 @@ impl GameRulesConfigurationScreen {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn ui<B: Backend>(&mut self, f: &mut Frame<B>) {
|
fn ui<B: Backend>(&mut self, f: &mut Frame<B>) {
|
||||||
let area = centered_rect_size(50, 20, &f.size());
|
let (w, h) = (50, 23);
|
||||||
|
|
||||||
let block = Block::default().title("Game rules").borders(Borders::ALL);
|
if f.size().width < w || f.size().height < h {
|
||||||
|
show_screen_too_small_popup(f);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let area = centered_rect_size(w, h, &f.size());
|
||||||
|
|
||||||
|
let block = Block::default()
|
||||||
|
.title("📓 Game rules")
|
||||||
|
.borders(Borders::ALL);
|
||||||
f.render_widget(block, area);
|
f.render_widget(block, area);
|
||||||
|
|
||||||
let chunks = Layout::default()
|
let chunks = Layout::default()
|
||||||
.direction(Direction::Vertical)
|
.direction(Direction::Vertical)
|
||||||
.constraints([
|
.constraints([
|
||||||
Constraint::Length(3),
|
Constraint::Length(3), // Map width
|
||||||
Constraint::Length(3),
|
Constraint::Length(3), // Map height
|
||||||
Constraint::Length(3),
|
Constraint::Length(3), // Boats list
|
||||||
Constraint::Length(1),
|
Constraint::Length(3), // Strike timeout
|
||||||
Constraint::Length(1),
|
Constraint::Length(1), // Boats can touch
|
||||||
|
Constraint::Length(1), // Player continue on hit
|
||||||
Constraint::Length(3), // Bot type
|
Constraint::Length(3), // Bot type
|
||||||
Constraint::Length(1), // Margin
|
Constraint::Length(1), // Margin
|
||||||
Constraint::Length(1), // Buttons
|
Constraint::Length(1), // Buttons
|
||||||
@@ -203,6 +240,13 @@ impl GameRulesConfigurationScreen {
|
|||||||
);
|
);
|
||||||
f.render_widget(editor, chunks[EditingField::BoatsList as usize]);
|
f.render_widget(editor, chunks[EditingField::BoatsList as usize]);
|
||||||
|
|
||||||
|
let editor = TextEditorWidget::new(
|
||||||
|
"Strike timeout (0 to disable)",
|
||||||
|
&self.rules.strike_timeout.unwrap_or(0).to_string(),
|
||||||
|
self.curr_field == EditingField::StrikeTimeout,
|
||||||
|
);
|
||||||
|
f.render_widget(editor, chunks[EditingField::StrikeTimeout as usize]);
|
||||||
|
|
||||||
let editor = CheckboxWidget::new(
|
let editor = CheckboxWidget::new(
|
||||||
"Boats can touch",
|
"Boats can touch",
|
||||||
self.rules.boats_can_touch,
|
self.rules.boats_can_touch,
|
@@ -9,7 +9,7 @@ use tui::text::*;
|
|||||||
use tui::widgets::*;
|
use tui::widgets::*;
|
||||||
use tui::{Frame, Terminal};
|
use tui::{Frame, Terminal};
|
||||||
|
|
||||||
use crate::constants::*;
|
use crate::consts::*;
|
||||||
use crate::ui_screens::utils::centered_rect_size;
|
use crate::ui_screens::utils::centered_rect_size;
|
||||||
use crate::ui_screens::ScreenResult;
|
use crate::ui_screens::ScreenResult;
|
||||||
use crate::ui_widgets::button_widget::ButtonWidget;
|
use crate::ui_widgets::button_widget::ButtonWidget;
|
||||||
@@ -18,6 +18,7 @@ use crate::ui_widgets::button_widget::ButtonWidget;
|
|||||||
pub fn confirm<B: Backend>(terminal: &mut Terminal<B>, msg: &str) -> bool {
|
pub fn confirm<B: Backend>(terminal: &mut Terminal<B>, msg: &str) -> bool {
|
||||||
matches!(
|
matches!(
|
||||||
ConfirmDialogScreen::new(msg)
|
ConfirmDialogScreen::new(msg)
|
||||||
|
.set_can_escape(true)
|
||||||
.show(terminal)
|
.show(terminal)
|
||||||
.unwrap_or(ScreenResult::Canceled),
|
.unwrap_or(ScreenResult::Canceled),
|
||||||
ScreenResult::Ok(true)
|
ScreenResult::Ok(true)
|
||||||
@@ -28,7 +29,7 @@ pub struct ConfirmDialogScreen<'a> {
|
|||||||
title: &'a str,
|
title: &'a str,
|
||||||
msg: &'a str,
|
msg: &'a str,
|
||||||
is_confirm: bool,
|
is_confirm: bool,
|
||||||
can_cancel: bool,
|
can_escape: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> ConfirmDialogScreen<'a> {
|
impl<'a> ConfirmDialogScreen<'a> {
|
||||||
@@ -37,10 +38,15 @@ impl<'a> ConfirmDialogScreen<'a> {
|
|||||||
title: "Confirmation Request",
|
title: "Confirmation Request",
|
||||||
msg,
|
msg,
|
||||||
is_confirm: true,
|
is_confirm: true,
|
||||||
can_cancel: false,
|
can_escape: false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn set_can_escape(mut self, v: bool) -> Self {
|
||||||
|
self.can_escape = v;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
pub fn show<B: Backend>(
|
pub fn show<B: Backend>(
|
||||||
mut self,
|
mut self,
|
||||||
terminal: &mut Terminal<B>,
|
terminal: &mut Terminal<B>,
|
||||||
@@ -56,7 +62,7 @@ impl<'a> ConfirmDialogScreen<'a> {
|
|||||||
if event::poll(timeout)? {
|
if event::poll(timeout)? {
|
||||||
if let Event::Key(key) = event::read()? {
|
if let Event::Key(key) = event::read()? {
|
||||||
match key.code {
|
match key.code {
|
||||||
KeyCode::Esc | KeyCode::Char('q') if self.can_cancel => {
|
KeyCode::Esc | KeyCode::Char('q') if self.can_escape => {
|
||||||
return Ok(ScreenResult::Canceled)
|
return Ok(ScreenResult::Canceled)
|
||||||
}
|
}
|
||||||
|
|
@@ -12,14 +12,17 @@ use tui::{Frame, Terminal};
|
|||||||
|
|
||||||
use sea_battle_backend::data::{Coordinates, CurrentGameMapStatus, CurrentGameStatus};
|
use sea_battle_backend::data::{Coordinates, CurrentGameMapStatus, CurrentGameStatus};
|
||||||
use sea_battle_backend::human_player_ws::{ClientMessage, ServerMessage};
|
use sea_battle_backend::human_player_ws::{ClientMessage, ServerMessage};
|
||||||
use sea_battle_backend::utils::Res;
|
use sea_battle_backend::utils::res_utils::Res;
|
||||||
|
use sea_battle_backend::utils::time_utils::time;
|
||||||
|
|
||||||
use crate::client::Client;
|
use crate::client::Client;
|
||||||
use crate::constants::*;
|
use crate::consts::*;
|
||||||
use crate::ui_screens::confirm_dialog_screen::confirm;
|
use crate::ui_screens::confirm_dialog_screen::confirm;
|
||||||
use crate::ui_screens::popup_screen::PopupScreen;
|
use crate::ui_screens::popup_screen::{show_screen_too_small_popup, PopupScreen};
|
||||||
use crate::ui_screens::set_boats_layout_screen::SetBoatsLayoutScreen;
|
use crate::ui_screens::set_boats_layout_screen::SetBoatsLayoutScreen;
|
||||||
use crate::ui_screens::utils::{centered_rect_size, centered_text};
|
use crate::ui_screens::utils::{
|
||||||
|
centered_rect_size, centered_rect_size_horizontally, centered_text,
|
||||||
|
};
|
||||||
use crate::ui_screens::ScreenResult;
|
use crate::ui_screens::ScreenResult;
|
||||||
use crate::ui_widgets::button_widget::ButtonWidget;
|
use crate::ui_widgets::button_widget::ButtonWidget;
|
||||||
use crate::ui_widgets::game_map_widget::{ColoredCells, GameMapWidget};
|
use crate::ui_widgets::game_map_widget::{ColoredCells, GameMapWidget};
|
||||||
@@ -52,21 +55,21 @@ impl GameStatus {
|
|||||||
|
|
||||||
pub fn status_text(&self) -> &str {
|
pub fn status_text(&self) -> &str {
|
||||||
match self {
|
match self {
|
||||||
GameStatus::Connecting => "Connecting...",
|
GameStatus::Connecting => "🔌 Connecting...",
|
||||||
GameStatus::WaitingForAnotherPlayer => "Waiting for another player...",
|
GameStatus::WaitingForAnotherPlayer => "🕑 Waiting for another player...",
|
||||||
GameStatus::OpponentConnected => "Opponent connected!",
|
GameStatus::OpponentConnected => "✅ Opponent connected!",
|
||||||
GameStatus::WaitingForOpponentBoatsConfig => "Waiting for ### boats configuration",
|
GameStatus::WaitingForOpponentBoatsConfig => "🕑 Waiting for ### boats configuration",
|
||||||
GameStatus::OpponentReady => "### is ready!",
|
GameStatus::OpponentReady => "✅ ### is ready!",
|
||||||
GameStatus::Starting => "Game is starting...",
|
GameStatus::Starting => "🕑 Game is starting...",
|
||||||
GameStatus::MustFire => "You must fire!",
|
GameStatus::MustFire => "🚨 You must fire!",
|
||||||
GameStatus::OpponentMustFire => "### must fire!",
|
GameStatus::OpponentMustFire => "💣 ### must fire!",
|
||||||
GameStatus::WonGame => "You won the game!",
|
GameStatus::WonGame => "🎉 You win the game!",
|
||||||
GameStatus::LostGame => "### won the game. You loose.",
|
GameStatus::LostGame => "😿 ### wins the game. You loose.",
|
||||||
GameStatus::RematchRequestedByOpponent => "Rematch requested by ###",
|
GameStatus::RematchRequestedByOpponent => "❓ Rematch requested by ###",
|
||||||
GameStatus::RematchRequestedByPlayer => "Rematch requested by you",
|
GameStatus::RematchRequestedByPlayer => "❓ Rematch requested by you",
|
||||||
GameStatus::RematchAccepted => "Rematch accepted!",
|
GameStatus::RematchAccepted => "✅ Rematch accepted!",
|
||||||
GameStatus::RematchRejected => "Rematch rejected!",
|
GameStatus::RematchRejected => "❌ Rematch rejected!",
|
||||||
GameStatus::OpponentLeftGame => "Opponent left game!",
|
GameStatus::OpponentLeftGame => "⛔ Opponent left game!",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -82,10 +85,10 @@ enum Buttons {
|
|||||||
impl Buttons {
|
impl Buttons {
|
||||||
pub fn text(&self) -> &str {
|
pub fn text(&self) -> &str {
|
||||||
match self {
|
match self {
|
||||||
Buttons::RequestRematch => "Request rematch",
|
Buttons::RequestRematch => "❓ Request rematch",
|
||||||
Buttons::AcceptRematch => "Accept rematch",
|
Buttons::AcceptRematch => "✅ Accept rematch",
|
||||||
Buttons::RejectRematch => "Reject rematch",
|
Buttons::RejectRematch => "❌ Reject rematch",
|
||||||
Buttons::QuitGame => "Quit game",
|
Buttons::QuitGame => "❌ Quit game",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -95,6 +98,7 @@ pub struct GameScreen {
|
|||||||
invite_code: Option<String>,
|
invite_code: Option<String>,
|
||||||
status: GameStatus,
|
status: GameStatus,
|
||||||
opponent_name: Option<String>,
|
opponent_name: Option<String>,
|
||||||
|
game_last_update: u64,
|
||||||
game: CurrentGameStatus,
|
game: CurrentGameStatus,
|
||||||
curr_shoot_position: Coordinates,
|
curr_shoot_position: Coordinates,
|
||||||
last_opponent_fire_position: Coordinates,
|
last_opponent_fire_position: Coordinates,
|
||||||
@@ -108,6 +112,7 @@ impl GameScreen {
|
|||||||
invite_code: None,
|
invite_code: None,
|
||||||
status: GameStatus::Connecting,
|
status: GameStatus::Connecting,
|
||||||
opponent_name: None,
|
opponent_name: None,
|
||||||
|
game_last_update: 0,
|
||||||
game: Default::default(),
|
game: Default::default(),
|
||||||
curr_shoot_position: Coordinates::new(0, 0),
|
curr_shoot_position: Coordinates::new(0, 0),
|
||||||
last_opponent_fire_position: Coordinates::invalid(),
|
last_opponent_fire_position: Coordinates::invalid(),
|
||||||
@@ -133,7 +138,7 @@ impl GameScreen {
|
|||||||
.unwrap_or_else(|| Duration::from_secs(0));
|
.unwrap_or_else(|| Duration::from_secs(0));
|
||||||
|
|
||||||
// Handle terminal events
|
// Handle terminal events
|
||||||
if crossterm::event::poll(timeout)? {
|
if event::poll(timeout)? {
|
||||||
let event = event::read()?;
|
let event = event::read()?;
|
||||||
|
|
||||||
// Keyboard event
|
// Keyboard event
|
||||||
@@ -142,7 +147,7 @@ impl GameScreen {
|
|||||||
|
|
||||||
match key.code {
|
match key.code {
|
||||||
// Leave game
|
// Leave game
|
||||||
KeyCode::Char('q')
|
KeyCode::Char('q') | KeyCode::Esc
|
||||||
if confirm(terminal, "Do you really want to leave game?") =>
|
if confirm(terminal, "Do you really want to leave game?") =>
|
||||||
{
|
{
|
||||||
self.client.close_connection().await;
|
self.client.close_connection().await;
|
||||||
@@ -238,7 +243,7 @@ impl GameScreen {
|
|||||||
}
|
}
|
||||||
|
|
||||||
ServerMessage::InvalidInviteCode => {
|
ServerMessage::InvalidInviteCode => {
|
||||||
PopupScreen::new("Invalid invite code!").show(terminal)?;
|
PopupScreen::new("❌ Invalid invite code!").show(terminal)?;
|
||||||
return Ok(ScreenResult::Ok(()));
|
return Ok(ScreenResult::Ok(()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -288,11 +293,13 @@ impl GameScreen {
|
|||||||
|
|
||||||
ServerMessage::OpponentMustFire { status } => {
|
ServerMessage::OpponentMustFire { status } => {
|
||||||
self.status = GameStatus::OpponentMustFire;
|
self.status = GameStatus::OpponentMustFire;
|
||||||
|
self.game_last_update = time();
|
||||||
self.game = status;
|
self.game = status;
|
||||||
}
|
}
|
||||||
|
|
||||||
ServerMessage::RequestFire { status } => {
|
ServerMessage::RequestFire { status } => {
|
||||||
self.status = GameStatus::MustFire;
|
self.status = GameStatus::MustFire;
|
||||||
|
self.game_last_update = time();
|
||||||
self.game = status;
|
self.game = status;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -303,11 +310,13 @@ impl GameScreen {
|
|||||||
}
|
}
|
||||||
|
|
||||||
ServerMessage::LostGame { status } => {
|
ServerMessage::LostGame { status } => {
|
||||||
|
self.game_last_update = time();
|
||||||
self.game = status;
|
self.game = status;
|
||||||
self.status = GameStatus::LostGame;
|
self.status = GameStatus::LostGame;
|
||||||
}
|
}
|
||||||
|
|
||||||
ServerMessage::WonGame { status } => {
|
ServerMessage::WonGame { status } => {
|
||||||
|
self.game_last_update = time();
|
||||||
self.game = status;
|
self.game = status;
|
||||||
self.status = GameStatus::WonGame;
|
self.status = GameStatus::WonGame;
|
||||||
}
|
}
|
||||||
@@ -357,6 +366,7 @@ impl GameScreen {
|
|||||||
buttons.push(Buttons::RejectRematch);
|
buttons.push(Buttons::RejectRematch);
|
||||||
} else if self.status != GameStatus::OpponentLeftGame
|
} else if self.status != GameStatus::OpponentLeftGame
|
||||||
&& self.status != GameStatus::RematchRejected
|
&& self.status != GameStatus::RematchRejected
|
||||||
|
&& self.status != GameStatus::RematchRequestedByPlayer
|
||||||
{
|
{
|
||||||
buttons.push(Buttons::RequestRematch);
|
buttons.push(Buttons::RequestRematch);
|
||||||
}
|
}
|
||||||
@@ -468,7 +478,7 @@ impl GameScreen {
|
|||||||
if !self.status.can_show_game_maps() {
|
if !self.status.can_show_game_maps() {
|
||||||
if self.status == GameStatus::WaitingForAnotherPlayer {
|
if self.status == GameStatus::WaitingForAnotherPlayer {
|
||||||
if let Some(code) = &self.invite_code {
|
if let Some(code) = &self.invite_code {
|
||||||
status_text.push_str(&format!("\n Invite code: {}", code));
|
status_text.push_str(&format!("\n\n🎫 Invite code: {}", code));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -476,6 +486,17 @@ impl GameScreen {
|
|||||||
return HashMap::default();
|
return HashMap::default();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Add timeout (if required)
|
||||||
|
let mut timeout_str = String::new();
|
||||||
|
if self.status == GameStatus::MustFire || self.status == GameStatus::OpponentMustFire {
|
||||||
|
if let Some(remaining) = self.game.remaining_time_for_strike {
|
||||||
|
let timeout = self.game_last_update + remaining;
|
||||||
|
if time() < timeout {
|
||||||
|
timeout_str = format!(" {} seconds left", timeout - time());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Draw main ui (default play UI)
|
// Draw main ui (default play UI)
|
||||||
let player_map = self
|
let player_map = self
|
||||||
.player_map(&self.game.your_map, false)
|
.player_map(&self.game.your_map, false)
|
||||||
@@ -519,19 +540,22 @@ impl GameScreen {
|
|||||||
|
|
||||||
let buttons_width = buttons.iter().fold(0, |a, b| a + b.estimated_size().0 + 4);
|
let buttons_width = buttons.iter().fold(0, |a, b| a + b.estimated_size().0 + 4);
|
||||||
|
|
||||||
let max_width = max(maps_width, status_text.len() as u16).max(buttons_width);
|
let max_width = max(maps_width, status_text.len() as u16)
|
||||||
let total_height = 3 + maps_height + 3;
|
.max(buttons_width)
|
||||||
|
.max(timeout_str.len() as u16);
|
||||||
|
let total_height = 3 + 1 + maps_height + 3;
|
||||||
|
|
||||||
// Check if frame is too small
|
// Check if frame is too small
|
||||||
if max_width > f.size().width || total_height > f.size().height {
|
if max_width > f.size().width || total_height > f.size().height {
|
||||||
PopupScreen::new("Screen too small!").show_in_frame(f);
|
show_screen_too_small_popup(f);
|
||||||
return HashMap::default();
|
return HashMap::default();
|
||||||
}
|
}
|
||||||
|
|
||||||
let chunks = Layout::default()
|
let chunks = Layout::default()
|
||||||
.direction(Direction::Vertical)
|
.direction(Direction::Vertical)
|
||||||
.constraints([
|
.constraints([
|
||||||
Constraint::Length(3),
|
Constraint::Length(2),
|
||||||
|
Constraint::Length(2),
|
||||||
Constraint::Length(maps_height),
|
Constraint::Length(maps_height),
|
||||||
Constraint::Length(3),
|
Constraint::Length(3),
|
||||||
])
|
])
|
||||||
@@ -541,25 +565,31 @@ impl GameScreen {
|
|||||||
let paragraph = Paragraph::new(status_text.as_str());
|
let paragraph = Paragraph::new(status_text.as_str());
|
||||||
f.render_widget(paragraph, centered_text(&status_text, &chunks[0]));
|
f.render_widget(paragraph, centered_text(&status_text, &chunks[0]));
|
||||||
|
|
||||||
|
// Render timeout
|
||||||
|
let paragraph = Paragraph::new(timeout_str.as_str());
|
||||||
|
f.render_widget(paragraph, centered_text(&timeout_str, &chunks[1]));
|
||||||
|
|
||||||
// Render maps
|
// Render maps
|
||||||
if show_both_maps {
|
if show_both_maps {
|
||||||
let maps_chunks = Layout::default()
|
let maps_chunks = Layout::default()
|
||||||
.direction(Direction::Horizontal)
|
.direction(Direction::Horizontal)
|
||||||
.constraints([
|
.constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
|
||||||
Constraint::Length(player_map_size.0),
|
.split(chunks[2]);
|
||||||
Constraint::Length(3),
|
|
||||||
Constraint::Length(opponent_map_size.0),
|
|
||||||
])
|
|
||||||
.split(chunks[1]);
|
|
||||||
|
|
||||||
f.render_widget(player_map, maps_chunks[0]);
|
f.render_widget(
|
||||||
f.render_widget(opponent_map, maps_chunks[2]);
|
player_map,
|
||||||
|
centered_rect_size_horizontally(player_map_size.0, &maps_chunks[0]),
|
||||||
|
);
|
||||||
|
f.render_widget(
|
||||||
|
opponent_map,
|
||||||
|
centered_rect_size_horizontally(opponent_map_size.0, &maps_chunks[1]),
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
// Render a single map
|
// Render a single map
|
||||||
if self.can_fire() {
|
if self.can_fire() {
|
||||||
f.render_widget(opponent_map, chunks[1]);
|
f.render_widget(opponent_map, chunks[2]);
|
||||||
} else {
|
} else {
|
||||||
f.render_widget(player_map, chunks[1]);
|
f.render_widget(player_map, chunks[2]);
|
||||||
drop(opponent_map);
|
drop(opponent_map);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -573,7 +603,7 @@ impl GameScreen {
|
|||||||
.map(|_| Constraint::Percentage(100 / buttons.len() as u16))
|
.map(|_| Constraint::Percentage(100 / buttons.len() as u16))
|
||||||
.collect::<Vec<_>>(),
|
.collect::<Vec<_>>(),
|
||||||
)
|
)
|
||||||
.split(chunks[2]);
|
.split(chunks[3]);
|
||||||
|
|
||||||
for (idx, b) in buttons.into_iter().enumerate() {
|
for (idx, b) in buttons.into_iter().enumerate() {
|
||||||
let target = centered_rect_size(
|
let target = centered_rect_size(
|
@@ -10,7 +10,7 @@ use tui::layout::*;
|
|||||||
use tui::widgets::*;
|
use tui::widgets::*;
|
||||||
use tui::{Frame, Terminal};
|
use tui::{Frame, Terminal};
|
||||||
|
|
||||||
use crate::constants::*;
|
use crate::consts::*;
|
||||||
use crate::ui_screens::utils::*;
|
use crate::ui_screens::utils::*;
|
||||||
use crate::ui_screens::ScreenResult;
|
use crate::ui_screens::ScreenResult;
|
||||||
use crate::ui_widgets::button_widget::ButtonWidget;
|
use crate::ui_widgets::button_widget::ButtonWidget;
|
||||||
@@ -125,7 +125,7 @@ impl<'a> InputScreen<'a> {
|
|||||||
|
|
||||||
fn ui<B: Backend>(&mut self, f: &mut Frame<B>) {
|
fn ui<B: Backend>(&mut self, f: &mut Frame<B>) {
|
||||||
let area = centered_rect_size(
|
let area = centered_rect_size(
|
||||||
(self.msg.len() + 4).max(self.max_len + 4) as u16,
|
(self.msg.len() + 4).max(self.max_len + 4).max(25) as u16,
|
||||||
7,
|
7,
|
||||||
&f.size(),
|
&f.size(),
|
||||||
);
|
);
|
@@ -9,11 +9,17 @@ use tui::text::*;
|
|||||||
use tui::widgets::*;
|
use tui::widgets::*;
|
||||||
use tui::{Frame, Terminal};
|
use tui::{Frame, Terminal};
|
||||||
|
|
||||||
use crate::constants::*;
|
use crate::consts::*;
|
||||||
use crate::ui_screens::utils::centered_rect_size;
|
use crate::ui_screens::utils::centered_rect_size;
|
||||||
use crate::ui_screens::ScreenResult;
|
use crate::ui_screens::ScreenResult;
|
||||||
use crate::ui_widgets::button_widget::ButtonWidget;
|
use crate::ui_widgets::button_widget::ButtonWidget;
|
||||||
|
|
||||||
|
/// Convenience function to inform user that his terminal window is too small to display the current
|
||||||
|
/// screen
|
||||||
|
pub fn show_screen_too_small_popup<B: Backend>(f: &mut Frame<B>) {
|
||||||
|
PopupScreen::new("🖵 Screen too small!").show_in_frame(f)
|
||||||
|
}
|
||||||
|
|
||||||
pub struct PopupScreen<'a> {
|
pub struct PopupScreen<'a> {
|
||||||
title: &'a str,
|
title: &'a str,
|
||||||
msg: &'a str,
|
msg: &'a str,
|
||||||
@@ -46,7 +52,7 @@ impl<'a> PopupScreen<'a> {
|
|||||||
if event::poll(timeout)? {
|
if event::poll(timeout)? {
|
||||||
if let Event::Key(key) = event::read()? {
|
if let Event::Key(key) = event::read()? {
|
||||||
match key.code {
|
match key.code {
|
||||||
KeyCode::Char('q') => return Ok(ScreenResult::Canceled),
|
KeyCode::Char('q') | KeyCode::Esc => return Ok(ScreenResult::Canceled),
|
||||||
KeyCode::Enter => {
|
KeyCode::Enter => {
|
||||||
return Ok(ScreenResult::Ok(()));
|
return Ok(ScreenResult::Ok(()));
|
||||||
}
|
}
|
@@ -11,7 +11,7 @@ use tui::{Frame, Terminal};
|
|||||||
|
|
||||||
use sea_battle_backend::data::{BotDescription, BotType, PlayConfiguration};
|
use sea_battle_backend::data::{BotDescription, BotType, PlayConfiguration};
|
||||||
|
|
||||||
use crate::constants::{HIGHLIGHT_COLOR, TICK_RATE};
|
use crate::consts::{HIGHLIGHT_COLOR, TICK_RATE};
|
||||||
use crate::ui_screens::utils::centered_rect_size;
|
use crate::ui_screens::utils::centered_rect_size;
|
||||||
use crate::ui_screens::ScreenResult;
|
use crate::ui_screens::ScreenResult;
|
||||||
|
|
||||||
@@ -49,7 +49,7 @@ impl SelectBotTypeScreen {
|
|||||||
if event::poll(timeout)? {
|
if event::poll(timeout)? {
|
||||||
if let Event::Key(key) = event::read()? {
|
if let Event::Key(key) = event::read()? {
|
||||||
match key.code {
|
match key.code {
|
||||||
KeyCode::Char('q') => return Ok(ScreenResult::Canceled),
|
KeyCode::Char('q') | KeyCode::Esc => return Ok(ScreenResult::Canceled),
|
||||||
KeyCode::Enter => {
|
KeyCode::Enter => {
|
||||||
return Ok(ScreenResult::Ok(self.types[self.curr_selection].r#type));
|
return Ok(ScreenResult::Ok(self.types[self.curr_selection].r#type));
|
||||||
}
|
}
|
@@ -1,7 +1,7 @@
|
|||||||
use std::io;
|
use std::io;
|
||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
use crate::constants::{HIGHLIGHT_COLOR, TICK_RATE};
|
use crate::consts::{HIGHLIGHT_COLOR, TICK_RATE};
|
||||||
use crate::ui_screens::utils::centered_rect_size;
|
use crate::ui_screens::utils::centered_rect_size;
|
||||||
use crate::ui_screens::ScreenResult;
|
use crate::ui_screens::ScreenResult;
|
||||||
use crossterm::event;
|
use crossterm::event;
|
||||||
@@ -17,12 +17,25 @@ pub enum SelectPlayModeResult {
|
|||||||
#[default]
|
#[default]
|
||||||
PlayAgainstBot,
|
PlayAgainstBot,
|
||||||
PlayRandom,
|
PlayRandom,
|
||||||
|
CreateInvite,
|
||||||
|
AcceptInvite,
|
||||||
Exit,
|
Exit,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SelectPlayModeResult {
|
impl SelectPlayModeResult {
|
||||||
/// Specify whether a selected play mode requires a user name or not
|
/// Specify whether a selected play mode requires a user name or not
|
||||||
pub fn need_user_name(&self) -> bool {
|
pub fn need_player_name(&self) -> bool {
|
||||||
|
self != &SelectPlayModeResult::PlayAgainstBot && self != &SelectPlayModeResult::Exit
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Specify whether a selected play mode requires a the user to specify its own game rules or
|
||||||
|
/// not
|
||||||
|
pub fn need_custom_rules(&self) -> bool {
|
||||||
|
self == &SelectPlayModeResult::PlayAgainstBot || self == &SelectPlayModeResult::CreateInvite
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Specify whether a play mode is to be played online or not
|
||||||
|
pub fn is_online_play_mode(&self) -> bool {
|
||||||
self != &SelectPlayModeResult::PlayAgainstBot && self != &SelectPlayModeResult::Exit
|
self != &SelectPlayModeResult::PlayAgainstBot && self != &SelectPlayModeResult::Exit
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -33,17 +46,25 @@ struct PlayModeDescription {
|
|||||||
value: SelectPlayModeResult,
|
value: SelectPlayModeResult,
|
||||||
}
|
}
|
||||||
|
|
||||||
const AVAILABLE_PLAY_MODES: [PlayModeDescription; 3] = [
|
const AVAILABLE_PLAY_MODES: [PlayModeDescription; 5] = [
|
||||||
PlayModeDescription {
|
PlayModeDescription {
|
||||||
name: "Play against bot (offline)",
|
name: "🤖 Play against bot (offline)",
|
||||||
value: SelectPlayModeResult::PlayAgainstBot,
|
value: SelectPlayModeResult::PlayAgainstBot,
|
||||||
},
|
},
|
||||||
PlayModeDescription {
|
PlayModeDescription {
|
||||||
name: "Play against random player (online)",
|
name: "🎲 Play against random player (online)",
|
||||||
value: SelectPlayModeResult::PlayRandom,
|
value: SelectPlayModeResult::PlayRandom,
|
||||||
},
|
},
|
||||||
PlayModeDescription {
|
PlayModeDescription {
|
||||||
name: "Exit app",
|
name: "➕ Create play invite (online)",
|
||||||
|
value: SelectPlayModeResult::CreateInvite,
|
||||||
|
},
|
||||||
|
PlayModeDescription {
|
||||||
|
name: "🎫 Accept play invite (online)",
|
||||||
|
value: SelectPlayModeResult::AcceptInvite,
|
||||||
|
},
|
||||||
|
PlayModeDescription {
|
||||||
|
name: "❌ Exit app",
|
||||||
value: SelectPlayModeResult::Exit,
|
value: SelectPlayModeResult::Exit,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
@@ -71,7 +92,7 @@ impl SelectPlayModeScreen {
|
|||||||
if crossterm::event::poll(timeout)? {
|
if crossterm::event::poll(timeout)? {
|
||||||
if let Event::Key(key) = event::read()? {
|
if let Event::Key(key) = event::read()? {
|
||||||
match key.code {
|
match key.code {
|
||||||
KeyCode::Char('q') => return Ok(ScreenResult::Canceled),
|
KeyCode::Char('q') | KeyCode::Esc => return Ok(ScreenResult::Canceled),
|
||||||
KeyCode::Enter => {
|
KeyCode::Enter => {
|
||||||
return Ok(ScreenResult::Ok(
|
return Ok(ScreenResult::Ok(
|
||||||
AVAILABLE_PLAY_MODES[self.curr_selection].value,
|
AVAILABLE_PLAY_MODES[self.curr_selection].value,
|
||||||
@@ -92,7 +113,7 @@ impl SelectPlayModeScreen {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn ui<B: Backend>(&mut self, f: &mut Frame<B>) {
|
fn ui<B: Backend>(&mut self, f: &mut Frame<B>) {
|
||||||
let area = centered_rect_size(50, 5, &f.size());
|
let area = centered_rect_size(50, 2 + AVAILABLE_PLAY_MODES.len() as u16, &f.size());
|
||||||
|
|
||||||
// Create a List from all list items and highlight the currently selected one
|
// Create a List from all list items and highlight the currently selected one
|
||||||
let items = AVAILABLE_PLAY_MODES
|
let items = AVAILABLE_PLAY_MODES
|
@@ -12,8 +12,9 @@ use tui::{Frame, Terminal};
|
|||||||
|
|
||||||
use sea_battle_backend::data::*;
|
use sea_battle_backend::data::*;
|
||||||
|
|
||||||
use crate::constants::*;
|
use crate::consts::*;
|
||||||
use crate::ui_screens::confirm_dialog_screen::confirm;
|
use crate::ui_screens::confirm_dialog_screen::confirm;
|
||||||
|
use crate::ui_screens::popup_screen::show_screen_too_small_popup;
|
||||||
use crate::ui_screens::utils::{centered_rect_size, centered_text};
|
use crate::ui_screens::utils::{centered_rect_size, centered_text};
|
||||||
use crate::ui_screens::ScreenResult;
|
use crate::ui_screens::ScreenResult;
|
||||||
use crate::ui_widgets::game_map_widget::{ColoredCells, GameMapWidget};
|
use crate::ui_widgets::game_map_widget::{ColoredCells, GameMapWidget};
|
||||||
@@ -65,7 +66,7 @@ impl<'a> SetBoatsLayoutScreen<'a> {
|
|||||||
let event = event::read()?;
|
let event = event::read()?;
|
||||||
if let Event::Key(key) = &event {
|
if let Event::Key(key) = &event {
|
||||||
match key.code {
|
match key.code {
|
||||||
KeyCode::Char('q') => {
|
KeyCode::Char('q') | KeyCode::Esc => {
|
||||||
if !self.confirm_on_cancel
|
if !self.confirm_on_cancel
|
||||||
|| confirm(terminal, "Do you really want to quit?")
|
|| confirm(terminal, "Do you really want to quit?")
|
||||||
{
|
{
|
||||||
@@ -227,6 +228,14 @@ impl<'a> SetBoatsLayoutScreen<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let (w, h) = game_map_widget.estimated_size();
|
let (w, h) = game_map_widget.estimated_size();
|
||||||
|
|
||||||
|
if f.size().width < w || f.size().height < h + 3 {
|
||||||
|
// +3 = for errors
|
||||||
|
show_screen_too_small_popup(f);
|
||||||
|
drop(game_map_widget);
|
||||||
|
return coordinates_mapper;
|
||||||
|
}
|
||||||
|
|
||||||
let area = centered_rect_size(w, h, &f.size());
|
let area = centered_rect_size(w, h, &f.size());
|
||||||
f.render_widget(game_map_widget, area);
|
f.render_widget(game_map_widget, area);
|
||||||
|
|
@@ -46,6 +46,25 @@ pub fn centered_rect_size(width: u16, height: u16, parent: &Rect) -> Rect {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// helper function to create a centered rect using up certain container size, only horizontally
|
||||||
|
pub fn centered_rect_size_horizontally(width: u16, parent: &Rect) -> Rect {
|
||||||
|
if parent.width < width {
|
||||||
|
return Rect {
|
||||||
|
x: parent.x,
|
||||||
|
y: parent.y,
|
||||||
|
width: parent.width,
|
||||||
|
height: parent.height,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
Rect {
|
||||||
|
x: parent.x + (parent.width - width) / 2,
|
||||||
|
y: parent.y,
|
||||||
|
width,
|
||||||
|
height: parent.height,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Get coordinates to render centered text
|
/// Get coordinates to render centered text
|
||||||
pub fn centered_text(text: &str, container: &Rect) -> Rect {
|
pub fn centered_text(text: &str, container: &Rect) -> Rect {
|
||||||
if text.len() > container.width as usize {
|
if text.len() > container.width as usize {
|
@@ -1,6 +1,6 @@
|
|||||||
use std::fmt::Display;
|
use std::fmt::Display;
|
||||||
|
|
||||||
use crate::constants::HIGHLIGHT_COLOR;
|
use crate::consts::HIGHLIGHT_COLOR;
|
||||||
use tui::buffer::Buffer;
|
use tui::buffer::Buffer;
|
||||||
use tui::layout::Rect;
|
use tui::layout::Rect;
|
||||||
use tui::style::{Color, Style};
|
use tui::style::{Color, Style};
|
@@ -1,4 +1,4 @@
|
|||||||
use crate::constants::HIGHLIGHT_COLOR;
|
use crate::consts::HIGHLIGHT_COLOR;
|
||||||
use std::fmt::Display;
|
use std::fmt::Display;
|
||||||
use tui::buffer::Buffer;
|
use tui::buffer::Buffer;
|
||||||
use tui::layout::Rect;
|
use tui::layout::Rect;
|
@@ -77,8 +77,8 @@ impl<'a> GameMapWidget<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn grid_size(&self) -> (u16, u16) {
|
pub fn grid_size(&self) -> (u16, u16) {
|
||||||
let w = self.rules.map_width as u16 * 2 + 1;
|
let w = (self.rules.map_width as u16 * 2) + 2;
|
||||||
let h = self.rules.map_height as u16 * 2 + 1;
|
let h = (self.rules.map_height as u16 * 2) + 2;
|
||||||
|
|
||||||
(w, h)
|
(w, h)
|
||||||
}
|
}
|
@@ -1,6 +1,6 @@
|
|||||||
use std::fmt::Display;
|
use std::fmt::Display;
|
||||||
|
|
||||||
use crate::constants::HIGHLIGHT_COLOR;
|
use crate::consts::HIGHLIGHT_COLOR;
|
||||||
use tui::buffer::Buffer;
|
use tui::buffer::Buffer;
|
||||||
use tui::layout::Rect;
|
use tui::layout::Rect;
|
||||||
use tui::style::*;
|
use tui::style::*;
|
Reference in New Issue
Block a user