Compare commits

..

15 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
7 changed files with 1375 additions and 475 deletions

View File

@@ -1,6 +1,6 @@
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct BoardSquare {
pub x: usize,
pub y: usize,
@@ -28,10 +28,10 @@ impl BoardSquare {
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 rank = idx / 8;
#[cfg(debug_assertions)]
{
if !(0..8).contains(&rank) {
@@ -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;
}
}

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::piecetype::PieceType;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
#[derive(Serialize, Deserialize, Debug, Clone)]
/*pub struct ChessMove {
pub move_type: MoveType,
pub piece_type: PieceType,
@@ -19,14 +22,14 @@ pub enum ChessMove {
piece_type: PieceType,
from_square: BoardSquare,
to_square: BoardSquare,
promotion_piece: Option<PieceType>
promotion_piece: Option<PieceType>,
},
Capture {
piece_type: PieceType,
from_square: BoardSquare,
to_square: BoardSquare,
captured_piece: PieceType,
promotion_piece: Option<PieceType>
promotion_piece: Option<PieceType>,
},
Castle {
king_type: PieceType,
@@ -34,15 +37,15 @@ pub enum ChessMove {
king_to: BoardSquare,
rook_type: PieceType,
rook_from: BoardSquare,
rook_to: BoardSquare
rook_to: BoardSquare,
},
EnPassant {
pawn_type: PieceType,
from_square: BoardSquare,
to_square: BoardSquare,
captured_piece: PieceType,
captured_from: BoardSquare
}
captured_from: BoardSquare,
},
}
impl ChessMove {
@@ -56,7 +59,7 @@ impl ChessMove {
piece_type,
from_square,
to_square,
promotion_piece
promotion_piece,
};
}
@@ -72,7 +75,7 @@ impl ChessMove {
from_square,
to_square,
captured_piece,
promotion_piece
promotion_piece,
};
}
@@ -90,11 +93,11 @@ impl ChessMove {
king_to,
rook_type,
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() {
BitMoveType::Quiet => {
let from_square_index = bitmove.from_square();
@@ -103,11 +106,16 @@ impl ChessMove {
let to_square = BoardSquare::from_index(bitmove.to_square());
let promotion_piece = match bitmove.promotion_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 => {
let from_square_index = bitmove.from_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 promotion_piece = match bitmove.promotion_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 => {
let from_square_index = bitmove.from_square();
let to_square_index = bitmove.to_square();
let king_type = PieceType::from_index(board.piece_board(from_square_index));
let king_from = BoardSquare::from_index(from_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() {
bitmove.from_square() + 3
} else {
@@ -142,44 +160,72 @@ impl ChessMove {
};
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 => {
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 {
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 {
Some(piece) => Some(piece.to_index()),
None => None
None => None,
};
return BitMove::quiet(
from_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 {
Some(piece) => Some(piece.to_index()),
None => None
None => None,
};
return BitMove::capture(
from_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 } => {
return BitMove::castle(
king_from.to_index(),
king_to.to_index()
);
},
ChessMove::EnPassant { pawn_type, from_square, to_square, captured_piece, captured_from } => {
}
ChessMove::Castle {
king_type,
king_from,
king_to,
rook_type,
rook_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");
}
};

View File

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

View File

@@ -45,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 {
@@ -64,6 +52,7 @@ pub enum ServerMessage2 {
},
UIUpdate {
fen: String,
turn_player: String,
},
MatchFound {
match_id: Uuid,
@@ -78,12 +67,22 @@ pub enum ServerMessage2 {
#[derive(Serialize, Deserialize)]
#[serde(tag = "type")]
enum ClientEvent {
Join { username: String },
Join {
username: String,
},
FindMatch,
Move { step: ChessMove },
Move {
step: ChessMove,
turn_player: String,
},
Resign,
Chat { text: String },
RequestLegalMoves { fen: String },
Chat {
text: String,
},
RequestLegalMoves {
fen: String,
},
CloseConnection,
}
#[derive(Debug)]
@@ -225,7 +224,7 @@ pub async fn handle_connection(
info!("Appended {} to the waiting queue", player_id);
info!("queue {:?}", wait_queue);
}
Move { step } => {
Move { step, turn_player } => {
let match_id = connections
.lock()
.await
@@ -251,6 +250,7 @@ pub async fn handle_connection(
.unwrap()
.board_state
.clone(),
turn_player: turn_player,
};
let _ = broadcast_to_match(
@@ -277,7 +277,7 @@ pub async fn handle_connection(
&serde_json::to_string(&message).unwrap(),
)
.await;
clean_up_match(&matches, &match_id);
clean_up_match(&matches, &match_id).await;
}
None => {
info!("No winner match continues. Id: {}", &match_id);
@@ -341,7 +341,7 @@ pub async fn handle_connection(
}
};
broadcast_to_match(
let _ = broadcast_to_match(
&connections,
&matches,
connections
@@ -354,7 +354,11 @@ pub async fn handle_connection(
&serde_json::to_string(&fuck).unwrap(),
)
.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");

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;
@@ -119,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

@@ -1,16 +1,19 @@
use engine::{chessmove::ChessMove, gameend::GameEnd};
use futures_util::StreamExt;
use futures_util::{SinkExt, StreamExt};
use local_ip_address::local_ip;
use log::{error, info, warn};
use serde::{Deserialize, Serialize};
use std::{
error::Error,
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 {
@@ -46,7 +49,11 @@ fn get_ip_address() -> IpAddr {
ip
}
pub async fn handle_connection(server_port: &str) -> anyhow::Result<()> {
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
@@ -61,7 +68,7 @@ pub async fn handle_connection(server_port: &str) -> anyhow::Result<()> {
let (ws_stream, _) = connect_async(url).await?;
let (mut write, mut read) = ws_stream.split();
let read_handle = while let Some(message) = read.next().await {
while let Some(message) = read.next().await {
info!("connection");
match message {
Ok(msg) => {
@@ -69,7 +76,7 @@ pub async fn handle_connection(server_port: &str) -> anyhow::Result<()> {
let text = msg.to_text().unwrap();
info!("text: {}", text);
if let Ok(parsed) = serde_json::from_str::<ServerMessage2>(text) {
/*if let Ok(parsed) = serde_json::from_str::<ServerMessage2>(text) {
match parsed {
ServerMessage2::GameEnd { winner } => {}
ServerMessage2::UIUpdate { fen } => {}
@@ -77,12 +84,26 @@ pub async fn handle_connection(server_port: &str) -> anyhow::Result<()> {
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?;
}
}
}
@@ -90,7 +111,7 @@ pub async fn handle_connection(server_port: &str) -> anyhow::Result<()> {
error!("Error receiving message: {}", e);
}
}
};
}
Ok(())
}

File diff suppressed because it is too large Load Diff