feat: add game loop

sending and receiving moves from server, client

implementation of this in a simple cli
This commit is contained in:
2026-08-17 23:23:45 +02:00
parent bb2599a3ca
commit e2a37d8a91
2 changed files with 146 additions and 14 deletions

View File

@@ -3,9 +3,12 @@ use std::{
io::{self, Write},
};
use checkers::network::{
use checkers::{
logic::board::pawn::{CapturePath, MovePath},
network::{
client::{Client, ClientData},
network_identity::NetworkIdentity,
},
};
use log::{debug, error, info, warn};
use tokio::sync::mpsc;
@@ -16,11 +19,17 @@ const HELP_COMMAND: &str = "/help";
const SEND_COMMAND: &str = "/send";
const READY_COMMAND: &str = "/ready";
const CAPTURE_COMMAND: &str = "/capture";
const MOVE_COMMAND: &str = "/move";
enum CliCommands {
Quit,
Help,
Send,
Ready,
Capture,
Move,
}
#[derive(Debug, PartialEq)]
@@ -41,11 +50,34 @@ impl TryFrom<&str> for CliCommands {
HELP_COMMAND => Ok(CliCommands::Help),
SEND_COMMAND => Ok(CliCommands::Send),
READY_COMMAND => Ok(CliCommands::Ready),
CAPTURE_COMMAND => Ok(CliCommands::Capture),
MOVE_COMMAND => Ok(CliCommands::Move),
_ => Err(UnknownCommandError),
}
}
}
struct ClientContext {
pub identity: Option<NetworkIdentity>,
pub is_my_turn: bool,
pub available_captures: Option<Vec<CapturePath>>,
pub available_moves: Option<Vec<MovePath>>,
}
impl Default for ClientContext {
fn default() -> Self {
Self {
identity: None,
is_my_turn: false,
available_captures: None,
available_moves: None,
}
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
env_logger::init();
@@ -62,8 +94,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let (stdin_sender, mut stdin_receiver) = mpsc::channel(1024);
let mut indentity: Option<NetworkIdentity> = None;
let mut is_my_turn: bool = false;
let mut context: ClientContext = ClientContext::default();
tokio::task::spawn_blocking(move || {
let stdin = std::io::stdin();
@@ -84,9 +115,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
│\t {} - show this message
│\t {} - message the server you're ready
│\t {} - send text message to the server
│
│\t {} <index>- choose a capture path from the list
│\t {} <index> <index>- choose move from the list. First number is pawn you want to move and second is position it should take
└───────────────────────────────────────
",
QUIT_COMMAND, HELP_COMMAND, READY_COMMAND, SEND_COMMAND,
QUIT_COMMAND, HELP_COMMAND, READY_COMMAND, SEND_COMMAND, CAPTURE_COMMAND, MOVE_COMMAND
);
info!("───────Type /help for help───────");
@@ -101,17 +135,17 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
"Got new identity: {}",
identity
);
indentity = Some(identity);
context.identity = Some(identity);
}
Some(ClientData::BoardView(view)) => {
info!("New board state:\n{}", view.to_string(&indentity.as_ref().unwrap().id));
info!("New board state:\n{}", view.to_string(&context.identity.as_ref().unwrap().id));
}
Some(ClientData::CurrentTurn(current_turn)) => {
is_my_turn = current_turn == indentity.as_ref().expect("Server sent us new current turn without telling us who we are!").id;
if is_my_turn {
context.is_my_turn = current_turn == context.identity.as_ref().expect("Server sent us new current turn without telling us who we are!").id;
if context.is_my_turn {
info!("It's our turn!");
} else {
info!("It's the turn of our enemy!");
@@ -120,12 +154,14 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
Some(ClientData::AvailableCaptures(capture_paths)) => {
info!("Available captures paths: {:?}", capture_paths);
todo!()
context.available_moves = None;
context.available_captures = Some(capture_paths);
}
Some(ClientData::AvailableMoves(move_paths)) => {
info!("Available moves: {:?}", move_paths);
todo!();
context.available_moves = Some(move_paths);
context.available_captures = None;
},
Some(ClientData::TextMessage {sender, content}) => {
@@ -150,8 +186,6 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
if !buffer.is_empty() {
let words: Vec<&str> = buffer.split_whitespace().collect();
let cmd = words[0];
let mut args: String = words[1..].join(" ");
args = args.trim().to_string();
match CliCommands::try_from(cmd) {
Ok(cmd) => match cmd {
@@ -166,8 +200,88 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
client.signal_readiness().await;
}
CliCommands::Send => {
let mut args: String = words[1..].join(" ");
args = args.trim().to_string();
client.send_text_message(args).await;
}
CliCommands::Capture => {
if words.len() < 2 {
error!("Too little arguments!");
continue;
}
let arg = words[1];
match arg.parse::<usize>() {
Ok(index) => {
if let Some(captures) = context.available_captures.as_ref() && context.is_my_turn {
if index >= captures.len() {
error!("Cannot capture path that doesn't exist!");
continue;
}
if !context.is_my_turn {
error!("We cannot capture when it's not our turn!");
}
client.send_capture(captures[index].clone()).await;
}
},
Err(_) => {
error!("Invalid input! Use: /capture <index>, where index is the number from capture_path");
continue;
}
}
},
CliCommands::Move => {
if words.len() < 3 {
error!("Too little arguments provided!");
continue;
}
let arg = words[1];
let move_arg = words[2];
match arg.parse::<usize>() {
Ok(index) => {
if let Some(moves) = context.available_moves.as_ref() && context.is_my_turn {
if index >= moves.len() {
error!("Cannot make a move that doesn't exist!");
continue;
}
if !context.is_my_turn {
error!("We cannot make a move when it's not our turn!");
}
let move_path = moves[index].clone();
match move_arg.parse::<usize>() {
Ok(move_index) => {
if move_index >= move_path.available_steps.len() {
error!("Second index out of range!");
continue;
}
client.send_move(move_path.from, move_path.available_steps[move_index]).await;
},
Err(_) => {
error!("Invalid second index. Use: /move <index> <index>, where first index is the pawn you want to move and second index is position you want it to take");
continue;
}
}
}
},
Err(_) => {
error!("Invalid input! Use: /move <index> <index>, where first index is the pawn you want to move and second index is position you want it to take");
continue;
}
}
},
},
Err(e) => error!("{}", e),
}

View File

@@ -237,6 +237,24 @@ impl Client {
});
}
pub async fn send_capture(&mut self, capture: CapturePath) {
debug!("Requesting sending capture: {:?}", capture);
if let Some(sender) = &self.commands_sender {
let _ = sender.send(ClientCommands::SendCapture(capture)).await;
} else {
error!("Command sender not set!");
}
}
pub async fn send_move(&mut self, from: Position, to: Position) {
debug!("Requested sending move from: {} to: {}", from, to);
if let Some(sender) = &self.commands_sender {
let _ = sender.send(ClientCommands::SendMove { from, to }).await;
} else {
error!("Command sender not set!");
}
}
pub async fn send_text_message(&mut self, content: String) {
if let Some(sender) = &self.commands_sender {
let _ = sender.send(ClientCommands::SendText(content)).await;