Compare commits

...

20 Commits

Author SHA1 Message Date
Bence
5e99034abe Added margin around chessboard 2025-12-02 19:17:52 +01:00
Bence
ac2fe4418c Added dark and light modes 2025-12-02 13:08:34 +01:00
Bence
9444441c07 Readded settings 2025-12-02 11:33:27 +01:00
Bence
2f9a91cab8 Added move history to InGame appstate 2025-11-30 16:46:16 +01:00
Bence
df28a16a55 Added "Return to main menu" button to Private Play 2025-11-30 15:26:32 +01:00
Bence
bfccdf1325 Dynamic button sizing 2025-11-30 14:35:04 +01:00
446413c1b2 added turn changing and checking before moving if the player is allowed to move 2025-11-30 11:58:42 +01:00
d94c088ae9 can now go back to the main menu before starting a match 2025-11-29 20:21:52 +01:00
bc03cead82 added clone to engine structs, added private session launch with starting server from ui 2025-11-29 18:55:10 +01:00
a0bca32733 fixed test conditions 2025-11-27 21:45:38 +01:00
bdbe93932d fixed unicode characters, fixed queen and king position, new min windows size 2025-11-27 21:17:53 +01:00
75c39ccbe4 added new tests for the new code 2025-11-27 16:45:40 +01:00
df02c2eee1 updated ui code with partial rewriting, now if there are two players they will join a match and the board will be drawn 2025-11-27 16:33:08 +01:00
5763716848 fixed error: sending both match notification to the same player and removed old server message struct 2025-11-27 16:31:48 +01:00
2112109470 added optional parameters that the ui will receive from server 2025-11-26 17:53:12 +01:00
Bence
933bb46f17 Board squares flipping 2025-11-26 15:22:23 +01:00
5deebb0621 connecting with websocket to local hosted server instance 2025-11-26 13:55:39 +01:00
60911f93f6 removed unused stuff from test client 2025-11-26 13:55:16 +01:00
7820555fa8 added new packages to ui and removed unused stuff from server 2025-11-26 11:18:58 +01:00
b5c18419d8 readded dependency for workflow 2025-11-25 19:03:38 +01:00
11 changed files with 1495 additions and 383 deletions

View File

@@ -77,6 +77,7 @@ jobs:
release: release:
needs: test-data-upload
if: github.ref == 'refs/heads/master' if: github.ref == 'refs/heads/master'
uses: ./.github/workflows/release.yml uses: ./.github/workflows/release.yml
secrets: inherit secrets: inherit

View File

@@ -1,6 +1,6 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug, Clone)]
pub struct BoardSquare { pub struct BoardSquare {
pub x: usize, pub x: usize,
pub y: usize, pub y: usize,
@@ -28,7 +28,7 @@ impl BoardSquare {
return Self { x: x, y: y }; return Self { x: x, y: y };
} }
pub(in super) fn from_index(idx: u8) -> Self { pub(super) fn from_index(idx: u8) -> Self {
let file = idx % 8; let file = idx % 8;
let rank = idx / 8; let rank = idx / 8;
@@ -39,10 +39,12 @@ impl BoardSquare {
} }
} }
return Self {x: file as usize, y: rank as usize}; return Self {
x: file as usize,
y: rank as usize,
};
} }
pub(in super) fn to_index(&self) -> u8 { pub(super) fn to_index(&self) -> u8 {
return (8 * self.y + self.x) as u8; return (8 * self.y + self.x) as u8;
} }
} }

View File

