UI/event #25

Merged
htamas1210 merged 10 commits from UI/event into master 2025-11-27 21:55:30 +01:00
7 changed files with 917 additions and 347 deletions

View File

@@ -7,12 +7,6 @@ use tokio_tungstenite::{connect_async, tungstenite::Message};
use url::Url;
use uuid::Uuid;
#[derive(Serialize, Deserialize, Debug)]
struct Step {
from: String,
to: String,
}
#[derive(Serialize, Deserialize)]
#[serde(tag = "type")]
enum ClientMessage {
@@ -24,17 +18,6 @@ enum ClientMessage {
RequestLegalMoves { fen: String },
}
#[derive(Serialize, Deserialize, Debug)]
struct ServerMessage {
#[serde(rename = "type")]
message_type: String,
player_id: Option<String>,
match_id: Option<String>,
opponent: Option<String>,
color: Option<String>,
reason: Option<String>,
}
#[derive(Serialize, Deserialize)]
pub enum ServerMessage2 {
GameEnd {
@@ -48,6 +31,9 @@ pub enum ServerMessage2 {
color: String,
opponent_name: String,
},
Ok {
response: Result<(), String>,
},
}
#[tokio::main]

View File

@@ -6,7 +6,6 @@ use engine::{get_available_moves, is_game_over};
use futures_util::{SinkExt, StreamExt};
use log::{error, info, warn};
use serde::{Deserialize, Serialize};
use std::char::from_u32_unchecked;
use std::collections::{HashMap, VecDeque};
use std::sync::Arc;
use tokio::net::TcpStream;
@@ -46,18 +45,6 @@ pub struct Step {
pub to: String,
}
/*#[derive(Serialize, Deserialize, Debug)]
struct ServerMessage {
#[serde(rename = "type")]
message_type: String,
player_id: Option<Uuid>,
match_id: Option<Uuid>,
opponent: Option<Uuid>,
color: Option<String>,
reason: Option<String>,
response: Option<String>,
}*/
#[derive(Serialize, Deserialize)]
pub enum ServerMessage2 {
GameEnd {

View File

@@ -1,8 +1,7 @@
mod connection;
mod matchmaking;
use env_logger::{Env, Logger};
use log::{error, info, warn};
use std::env;
use env_logger::Env;
use log::{error, info};
use tokio::net::TcpListener;
#[tokio::main]

View File

@@ -1,5 +1,5 @@
use crate::connection::ServerMessage2;
use crate::connection::{ConnectionMap, GameMatch, MatchMap, WaitingQueue, broadcast_to_match};
use crate::connection::{ConnectionMap, GameMatch, MatchMap, WaitingQueue};
use log::{error, info, warn};
use rand::random;
use uuid::Uuid;
@@ -26,12 +26,8 @@ impl MatchmakingSystem {
}
}
pub async fn clean_up(&self, match_id: Uuid) {
self.matches.lock().await.remove(&match_id);
}
async fn try_create_match(&self) {
info!("Checking for new matches!");
//info!("Checking for new matches!");
let mut queue = self.waiting_queue.lock().await;
while queue.len() >= 2 {
@@ -72,6 +68,7 @@ impl MatchmakingSystem {
}
if let Some(player) = conn_map.get_mut(&black_player) {
player.current_match = Some(match_id);
//TODO: at the end of a match delete this from player
} else {
error!("Could not store match id for black player");
}
@@ -122,7 +119,7 @@ impl MatchmakingSystem {
};
let _ = crate::connection::send_message_to_player_connection(
conn_map.get_mut(&white),
conn_map.get_mut(&black),
&serde_json::to_string(&message).unwrap(),
)
.await;

View File

@@ -6,5 +6,17 @@ edition = "2024"
[dependencies]
eframe = "0.33.0"
egui = "0.33.0"
tokio-tungstenite = "0.28.0"
winit = "0.30.12"
tokio = { version = "1", features = ["full"] }
tokio-tungstenite = "0.21"
tungstenite = "0.21"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
futures-util = "0.3.31"
url = "2.5.7"
uuid = {version = "1.18.1", features = ["v4", "serde"] }
engine = {path = "../engine/"}
log = {version = "0.4.28"}
env_logger = "0.11.8"
local-ip-address = "0.6.5"
anyhow = "1.0.100"

117
ui/src/connection.rs Normal file
View File

@@ -0,0 +1,117 @@
use engine::{chessmove::ChessMove, gameend::GameEnd};
use futures_util::{SinkExt, StreamExt};
use local_ip_address::local_ip;
use log::{error, info, warn};
use serde::{Deserialize, Serialize};
use std::{
net::{IpAddr, Ipv4Addr},
sync::{Arc, Mutex},
};
use tokio_tungstenite::connect_async;
use tungstenite::Message;
use url::Url;
use uuid::Uuid;
use crate::{ChessApp, ClientEvent, SharedGameState};
#[derive(Serialize, Deserialize)]
pub enum ServerMessage2 {
GameEnd {
winner: GameEnd,
},
UIUpdate {
fen: String,
},
MatchFound {
match_id: Uuid,
color: String,
opponent_name: String,
},
Ok {
response: Result<(), String>,
},
}
#[derive(Serialize, Deserialize)]
#[serde(tag = "type")]
enum ClientMessage {
Join { username: String },
FindMatch,
Move { step: ChessMove, fen: String },
Resign,
Chat { text: String },
RequestLegalMoves { fen: String },
}
fn get_ip_address() -> IpAddr {
let ip = local_ip().unwrap_or(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)));
ip
}
pub async fn handle_connection(
server_port: &str,
shared_state: SharedGameState,
ui_events: Arc<Mutex<Vec<ClientEvent>>>,
) -> anyhow::Result<()> {
let address = get_ip_address();
//start main loop
let server_address = String::from("ws://") + &address.to_string() + ":" + server_port;
warn!(
"Machine IpAddress is bound for listener. Ip: {}",
server_address
);
let url = Url::parse(&server_address)?;
let (ws_stream, _) = connect_async(url).await?;
let (mut write, mut read) = ws_stream.split();
while let Some(message) = read.next().await {
info!("connection");
match message {
Ok(msg) => {
if msg.is_text() {
let text = msg.to_text().unwrap();
info!("text: {}", text);
/*if let Ok(parsed) = serde_json::from_str::<ServerMessage2>(text) {
match parsed {
ServerMessage2::GameEnd { winner } => {}
ServerMessage2::UIUpdate { fen } => {}
ServerMessage2::MatchFound {
match_id,
color,
opponent_name,
} => {
//chess_app.player_color = Some(color);
}
ServerMessage2::Ok { response } => {}
_ => {
error!("Received unkown servermessage2");
}
}
}*/
if let Ok(parsed) = serde_json::from_str::<ServerMessage2>(text) {
// Update shared state with server message
shared_state.update_from_server_message(parsed);
}
// Send UI events to server
let events = ui_events.lock().unwrap().drain(..).collect::<Vec<_>>();
for event in events {
let message = serde_json::to_string(&event)?;
write.send(Message::Text(message)).await?;
}
}
}
Err(e) => {
error!("Error receiving message: {}", e);
}
}
}
Ok(())
}

File diff suppressed because it is too large Load Diff