mirror of
https://github.com/szymon-jozef/checkers.git
synced 2026-10-28 11:10:44 +01:00
feat: add starting the game
This commit is contained in:
@@ -3,11 +3,15 @@ use std::net::{IpAddr, Ipv4Addr, SocketAddr};
|
||||
use log::{debug, error, info};
|
||||
use tokio::sync::mpsc::{self, Receiver, Sender};
|
||||
|
||||
use crate::network::{
|
||||
connection::{Connection, ConnectionType},
|
||||
message::{
|
||||
ClientMessage::{self, SignalReadiness, TextMessage},
|
||||
Message, ServerMessage,
|
||||
use crate::{
|
||||
logic::board::board_view::BoardView,
|
||||
network::{
|
||||
connection::{Connection, ConnectionType},
|
||||
message::{
|
||||
ClientMessage::{self, SignalReadiness, TextMessage},
|
||||
Message, ServerMessage,
|
||||
},
|
||||
network_identity::NetworkIdentity,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -21,6 +25,10 @@ pub struct Client {
|
||||
conn_reciever_incoming: Option<Receiver<(SocketAddr, Message<ServerMessage>)>>,
|
||||
conn_sender_outgoing: Sender<Message<ClientMessage>>,
|
||||
settings: ClientSettings,
|
||||
|
||||
identity: Option<NetworkIdentity>,
|
||||
board_view: Option<BoardView>,
|
||||
update_reciever: Option<Receiver<Message<ServerMessage>>>,
|
||||
}
|
||||
|
||||
impl Client {
|
||||
@@ -51,6 +59,9 @@ impl Client {
|
||||
conn_reciever_incoming: Some(conn_reciever),
|
||||
conn_sender_outgoing,
|
||||
settings,
|
||||
identity: None,
|
||||
board_view: None,
|
||||
update_reciever: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -64,6 +75,9 @@ impl Client {
|
||||
|
||||
let settings = self.settings.clone();
|
||||
|
||||
let (update_sender, update_reciever) = mpsc::channel::<Message<ServerMessage>>(1024);
|
||||
self.update_reciever = Some(update_reciever);
|
||||
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
if let Some(oldest_msg) = conn_reciever_incoming.recv().await {
|
||||
@@ -79,13 +93,28 @@ impl Client {
|
||||
|
||||
let _ = sender.send(msg.unwrap()).await;
|
||||
}
|
||||
|
||||
ServerMessage::AcceptHandshake => {
|
||||
info!("Server accepted us! Yay :D");
|
||||
}
|
||||
|
||||
ServerMessage::DeclineHandshake { reason } => {
|
||||
error!("Server declined connection: {}", reason);
|
||||
break;
|
||||
}
|
||||
|
||||
ServerMessage::GameStart {
|
||||
identity,
|
||||
board_view,
|
||||
} => {
|
||||
info!("Server started the game!");
|
||||
info!("Our identity is: {}", identity);
|
||||
/*
|
||||
self.board_view = Some(board_view);
|
||||
self.identity = Some(identity);
|
||||
*/
|
||||
}
|
||||
|
||||
ServerMessage::AvailableCaptures { captures } => todo!(),
|
||||
ServerMessage::AvailableMoves { moves } => todo!(),
|
||||
ServerMessage::BroadcastBoardState { board } => todo!(),
|
||||
|
||||
@@ -3,13 +3,17 @@ use std::net::SocketAddr;
|
||||
use serde::{Deserialize, Serialize, de::DeserializeOwned};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::logic::{
|
||||
board::{
|
||||
board::Board,
|
||||
pawn::{CapturePath, MovePath},
|
||||
use crate::{
|
||||
logic::{
|
||||
board::{
|
||||
board::Board,
|
||||
board_view::BoardView,
|
||||
pawn::{CapturePath, MovePath},
|
||||
},
|
||||
game_master::GameResult,
|
||||
math::position::Position,
|
||||
},
|
||||
game_master::GameResult,
|
||||
math::position::Position,
|
||||
network::network_identity::NetworkIdentity,
|
||||
};
|
||||
|
||||
use postcard::{from_bytes, to_allocvec};
|
||||
@@ -38,15 +42,32 @@ where
|
||||
pub enum ServerMessage {
|
||||
RequestHandshake,
|
||||
AcceptHandshake,
|
||||
DeclineHandshake { reason: String },
|
||||
DeclineHandshake {
|
||||
reason: String,
|
||||
},
|
||||
|
||||
AvailableCaptures { captures: Vec<CapturePath> },
|
||||
AvailableMoves { moves: Vec<MovePath> },
|
||||
GameStart {
|
||||
identity: NetworkIdentity,
|
||||
board_view: BoardView,
|
||||
},
|
||||
|
||||
BroadcastBoardState { board: Board },
|
||||
BroadcastCurrentTurn { active_player: Uuid },
|
||||
AvailableCaptures {
|
||||
captures: Vec<CapturePath>,
|
||||
},
|
||||
AvailableMoves {
|
||||
moves: Vec<MovePath>,
|
||||
},
|
||||
|
||||
GameEnd { result: GameResult },
|
||||
BroadcastBoardState {
|
||||
board: Board,
|
||||
},
|
||||
BroadcastCurrentTurn {
|
||||
active_player: Uuid,
|
||||
},
|
||||
|
||||
GameEnd {
|
||||
result: GameResult,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Debug, PartialEq, Eq, Clone)]
|
||||
|
||||
@@ -1,15 +1,23 @@
|
||||
use std::fmt::Display;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::sync::mpsc::Sender;
|
||||
|
||||
use crate::network::message::{Message, ServerMessage};
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[derive(Deserialize, Serialize, Clone, PartialEq, Eq, Debug)]
|
||||
pub struct NetworkIdentity {
|
||||
pub name: String,
|
||||
pub id: uuid::Uuid,
|
||||
pub is_ready: bool,
|
||||
}
|
||||
|
||||
impl Display for NetworkIdentity {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "(Name: {}, id: {})", self.name, self.id)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for NetworkIdentity {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
|
||||
@@ -7,9 +7,14 @@ use tokio::{
|
||||
net::TcpListener,
|
||||
sync::mpsc::{Receiver, Sender},
|
||||
};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{
|
||||
logic::{board::pawn::CapturePath, game_master::GameMaster, math::position::Position},
|
||||
logic::{
|
||||
board::{board_view::BoardView, pawn::CapturePath},
|
||||
game_master::GameMaster,
|
||||
math::position::Position,
|
||||
},
|
||||
network::{
|
||||
connection::{Connection, ConnectionType},
|
||||
message::{
|
||||
@@ -83,7 +88,7 @@ impl Server {
|
||||
.expect("Could not start the server"),
|
||||
), // TODO! Handle this nicely, as this will
|
||||
// crash gui app
|
||||
connections: HashMap::new(),
|
||||
connections: HashMap::with_capacity(2),
|
||||
sender,
|
||||
reciever,
|
||||
welcoming_reciever: None,
|
||||
@@ -186,7 +191,7 @@ impl Server {
|
||||
},
|
||||
|
||||
ClientMessage::SignalReadiness => {
|
||||
self.handle_readiness(addr)
|
||||
self.handle_readiness(addr).await
|
||||
},
|
||||
|
||||
ClientMessage::RequestCapture { capture_path } => {
|
||||
@@ -210,8 +215,48 @@ impl Server {
|
||||
}
|
||||
}
|
||||
|
||||
fn start_game(&self) {
|
||||
todo!();
|
||||
async fn start_game(&mut self) {
|
||||
info!("Starting the game!");
|
||||
let mut names: Vec<String> = vec![];
|
||||
for networkidentity in self.connections.values() {
|
||||
if networkidentity.identity.is_ready {
|
||||
names.push(networkidentity.identity.name.clone());
|
||||
}
|
||||
}
|
||||
|
||||
if names.len() != self.settings.max_connections {
|
||||
error!("Tried starting the game, but could not gather enough ready player names");
|
||||
return;
|
||||
}
|
||||
|
||||
let game_master = GameMaster::new(&names[0], &names[1]);
|
||||
|
||||
let names_and_ids: Vec<(String, Uuid)> = game_master.get_players_names_and_ids();
|
||||
let board_view: BoardView = game_master.get_board_view();
|
||||
|
||||
let mut msgs: Vec<(SocketAddr, Result<Message<ServerMessage>, postcard::Error>)> = vec![];
|
||||
|
||||
for (name, id) in names_and_ids {
|
||||
for (addr, networkidentity) in self.connections.iter_mut() {
|
||||
if networkidentity.identity.name == name {
|
||||
networkidentity.identity.id = id;
|
||||
|
||||
msgs.push((
|
||||
*addr,
|
||||
Message::new(ServerMessage::GameStart {
|
||||
identity: networkidentity.identity.clone(),
|
||||
board_view: board_view.clone(),
|
||||
}),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (addr, msg) in msgs {
|
||||
self.send_message(addr, msg).await;
|
||||
}
|
||||
|
||||
self.game_master = Some(game_master);
|
||||
}
|
||||
|
||||
/* ======= Processing messages :D helper functions ======== */
|
||||
@@ -293,7 +338,7 @@ impl Server {
|
||||
};
|
||||
}
|
||||
|
||||
fn handle_readiness(&mut self, addr: SocketAddr) {
|
||||
async fn handle_readiness(&mut self, addr: SocketAddr) {
|
||||
self.state.ready_count += 1;
|
||||
info!(
|
||||
"{} signaled readiness. Currently ready: {}/{}",
|
||||
@@ -304,7 +349,7 @@ impl Server {
|
||||
if self.state.ready_count == self.settings.max_connections {
|
||||
info!("All players are ready! Changing state to ServerStage::Game");
|
||||
self.state.stage = ServerStage::Game;
|
||||
self.start_game();
|
||||
self.start_game().await;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user