@@ -1,10 +1,13 @@
use crate::{bitboard::{bitmove::{BitMove, BitMoveType}, board::Board}}; use crate::bitboard::{
bitmove::{BitMove, BitMoveType},
board::Board,
};
use super::boardsquare::BoardSquare; use super::boardsquare::BoardSquare;
use super::piecetype::PieceType; use super::piecetype::PieceType;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug, Clone)]
/*pub struct ChessMove { /*pub struct ChessMove {
pub move_type: MoveType, pub move_type: MoveType,
pub piece_type: PieceType, pub piece_type: PieceType,
@@ -19,14 +22,14 @@ pub enum ChessMove {
piece_type: PieceType, piece_type: PieceType,
from_square: BoardSquare, from_square: BoardSquare,
to_square: BoardSquare, to_square: BoardSquare,
promotion_piece: Option<PieceType> promotion_piece: Option<PieceType>,
}, },
Capture { Capture {
piece_type: PieceType, piece_type: PieceType,
from_square: BoardSquare, from_square: BoardSquare,
to_square: BoardSquare, to_square: BoardSquare,
captured_piece: PieceType, captured_piece: PieceType,
promotion_piece: Option<PieceType> promotion_piece: Option<PieceType>,
}, },
Castle { Castle {
king_type: PieceType, king_type: PieceType,
@@ -34,15 +37,15 @@ pub enum ChessMove {
king_to: BoardSquare, king_to: BoardSquare,
rook_type: PieceType, rook_type: PieceType,
rook_from: BoardSquare, rook_from: BoardSquare,
rook_to: BoardSquare rook_to: BoardSquare,
}, },
EnPassant { EnPassant {
pawn_type: PieceType, pawn_type: PieceType,
from_square: BoardSquare, from_square: BoardSquare,
to_square: BoardSquare, to_square: BoardSquare,
captured_piece: PieceType, captured_piece: PieceType,
captured_from: BoardSquare captured_from: BoardSquare,
} },
} }
impl ChessMove { impl ChessMove {
@@ -56,7 +59,7 @@ impl ChessMove {
piece_type, piece_type,
from_square, from_square,
to_square, to_square,
promotion_piece promotion_piece,
}; };
} }
@@ -72,7 +75,7 @@ impl ChessMove {
from_square, from_square,
to_square, to_square,
captured_piece, captured_piece,
promotion_piece promotion_piece,
}; };
} }
@@ -90,11 +93,11 @@ impl ChessMove {
king_to, king_to,
rook_type, rook_type,
rook_from, rook_from,
rook_to rook_to,
}; };
} }
pub(in super) fn from_bitmove(bitmove: &BitMove, board: &Board) -> Self { pub(super) fn from_bitmove(bitmove: &BitMove, board: &Board) -> Self {
match bitmove.move_type() { match bitmove.move_type() {
BitMoveType::Quiet => { BitMoveType::Quiet => {
let from_square_index = bitmove.from_square(); let from_square_index = bitmove.from_square();
@@ -103,11 +106,16 @@ impl ChessMove {
let to_square = BoardSquare::from_index(bitmove.to_square()); let to_square = BoardSquare::from_index(bitmove.to_square());
let promotion_piece = match bitmove.promotion_piece() { let promotion_piece = match bitmove.promotion_piece() {
Some(piece) => Some(PieceType::from_index(piece)), Some(piece) => Some(PieceType::from_index(piece)),
None => None None => None,
}; };
return ChessMove::Quiet { piece_type, from_square, to_square, promotion_piece } return ChessMove::Quiet {
}, piece_type,
from_square,
to_square,
promotion_piece,
};
}
BitMoveType::Capture => { BitMoveType::Capture => {
let from_square_index = bitmove.from_square(); let from_square_index = bitmove.from_square();
let to_square_index = bitmove.to_square(); let to_square_index = bitmove.to_square();
@@ -117,18 +125,28 @@ impl ChessMove {
let captured_piece = PieceType::from_index(board.piece_board(to_square_index)); let captured_piece = PieceType::from_index(board.piece_board(to_square_index));
let promotion_piece = match bitmove.promotion_piece() { let promotion_piece = match bitmove.promotion_piece() {
Some(piece) => Some(PieceType::from_index(piece)), Some(piece) => Some(PieceType::from_index(piece)),
None => None None => None,
}; };
return ChessMove::Capture { piece_type, from_square, to_square, captured_piece, promotion_piece } return ChessMove::Capture {
}, piece_type,
from_square,
to_square,
captured_piece,
promotion_piece,
};
}
BitMoveType::Castle => { BitMoveType::Castle => {
let from_square_index = bitmove.from_square(); let from_square_index = bitmove.from_square();
let to_square_index = bitmove.to_square(); let to_square_index = bitmove.to_square();
let king_type = PieceType::from_index(board.piece_board(from_square_index)); let king_type = PieceType::from_index(board.piece_board(from_square_index));
let king_from = BoardSquare::from_index(from_square_index); let king_from = BoardSquare::from_index(from_square_index);
let king_to = BoardSquare::from_index(to_square_index); let king_to = BoardSquare::from_index(to_square_index);
let rook_type = if bitmove.from_square() < 32 { PieceType::WhiteRook } else { PieceType::BlackRook }; let rook_type = if bitmove.from_square() < 32 {
PieceType::WhiteRook
} else {
PieceType::BlackRook
};
let rook_from_index = if bitmove.to_square() > bitmove.from_square() { let rook_from_index = if bitmove.to_square() > bitmove.from_square() {
bitmove.from_square() + 3 bitmove.from_square() + 3
} else { } else {
@@ -142,44 +160,72 @@ impl ChessMove {
}; };
let rook_to = BoardSquare::from_index(rook_to_index); let rook_to = BoardSquare::from_index(rook_to_index);
return ChessMove::Castle { king_type, king_from, king_to, rook_type, rook_from, rook_to } return ChessMove::Castle {
}, king_type,
king_from,
king_to,
rook_type,
rook_from,
rook_to,
};
}
BitMoveType::EnPassant => { BitMoveType::EnPassant => {
panic!("ChessMove::from_bitmove was left unimplemented"); panic!("ChessMove::from_bitmove was left unimplemented");
} }
} }
} }
pub(in super) fn to_bitmove(&self) -> BitMove { pub(super) fn to_bitmove(&self) -> BitMove {
let bitmove = match self { let bitmove = match self {
ChessMove::Quiet { piece_type, from_square, to_square, promotion_piece } => { ChessMove::Quiet {
piece_type,
from_square,
to_square,
promotion_piece,
} => {
let promotion_piece = match promotion_piece { let promotion_piece = match promotion_piece {
Some(piece) => Some(piece.to_index()), Some(piece) => Some(piece.to_index()),
None => None None => None,
}; };
return BitMove::quiet( return BitMove::quiet(
from_square.to_index(), from_square.to_index(),
to_square.to_index(), to_square.to_index(),
promotion_piece promotion_piece,
); );
}, }
ChessMove::Capture { piece_type, from_square, to_square, captured_piece, promotion_piece } => { ChessMove::Capture {
piece_type,
from_square,
to_square,
captured_piece,
promotion_piece,
} => {
let promotion_piece = match promotion_piece { let promotion_piece = match promotion_piece {
Some(piece) => Some(piece.to_index()), Some(piece) => Some(piece.to_index()),
None => None None => None,
}; };
return BitMove::capture( return BitMove::capture(
from_square.to_index(), from_square.to_index(),
to_square.to_index(), to_square.to_index(),
promotion_piece promotion_piece,
); );
}, }
ChessMove::Castle { king_type, king_from, king_to, rook_type, rook_from, rook_to } => { ChessMove::Castle {
return BitMove::castle( king_type,
king_from.to_index(), king_from,
king_to.to_index() king_to,
); rook_type,
}, rook_from,
ChessMove::EnPassant { pawn_type, from_square, to_square, captured_piece, captured_from } => { rook_to,
} => {
return BitMove::castle(king_from.to_index(), king_to.to_index());
}
ChessMove::EnPassant {
pawn_type,
from_square,
to_square,
captured_piece,
captured_from,
} => {
panic!("ChessMove::to_bitmove was left unimplemented"); panic!("ChessMove::to_bitmove was left unimplemented");
} }
}; };

View File

@@ -1,6 +1,6 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)] #[derive(Clone, Serialize, Deserialize, Debug)]
pub enum PieceType { pub enum PieceType {
WhitePawn, WhitePawn,
WhiteKnight, WhiteKnight,
@@ -17,8 +17,7 @@ pub enum PieceType {
} }
impl PieceType { impl PieceType {
pub(super) fn from_index(idx: u8) -> Self {
pub(in super) fn from_index(idx: u8) -> Self {
return match idx { return match idx {
0 => PieceType::WhitePawn, 0 => PieceType::WhitePawn,
1 => PieceType::WhiteKnight, 1 => PieceType::WhiteKnight,
@@ -32,10 +31,10 @@ impl PieceType {
9 => PieceType::BlackRook, 9 => PieceType::BlackRook,
10 => PieceType::BlackQueen, 10 => PieceType::BlackQueen,
11 => PieceType::BlackKing, 11 => PieceType::BlackKing,
_ => panic!("invalid piece index! should NEVER appear") _ => panic!("invalid piece index! should NEVER appear"),
};
} }
} pub(super) fn to_index(&self) -> u8 {
pub(in super) fn to_index(&self) -> u8 {
return match self { return match self {
&PieceType::WhitePawn => 0, &PieceType::WhitePawn => 0,
&PieceType::WhiteKnight => 1, &PieceType::WhiteKnight => 1,
@@ -48,7 +47,8 @@ impl PieceType {
&PieceType::BlackBishop => 8, &PieceType::BlackBishop => 8,
&PieceType::BlackRook => 9, &PieceType::BlackRook => 9,
&PieceType::BlackQueen => 10, &PieceType::BlackQueen => 10,
&PieceType::BlackKing => 11 &PieceType::BlackKing => 11,
} };
} }
} }

View File

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

View File

@@ -6,7 +6,6 @@ use engine::{get_available_moves, is_game_over};
use futures_util::{SinkExt, StreamExt}; use futures_util::{SinkExt, StreamExt};
use log::{error, info, warn}; use log::{error, info, warn};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::char::from_u32_unchecked;
use std::collections::{HashMap, VecDeque}; use std::collections::{HashMap, VecDeque};
use std::sync::Arc; use std::sync::Arc;
use tokio::net::TcpStream; use tokio::net::TcpStream;
@@ -46,18 +45,6 @@ pub struct Step {
pub to: String, 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)] #[derive(Serialize, Deserialize)]
pub enum ServerMessage2 { pub enum ServerMessage2 {
GameEnd { GameEnd {
@@ -65,6 +52,7 @@ pub enum ServerMessage2 {
}, },
UIUpdate { UIUpdate {
fen: String, fen: String,
turn_player: String,
}, },
MatchFound { MatchFound {
match_id: Uuid, match_id: Uuid,
@@ -79,12 +67,22 @@ pub enum ServerMessage2 {
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
#[serde(tag = "type")] #[serde(tag = "type")]
enum ClientEvent { enum ClientEvent {
Join { username: String }, Join {
username: String,
},
FindMatch, FindMatch,
Move { step: ChessMove }, Move {
step: ChessMove,
turn_player: String,
},
Resign, Resign,
Chat { text: String }, Chat {
RequestLegalMoves { fen: String }, text: String,
},
RequestLegalMoves {
fen: String,
},
CloseConnection,
} }
#[derive(Debug)] #[derive(Debug)]
@@ -226,7 +224,7 @@ pub async fn handle_connection(
info!("Appended {} to the waiting queue", player_id); info!("Appended {} to the waiting queue", player_id);
info!("queue {:?}", wait_queue); info!("queue {:?}", wait_queue);
} }
Move { step } => { Move { step, turn_player } => {
let match_id = connections let match_id = connections
.lock() .lock()
.await .await
@@ -252,6 +250,7 @@ pub async fn handle_connection(
.unwrap() .unwrap()
.board_state .board_state
.clone(), .clone(),
turn_player: turn_player,
}; };
let _ = broadcast_to_match( let _ = broadcast_to_match(
@@ -278,7 +277,7 @@ pub async fn handle_connection(
&serde_json::to_string(&message).unwrap(), &serde_json::to_string(&message).unwrap(),
) )
.await; .await;
clean_up_match(&matches, &match_id); clean_up_match(&matches, &match_id).await;
} }
None => { None => {
info!("No winner match continues. Id: {}", &match_id); info!("No winner match continues. Id: {}", &match_id);
@@ -342,7 +341,7 @@ pub async fn handle_connection(
} }
}; };
broadcast_to_match( let _ = broadcast_to_match(
&connections, &connections,
&matches, &matches,
connections connections
@@ -355,7 +354,11 @@ pub async fn handle_connection(
&serde_json::to_string(&fuck).unwrap(), &serde_json::to_string(&fuck).unwrap(),
) )
.await; .await;
clean_up_match(&matches, fuck_id); clean_up_match(&matches, fuck_id).await;
}
CloseConnection => {
warn!("Closing connection for: {}", &player_id);
break;
} }
_ => { _ => {
warn!("Not known client event"); warn!("Not known client event");

View File

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

View File

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

View File

@@ -6,5 +6,17 @@ edition = "2024"
[dependencies] [dependencies]
eframe = "0.33.0" eframe = "0.33.0"
egui = "0.33.0" egui = "0.33.0"
tokio-tungstenite = "0.28.0"
winit = "0.30.12" 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