Compare commits

..

77 Commits

Author SHA1 Message Date
Hatvani Tamás
6e86de42b5 Update link 2025-12-08 12:06:01 +01:00
Hatvani Tamás
40f3a6e0e3 Create link for presentation 2025-12-08 12:05:01 +01:00
vargadavidlajos
db527ce259 Merge pull request #29 from htamas1210/UI/event
UI/event
2025-12-04 14:46:44 +01:00
da858d9ed4 merge removed line readded 2025-12-04 14:32:46 +01:00
Hatvani Tamás
9efc7e3ba6 Merge branch 'master' into UI/event 2025-12-04 14:21:59 +01:00
568fdba7e7 added move history to ui and server 2025-12-03 22:06:11 +01:00
Varga Dávid Lajos
86b5f172ee added method to get notation of chessmove 2025-12-03 21:09:13 +01:00
5094a6e1fd fixed crashing when a wrong move was mode which was not in the legal moves vector 2025-12-03 20:44:45 +01:00
898ba3e92f fixed request moves event to have the correct fen string 2025-12-03 20:06:41 +01:00
Hatvani Tamás
683c392ab9 Merge pull request #27 from htamas1210/Engine/make-move
Engine/make move
2025-12-03 18:38:08 +01:00
5e85a59c29 fixed tests 2025-12-03 14:18:45 +01:00
dca37108d7 fixed game resignation 2025-12-03 13:37:49 +01:00
66c3f9652f Merge branch 'UI/Appearance' into UI/event 2025-12-02 19:23:53 +01:00
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
ad2ad63e22 filtering positions correctly from av. moves, bug with fen ui update and fenstring from server 2025-12-01 13:27:53 +01:00
f6c9503965 requesting moves from engine, still needs proper checking 2025-11-30 16:57:25 +01:00
Bence
2f9a91cab8 Added move history to InGame appstate 2025-11-30 16:46:16 +01:00
bf490aa73d added legal moves message to send back available moves to clients 2025-11-30 16:32:14 +01:00
73a6cf004b deleted connection file 2025-11-30 16:31:39 +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
Hatvani Tamás
2fd04238f5 Remove checkout step from release.yml
Removed checkout step from release workflow.
2025-11-28 11:47:54 +01:00
Hatvani Tamás
c7bad7665f Update release job dependencies in dispatcher.yml 2025-11-28 11:44:39 +01:00
Hatvani Tamás
b2d1d3f809 Merge pull request #26 from htamas1210/Engine/make-move
Engine/make move
2025-11-28 11:27:38 +01:00
Varga Dávid Lajos
fe8f8621d7 implemented library function get_board_after_move 2025-11-28 00:26:12 +02:00
Varga Dávid Lajos
767e7d14fd added and used method bitboard::makemove::castles::make_castle 2025-11-28 00:15:37 +02:00
Varga Dávid Lajos
074f181791 added file and module structure for bitboard::makemove::castles 2025-11-27 23:57:31 +02:00
Varga Dávid Lajos
542dd39aa6 added and used method bitboard::makemove::captures::make_capture 2025-11-27 23:56:27 +02:00
Varga Dávid Lajos
6db4ae6d07 added file and module structure for bitboard::makemove::captures 2025-11-27 23:50:53 +02:00
Varga Dávid Lajos
171a7b8020 added and used method bitboard::makemove::quiets::make_quiet 2025-11-27 23:49:18 +02:00
Varga Dávid Lajos
205e8811d5 added file and module structure for bitboard::makemove::quiets 2025-11-27 23:28:46 +02:00
Varga Dávid Lajos
2394da84ce added skeleton for method bitboard::makemove::make_move 2025-11-27 23:26:59 +02:00
Varga Dávid Lajos
e7c7743682 added file and module structure for bitboard::makemove 2025-11-27 23:08:39 +02:00
Varga Dávid Lajos
2375f28ee3 added getter method bitboard::board::fen 2025-11-27 23:05:01 +02:00
Bence
036f57daa0 Merge pull request #25 from htamas1210/UI/event
UI/event
2025-11-27 21:55:30 +01:00
a0bca32733 fixed test conditions 2025-11-27 21:45:38 +01:00
Varga Dávid Lajos
5b6318442e added part of getter bitboard::board::fen 2025-11-27 22:31:06 +02:00
Varga Dávid Lajos
24ddc74573 added specialized getter method get_piece_character to bitboard/board.rs 2025-11-27 22:18:04 +02: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
Hatvani Tamás
32ab155ff5 Merge pull request #24 from htamas1210/Engine/API-logic 2025-11-24 15:53:45 +01:00
1f3fff3501 removed test upload dependenci, issue with sheets api 2025-11-24 15:51:37 +01:00
vargadavidlajos
b8113b8cc4 Merge branch 'master' into Engine/API-logic 2025-11-24 15:05:58 +01:00
vargadavidlajos
3795087b3c Merge pull request #23 from htamas1210/Server/logging
Server/logging
2025-11-24 13:30:22 +01:00
Hatvani Tamás
7fdd7fd65c Merge branch 'master' into Server/logging 2025-11-24 13:20:16 +01:00
vargadavidlajos
90a59305ac Merge pull request #22 from htamas1210/Server/event
Server/event
2025-11-24 13:17:29 +01:00
5ccca3ab8e added resign event and deleting finished matches 2025-11-24 13:14:38 +01:00
f2adc14ce2 fixed error, not removing reference to deleted crate 2025-11-24 12:10:29 +01:00
7ed9ae3799 refactored println statements into formatted logs with log crate 2025-11-24 12:05:07 +01:00
622bef963f new serevr message enum for easier message handling 2025-11-24 10:07:20 +01:00
Varga Dávid Lajos
499b0fd152 removed unneeded log message 2025-11-21 23:43:57 +02:00
Varga Dávid Lajos
eba8076ea9 implemented api function is_game_over 2025-11-21 23:41:33 +02:00
Varga Dávid Lajos
f05b1c80da added test for api function is_game_over 2025-11-21 23:26:15 +02:00
Varga Dávid Lajos
068f5248cd implemented api function get_available_moves 2025-11-21 22:56:02 +02:00
Varga Dávid Lajos
a63954fbfe implemented traits needed for testing in lib.rs 2025-11-21 21:52:46 +02:00
Varga Dávid Lajos
2b7faf80ab removed unused variable from conversion method from_bitmove from chessmove.rs 2025-11-21 20:36:22 +02:00
Hatvani Tamás
890fab38cb Merge pull request #21 from htamas1210/Engine/api-conversions 2025-11-21 14:54:51 +01:00
6fc1b6c3fd fixed test function, removed messages because we do not use it 2025-11-20 17:23:30 +01:00
a985182c99 rewrote the message function to use an Option value and check if the playerconnection has value before trying to send message 2025-11-20 16:36:02 +01:00
3b78a8e925 Merge branch 'master' into Server/event 2025-11-20 14:46:33 +01:00
ab369f179c updated move event to use chessmove struct from engine 2025-11-20 14:46:01 +01:00
be6a86bebf handling client move event 2025-11-20 13:38:39 +01:00
5336aadf97 fixed bug in findmatch, added a new command in test client, refactored how the server sends messages to the client 2025-11-19 20:16:55 +01:00
8d559f4b11 added request legal moves to testing client 2025-11-18 17:24:49 +01:00
25 changed files with 3840 additions and 507 deletions

View File

@@ -77,7 +77,7 @@ jobs:
release: release:
needs: test-data-upload needs: [engine, server, ui]
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

@@ -12,9 +12,6 @@ jobs:
name: Build and release (master only) name: Build and release (master only)
runs-on: self-hosted runs-on: self-hosted
steps: steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Build Engine for Linux - name: Build Engine for Linux
run: | run: |
cd $(git rev-parse --show-toplevel) cd $(git rev-parse --show-toplevel)

Binary file not shown.

View File

@@ -3,8 +3,9 @@ mod utils;
mod legality; mod legality;
mod checkinfo; mod checkinfo;
mod attacks; mod attacks;
mod movebuffer;
mod movegen; mod movegen;
pub mod board; pub mod board;
pub(in super) mod bitmove; pub(in super) mod bitmove;
pub(in super) mod movebuffer;
pub(in super) mod makemove;

View File

@@ -1,3 +1,5 @@
use crate::bitboard::utils::notation_from_square_number;
use super::utils::try_get_square_number_from_notation; use super::utils::try_get_square_number_from_notation;
pub struct Board { pub struct Board {
@@ -12,6 +14,7 @@ pub struct Board {
} }
impl Board { impl Board {
pub const EMPTY_SQUARE: u8 = 12;
pub fn new_clear() -> Self { pub fn new_clear() -> Self {
let mut bit_board: Self = Self { let mut bit_board: Self = Self {
@@ -159,6 +162,57 @@ impl Board {
return if self.side_to_move == 0 { self.bitboards[5].trailing_zeros() } else { self.bitboards[11].trailing_zeros() }; return if self.side_to_move == 0 { self.bitboards[5].trailing_zeros() } else { self.bitboards[11].trailing_zeros() };
} }
pub fn fen(&self) -> String {
let mut fen = String::new();
for row in (0..8).rev() {
let mut empty = 0;
for col in 0..8 {
let sq = row * 8 + col;
if let Some(piece) = self.get_piece_character(sq) {
if empty > 0 {
fen.push_str(&empty.to_string());
empty = 0;
}
fen.push(piece);
} else {
empty += 1;
if col == 7 {
fen.push_str(&empty.to_string());
}
}
}
if row > 0 {
fen.push('/');
}
}
fen.push(' ');
if self.side_to_move() == 0 { fen.push('w'); } else { fen.push('b'); }
fen.push(' ');
if self.castling_rights() == 0 {
fen.push('-');
} else {
if self.castling_rights() & (1 << 3) != 0 { fen.push('K'); }
if self.castling_rights() & (1 << 2) != 0 { fen.push('Q'); }
if self.castling_rights() & (1 << 1) != 0 { fen.push('k'); }
if self.castling_rights() & (1 << 0) != 0 { fen.push('q'); }
}
fen.push(' ');
if self.en_passant_square() == 0 {
fen.push('-');
} else {
let sq = self.en_passant_square().trailing_zeros();
fen.push_str(&notation_from_square_number(sq as u8));
}
fen.push_str(" 0 1");
return fen;
}
fn calc_occupancy(&mut self) { fn calc_occupancy(&mut self) {
self.occupancy = [0u64; 3]; self.occupancy = [0u64; 3];
for b in 0..6 { for b in 0..6 {
@@ -196,4 +250,46 @@ impl Board {
_ => () _ => ()
} }
} }
pub fn get_piece_character(&self, index: i32) -> Option<char> {
let sq = 1 << index;
if (self.bitboards[0] & sq) != 0 {
return Some('P');
}
if (self.bitboards[1] & sq) != 0 {
return Some('N');
}
if (self.bitboards[2] & sq) != 0 {
return Some('B');
}
if (self.bitboards[3] & sq) != 0 {
return Some('R');
}
if (self.bitboards[4] & sq) != 0 {
return Some('Q');
}
if (self.bitboards[5] & sq) != 0 {
return Some('K');
}
if (self.bitboards[6] & sq) != 0 {
return Some('p');
}
if (self.bitboards[7] & sq) != 0 {
return Some('n');
}
if (self.bitboards[8] & sq) != 0 {
return Some('b');
}
if (self.bitboards[9] & sq) != 0 {
return Some('r');
}
if (self.bitboards[10] & sq) != 0 {
return Some('q');
}
if (self.bitboards[11] & sq) != 0 {
return Some('k');
}
return None;
}
} }

View File

@@ -0,0 +1,38 @@
mod quiets;
mod captures;
mod castles;
use super::bitmove::BitMoveType;
use super::bitmove::BitMove;
use super::board::Board;
impl Board {
#[inline]
pub fn make_move(&mut self, played_move: &BitMove) {
let move_type = played_move.move_type();
match move_type {
BitMoveType::Quiet => {
self.make_quiet(played_move);
}
BitMoveType::Capture => {
self.make_capture(played_move);
}
BitMoveType::Castle => {
self.make_castle(played_move);
}
BitMoveType::EnPassant => {
}
}
self.occupancy[2] = self.occupancy[0] | self.occupancy[1];
if self.en_passant_square != 0 {
self.en_passant_square = 0u64;
}
self.side_to_move = 1 - self.side_to_move;
}
}

View File

@@ -0,0 +1,82 @@
use super::*;
impl Board {
pub fn make_capture(&mut self, played_move: &BitMove) {
let main_from: usize = played_move.from_square() as usize;
let main_to: usize = played_move.to_square() as usize;
let main_piece: usize = self.piece_board(main_from as u8) as usize;
let friendly_occupancy = main_piece/6;
let color_offset = self.side_to_move * 6;
let castling_offset = 2 - 2 * self.side_to_move as usize;
let castling_rights = self.castling_rights >> castling_offset;
let mut taken_piece = 0u8;
taken_piece = self.piece_board(main_to as u8);
let secondary_piece = taken_piece as usize;
let secondary_from = main_to;
let opponent_castling_offset = 2 * self.side_to_move as usize;
let opponent_castling_rights = self.castling_rights >> opponent_castling_offset;
let opponent_occupancy = 1 - self.side_to_move as usize;
self.bitboards[main_piece] &= !(1 << main_from);
self.occupancy[friendly_occupancy] &= !(1 << main_from);
self.piece_board[main_from] = Self::EMPTY_SQUARE;
self.bitboards[secondary_piece] &= !(1 << secondary_from);
self.occupancy[opponent_occupancy] &= !(1 << secondary_from);
self.piece_board[secondary_from] = Self::EMPTY_SQUARE;
if opponent_castling_rights != 0
&& secondary_piece == 9 - color_offset as usize{
let back_rank_offset = 56 - 56 * self.side_to_move as usize;
if opponent_castling_rights & 0b01 != 0
&& secondary_from == back_rank_offset {
self.castling_rights &= !(1 << opponent_castling_offset);
}
else if opponent_castling_rights & 0b10 != 0
&& secondary_from == 7 + back_rank_offset {
self.castling_rights &= !(2 << opponent_castling_offset);
}
}
if let Some(promotion_piece) = played_move.promotion_piece() {
let promotion_piece = (color_offset + promotion_piece) as usize;
self.bitboards[promotion_piece] |= 1 << main_to;
self.occupancy[friendly_occupancy] |= 1 << main_to;
self.piece_board[main_to] = promotion_piece as u8;
}
else {
self.bitboards[main_piece] |= 1 << main_to;
self.occupancy[friendly_occupancy] |= 1 << main_to;
self.piece_board[main_to] = main_piece as u8;
if main_piece == 5 + color_offset as usize
&& castling_rights != 0 {
if castling_rights & 0b1 != 0 {
self.castling_rights &= !(1 << castling_offset);
}
if castling_rights & 0b10 != 0 {
self.castling_rights &= !(2 << castling_offset);
}
}
else if main_piece == 3 + color_offset as usize
&& castling_rights != 0 {
let back_rank_offset = 56 * self.side_to_move as usize;
if castling_rights & 0b10 != 0
&& main_from == 7 + back_rank_offset {
self.castling_rights &= !(2 << castling_offset);
}
else if castling_rights & 0b1 != 0
&& main_from == back_rank_offset {
self.castling_rights &= !(1 << castling_offset);
}
}
}
}
}

View File

@@ -0,0 +1,35 @@
use super::*;
impl Board {
pub fn make_castle(&mut self, played_move: &BitMove) {
let main_from: usize = played_move.from_square() as usize;
let main_to: usize = played_move.to_square() as usize;
let main_piece: usize = self.piece_board(main_from as u8) as usize;
let friendly_occupancy = main_piece/6;
let castling_offset = 2 - 2 * self.side_to_move as usize;
let secondary_piece: usize = main_piece - 2;
let is_kingside = main_to%8 > 4;
let secondary_from: usize = if is_kingside { main_to + 1 } else { main_to - 2 };
let secondary_to: usize = if is_kingside { main_to - 1 } else { main_to + 1 };
self.bitboards[main_piece] |= 1 << main_to;
self.occupancy[friendly_occupancy] |= 1 << main_to;
self.piece_board[main_to] = main_piece as u8;
self.bitboards[main_piece] &= !(1 << main_from);
self.occupancy[friendly_occupancy] &= !(1 << main_from);
self.piece_board[main_from] = Self::EMPTY_SQUARE;
self.bitboards[secondary_piece] |= 1 << secondary_to;
self.occupancy[friendly_occupancy] |= 1 << secondary_to;
self.piece_board[secondary_to] = secondary_piece as u8;
self.bitboards[secondary_piece] &= !(1 << secondary_from);
self.occupancy[friendly_occupancy] &= !(1 << secondary_from);
self.piece_board[secondary_from] = Self::EMPTY_SQUARE;
self.castling_rights &= !(3 << castling_offset);
}
}

View File

@@ -0,0 +1,61 @@
use super::*;
impl Board {
pub fn make_quiet(&mut self, played_move: &BitMove) {
let main_from: usize = played_move.from_square() as usize;
let main_to: usize = played_move.to_square() as usize;
let main_piece: usize = self.piece_board(main_from as u8) as usize;
let friendly_occupancy = main_piece/6;
let color_offset = self.side_to_move * 6;
let castling_offset = 2 - 2 * self.side_to_move as usize;
let castling_rights = self.castling_rights >> castling_offset;
self.bitboards[main_piece] &= !(1 << main_from);
self.occupancy[friendly_occupancy] &= !(1 << main_from);
self.piece_board[main_from] = Self::EMPTY_SQUARE;
if let Some(promotion_piece) = played_move.promotion_piece() {
let promotion_piece = (color_offset + promotion_piece) as usize;
self.bitboards[promotion_piece] |= 1 << main_to;
self.occupancy[friendly_occupancy] |= 1 << main_to;
self.piece_board[main_to] = promotion_piece as u8;
}
else {
self.bitboards[main_piece] |= 1 << main_to;
self.occupancy[friendly_occupancy] |= 1 << main_to;
self.piece_board[main_to] = main_piece as u8;
if main_piece == 0 && (main_to - main_from) == 16 {
let new_en_passant = main_to - 8;
self.en_passant_square = 1 << new_en_passant;
}
else if main_piece == 6 && (main_from - main_to) == 16 {
let new_en_passant = main_to + 8;
self.en_passant_square = 1 << new_en_passant;
}
else if main_piece == 5 + color_offset as usize
&& castling_rights != 0 {
if castling_rights & 0b1 != 0 {
self.castling_rights &= !(1 << castling_offset);
}
if castling_rights & 0b10 != 0 {
self.castling_rights &= !(2 << castling_offset);
}
}
else if main_piece == 3 + color_offset as usize
&& castling_rights != 0 {
let back_rank_offset = 56 * self.side_to_move as usize;
if castling_rights & 0b10 != 0
&& main_from == 7 + back_rank_offset {
self.castling_rights &= !(2 << castling_offset);
}
else if castling_rights & 0b1 != 0
&& main_from == back_rank_offset {
self.castling_rights &= !(1 << castling_offset);
}
}
}
}
}

View File

@@ -1,6 +1,6 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)] #[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)] #[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,22 +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 promotion_piece = match bitmove.promotion_piece() { let rook_type = if bitmove.from_square() < 32 {
Some(piece) => Some(PieceType::from_index(piece)), PieceType::WhiteRook
None => None } 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 {
@@ -146,47 +160,79 @@ 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");
} }
}; };
return bitmove; return bitmove;
} }
pub fn notation(&self) -> String {
return self.to_bitmove().uci_notation();
}
} }

View File

@@ -1,6 +1,8 @@
use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)]
pub enum GameEnd { pub enum GameEnd {
WhiteWon(String), WhiteWon(String),
BlackWon(String), BlackWon(String),
Draw(String) Draw(String),
} }

View File

@@ -1,24 +1,538 @@
mod bitboard; mod bitboard;
pub mod chessmove;
pub mod piecetype;
pub mod boardsquare; pub mod boardsquare;
pub mod movetype; pub mod chessmove;
pub mod gameend; pub mod gameend;
pub mod movetype;
pub mod piecetype;
use bitboard::board::Board;
use bitboard::movebuffer::MoveBuffer;
use chessmove::ChessMove; use chessmove::ChessMove;
use gameend::GameEnd; use gameend::GameEnd;
pub fn get_available_moves(fen: &str) -> Vec<ChessMove> { pub fn get_available_moves(fen: &str) -> Vec<ChessMove> {
println!("get_available_moves answered"); let mut board = Board::build(fen);
return vec![]; let mut buffer = MoveBuffer::new();
let mut temp_buffer = MoveBuffer::new();
let mut generated_moves: Vec<ChessMove> = vec![];
board.collect_moves(&mut buffer, &mut temp_buffer);
for idx in 0..buffer.count() {
generated_moves.push(ChessMove::from_bitmove(buffer.get(idx), &board));
}
println!(
"get_available_moves resulted in {} moves",
generated_moves.len()
);
return generated_moves;
} }
pub fn is_game_over(fen: &str) -> Option<GameEnd> { pub fn is_game_over(fen: &str) -> Option<GameEnd> {
let mut board = Board::build(fen);
let mut buffer = MoveBuffer::new();
let mut temp_buffer = MoveBuffer::new();
let in_check = board.collect_moves(&mut buffer, &mut temp_buffer);
println!("is_game_over answered"); println!("is_game_over answered");
if buffer.count() > 0 {
return None; return None;
}
if !in_check {
return Some(GameEnd::Draw("".to_string()));
}
return if board.side_to_move() == 0 {
Some(GameEnd::BlackWon("".to_string()))
} else {
Some(GameEnd::WhiteWon("".to_string()))
};
} }
pub fn get_board_after_move(fen: &str, chess_move: &ChessMove) -> String { pub fn get_board_after_move(fen: &str, chess_move: &ChessMove) -> String {
let mut board = Board::build(fen);
let played_move = chess_move.to_bitmove();
println!("get_board_after_move answered"); println!("get_board_after_move answered");
return String::from("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"); board.make_move(&played_move);
return board.fen();
} }
#[cfg(test)]
mod tests {
use crate::boardsquare::BoardSquare;
use crate::gameend::GameEnd;
use crate::piecetype::PieceType::*;
use super::*;
impl PartialEq for ChessMove {
fn eq(&self, other: &Self) -> bool {
canonical(self) == canonical(other)
}
}
impl Eq for ChessMove {}
impl Ord for ChessMove {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
let lhs = canonical(self);
let rhs = canonical(other);
lhs.cmp(&rhs)
}
}
impl PartialOrd for ChessMove {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
fn canonical(m: &ChessMove) -> (u8, u8, u8) {
match m {
ChessMove::Quiet {
piece_type,
from_square,
to_square,
promotion_piece,
} => (0, from_square.to_index(), to_square.to_index()),
ChessMove::Capture {
piece_type,
from_square,
to_square,
captured_piece,
promotion_piece,
} => (1, from_square.to_index(), to_square.to_index()),
ChessMove::Castle {
king_type,
king_from,
king_to,
rook_type,
rook_from,
rook_to,
} => (2, king_from.to_index(), king_to.to_index()),
ChessMove::EnPassant {
pawn_type,
from_square,
to_square,
captured_piece,
captured_from,
} => (3, from_square.to_index(), to_square.to_index()),
}
}
#[test]
fn get_available_moves_test() {
let boards: [&str; 2] = [
"rnbqkbnr/pppppppp/8/1B6/4P3/5P1N/PPPP2PP/RNBQK2R w KQkq e6 0 1",
"6Bn/B2Pk3/8/p1r3NK/3p4/b6P/3p2n1/2R5 w - - 0 1",
];
let mut expected_moves: Vec<Vec<ChessMove>> = vec![
vec![
ChessMove::capture(
WhiteBishop,
BoardSquare::from_coord(1, 4),
BoardSquare::from_coord(3, 6),
BlackPawn,
None,
),
ChessMove::quiet(
WhitePawn,
BoardSquare::from_coord(0, 1),
BoardSquare::from_coord(0, 2),
None,
),
ChessMove::quiet(
WhitePawn,
BoardSquare::from_coord(0, 1),
BoardSquare::from_coord(0, 3),
None,
),
ChessMove::quiet(
WhitePawn,
BoardSquare::from_coord(1, 1),
BoardSquare::from_coord(1, 2),
None,
),
ChessMove::quiet(
WhitePawn,
BoardSquare::from_coord(1, 1),
BoardSquare::from_coord(1, 3),
None,
),
ChessMove::quiet(
WhitePawn,
BoardSquare::from_coord(2, 1),
BoardSquare::from_coord(2, 2),
None,
),
ChessMove::quiet(
WhitePawn,
BoardSquare::from_coord(2, 1),
BoardSquare::from_coord(2, 3),
None,
),
ChessMove::quiet(
WhitePawn,
BoardSquare::from_coord(3, 1),
BoardSquare::from_coord(3, 2),
None,
),
ChessMove::quiet(
WhitePawn,
BoardSquare::from_coord(3, 1),
BoardSquare::from_coord(3, 3),
None,
),
ChessMove::quiet(
WhitePawn,
BoardSquare::from_coord(4, 3),
BoardSquare::from_coord(4, 4),
None,
),
ChessMove::quiet(
WhitePawn,
BoardSquare::from_coord(5, 2),
BoardSquare::from_coord(5, 3),
None,
),
ChessMove::quiet(
WhitePawn,
BoardSquare::from_coord(6, 1),
BoardSquare::from_coord(6, 2),
None,
),
ChessMove::quiet(
WhitePawn,
BoardSquare::from_coord(6, 1),
BoardSquare::from_coord(6, 3),
None,
),
ChessMove::quiet(
WhiteKnight,
BoardSquare::from_coord(1, 0),
BoardSquare::from_coord(0, 2),
None,
),
ChessMove::quiet(
WhiteKnight,
BoardSquare::from_coord(1, 0),
BoardSquare::from_coord(2, 2),
None,
),
ChessMove::quiet(
WhiteKnight,
BoardSquare::from_coord(7, 2),
BoardSquare::from_coord(6, 0),
None,
),
ChessMove::quiet(
WhiteKnight,
BoardSquare::from_coord(7, 2),
BoardSquare::from_coord(5, 1),
None,
),
ChessMove::quiet(
WhiteKnight,
BoardSquare::from_coord(7, 2),
BoardSquare::from_coord(5, 3),
None,
),
ChessMove::quiet(
WhiteKnight,
BoardSquare::from_coord(7, 2),
BoardSquare::from_coord(6, 4),
None,
),
ChessMove::quiet(
WhiteBishop,
BoardSquare::from_coord(1, 4),
BoardSquare::from_coord(5, 0),
None,
),
ChessMove::quiet(
WhiteBishop,
BoardSquare::from_coord(1, 4),
BoardSquare::from_coord(4, 1),
None,
),
ChessMove::quiet(
WhiteBishop,
BoardSquare::from_coord(1, 4),
BoardSquare::from_coord(3, 2),
None,
),
ChessMove::quiet(
WhiteBishop,
BoardSquare::from_coord(1, 4),
BoardSquare::from_coord(2, 3),
None,
),
ChessMove::quiet(
WhiteBishop,
BoardSquare::from_coord(1, 4),
BoardSquare::from_coord(0, 3),
None,
),
ChessMove::quiet(
WhiteBishop,
BoardSquare::from_coord(1, 4),
BoardSquare::from_coord(0, 5),
None,
),
ChessMove::quiet(
WhiteBishop,
BoardSquare::from_coord(1, 4),
BoardSquare::from_coord(2, 5),
None,
),
ChessMove::quiet(
WhiteRook,
BoardSquare::from_coord(7, 0),
BoardSquare::from_coord(6, 0),
None,
),
ChessMove::quiet(
WhiteRook,
BoardSquare::from_coord(7, 0),
BoardSquare::from_coord(5, 0),
None,
),
ChessMove::quiet(
WhiteQueen,
BoardSquare::from_coord(3, 0),
BoardSquare::from_coord(4, 1),
None,
),
ChessMove::quiet(
WhiteKing,
BoardSquare::from_coord(4, 0),
BoardSquare::from_coord(4, 1),
None,
),
ChessMove::quiet(
WhiteKing,
BoardSquare::from_coord(4, 0),
BoardSquare::from_coord(5, 1),
None,
),
ChessMove::quiet(
WhiteKing,
BoardSquare::from_coord(4, 0),
BoardSquare::from_coord(5, 0),
None,
),
ChessMove::castle(
WhiteKing,
BoardSquare::from_coord(4, 0),
BoardSquare::from_coord(6, 0),
WhiteRook,
BoardSquare::from_coord(7, 0),
BoardSquare::from_coord(5, 0),
),
],
vec![
ChessMove::capture(
WhiteBishop,
BoardSquare::from_coord(0, 6),
BoardSquare::from_coord(2, 4),
BlackRook,
None,
),
ChessMove::capture(
WhiteRook,
BoardSquare::from_coord(2, 0),
BoardSquare::from_coord(2, 4),
BlackRook,
None,
),
ChessMove::quiet(
WhitePawn,
BoardSquare::from_coord(7, 2),
BoardSquare::from_coord(7, 3),
None,
),
ChessMove::quiet(
WhitePawn,
BoardSquare::from_coord(3, 6),
BoardSquare::from_coord(3, 7),
Some(WhiteQueen),
),
ChessMove::quiet(
WhitePawn,
BoardSquare::from_coord(3, 6),
BoardSquare::from_coord(3, 7),
Some(WhiteRook),
),
ChessMove::quiet(
WhitePawn,
BoardSquare::from_coord(3, 6),
BoardSquare::from_coord(3, 7),
Some(WhiteBishop),
),
ChessMove::quiet(
WhitePawn,
BoardSquare::from_coord(3, 6),
BoardSquare::from_coord(3, 7),
Some(WhiteKnight),
),
ChessMove::quiet(
WhiteBishop,
BoardSquare::from_coord(0, 6),
BoardSquare::from_coord(1, 5),
None,
),
ChessMove::quiet(
WhiteBishop,
BoardSquare::from_coord(0, 6),
BoardSquare::from_coord(1, 7),
None,
),
ChessMove::quiet(
WhiteBishop,
BoardSquare::from_coord(6, 7),
BoardSquare::from_coord(7, 6),
None,
),
ChessMove::quiet(
WhiteBishop,
BoardSquare::from_coord(6, 7),
BoardSquare::from_coord(5, 6),
None,
),
ChessMove::quiet(
WhiteBishop,
BoardSquare::from_coord(6, 7),
BoardSquare::from_coord(4, 5),
None,
),
ChessMove::quiet(
WhiteBishop,
BoardSquare::from_coord(6, 7),
BoardSquare::from_coord(3, 4),
None,
),
ChessMove::quiet(
WhiteBishop,
BoardSquare::from_coord(6, 7),
BoardSquare::from_coord(2, 3),
None,
),
ChessMove::quiet(
WhiteBishop,
BoardSquare::from_coord(6, 7),
BoardSquare::from_coord(1, 2),
None,
),
ChessMove::quiet(
WhiteBishop,
BoardSquare::from_coord(6, 7),
BoardSquare::from_coord(0, 1),
None,
),
ChessMove::quiet(
WhiteRook,
BoardSquare::from_coord(2, 0),
BoardSquare::from_coord(0, 0),
None,
),
ChessMove::quiet(
WhiteRook,
BoardSquare::from_coord(2, 0),
BoardSquare::from_coord(1, 0),
None,
),
ChessMove::quiet(
WhiteRook,
BoardSquare::from_coord(2, 0),
BoardSquare::from_coord(3, 0),
None,
),
ChessMove::quiet(
WhiteRook,
BoardSquare::from_coord(2, 0),
BoardSquare::from_coord(4, 0),
None,
),
ChessMove::quiet(
WhiteRook,
BoardSquare::from_coord(2, 0),
BoardSquare::from_coord(5, 0),
None,
),
ChessMove::quiet(
WhiteRook,
BoardSquare::from_coord(2, 0),
BoardSquare::from_coord(6, 0),
None,
),
ChessMove::quiet(
WhiteRook,
BoardSquare::from_coord(2, 0),
BoardSquare::from_coord(7, 0),
None,
),
ChessMove::quiet(
WhiteRook,
BoardSquare::from_coord(2, 0),
BoardSquare::from_coord(2, 1),
None,
),
ChessMove::quiet(
WhiteRook,
BoardSquare::from_coord(2, 0),
BoardSquare::from_coord(2, 2),
None,
),
ChessMove::quiet(
WhiteRook,
BoardSquare::from_coord(2, 0),
BoardSquare::from_coord(2, 3),
None,
),
ChessMove::quiet(
WhiteKing,
BoardSquare::from_coord(7, 4),
BoardSquare::from_coord(6, 3),
None,
),
ChessMove::quiet(
WhiteKing,
BoardSquare::from_coord(7, 4),
BoardSquare::from_coord(7, 5),
None,
),
],
];
for case in 0..2 {
let mut generated_moves = get_available_moves(boards[case]);
generated_moves.sort();
expected_moves[case].sort();
assert_eq!(generated_moves.len(), expected_moves[case].len());
assert_eq!(generated_moves, expected_moves[case]);
}
}
#[test]
fn is_game_over_test() {
let boards: [&str; 4] = [
"2k5/3pn3/2pP4/1R1P3B/1Np5/3RPp2/1B6/6Kb w - - 0 1",
"2K3B1/4P3/8/7p/4pPn1/1N1P1p1p/4bp2/2Rk4 b - - 0 1",
"6N1/B2PP3/pR1b4/3P2nb/6P1/3P1k2/2p5/4r1K1 w - - 0 1",
"3n1K2/p2k1p2/5P2/b1p2P2/P7/8/3p2r1/8 w - - 0 1",
];
let expected_results: [Option<GameEnd>; 4] = [
None,
Some(GameEnd::WhiteWon("".to_string())),
Some(GameEnd::BlackWon("".to_string())),
Some(GameEnd::Draw("".to_string())),
];
for case in 0..4 {
let fen = boards[case];
let actual = is_game_over(fen);
assert_eq!(actual, expected_results[case]);
}
}
}

View File

@@ -1,6 +1,6 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)] #[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,
} };
} }
} }

1
link Normal file
View File

@@ -0,0 +1 @@
https://docs.google.com/presentation/d/16Niob9Z0Y8RPFdfZfuh8XyRbdUf83NaPepvQiLAnCIU/edit?usp=drivesdk

1256
server/Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -15,6 +15,8 @@ uuid = {version = "1.18.1", features = ["v4", "serde"] }
anyhow = "1.0.100" anyhow = "1.0.100"
rand = "0.9.2" rand = "0.9.2"
engine = {path = "../engine/"} engine = {path = "../engine/"}
log = {version = "0.4.28"}
env_logger = "0.11.8"
[[bin]] [[bin]]

View File

@@ -1,28 +1,39 @@
use engine::gameend::GameEnd;
use engine::{boardsquare::BoardSquare, chessmove::ChessMove, piecetype::PieceType};
use futures_util::{SinkExt, StreamExt}; use futures_util::{SinkExt, StreamExt};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::io::{self, Write}; use std::io::{self, Write};
use tokio_tungstenite::{connect_async, tungstenite::Message}; use tokio_tungstenite::{connect_async, tungstenite::Message};
use url::Url; use url::Url;
use uuid::Uuid;
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize)]
#[serde(tag = "type")] #[serde(tag = "type")]
enum ClientMessage { enum ClientMessage {
Join { username: String }, Join { username: String },
FindMatch, FindMatch,
Move { from: String, to: String }, Move { step: ChessMove, fen: String },
Resign, Resign,
Chat { text: String }, Chat { text: String },
RequestLegalMoves { fen: String },
} }
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize)]
struct ServerMessage { pub enum ServerMessage2 {
#[serde(rename = "type")] GameEnd {
message_type: String, winner: GameEnd,
player_id: Option<String>, },
match_id: Option<String>, UIUpdate {
opponent: Option<String>, fen: String,
color: Option<String>, },
reason: Option<String>, MatchFound {
match_id: Uuid,
color: String,
opponent_name: String,
},
Ok {
response: Result<(), String>,
},
} }
#[tokio::main] #[tokio::main]
@@ -60,15 +71,20 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("\nServer: {}", text); println!("\nServer: {}", text);
// Try to parse as structured message // Try to parse as structured message
if let Ok(parsed) = serde_json::from_str::<ServerMessage>(text) { if let Ok(parsed) = serde_json::from_str::<ServerMessage2>(text) {
match parsed.message_type.as_str() { match parsed {
"welcome" => { ServerMessage2::MatchFound {
if let Some(player_id) = parsed.player_id { match_id,
println!("Welcome! Your player ID: {}", player_id); color,
} opponent_name,
} => {
println!(
"opponent: {}, match_id: {}, color: {}",
opponent_name, match_id, color
);
} }
_ => { _ => {
println!("cucc: {:?}", parsed); println!("cucc");
} }
} }
} }
@@ -128,11 +144,20 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
} }
"move" => { "move" => {
if parts.len() >= 3 { if parts.len() >= 3 {
let from = parts[1].to_string(); //let from = parts[1].to_string();
let to = parts[2].to_string(); //let to = parts[2].to_string();
let message = ClientMessage::Move { from, to }; let fen = parts[1].to_string();
let step = ChessMove::quiet(
engine::piecetype::PieceType::WhiteBishop,
BoardSquare::new(),
BoardSquare { x: 1, y: 1 },
None,
);
let message = ClientMessage::Move { step, fen };
send_message(&mut write, &message).await?; send_message(&mut write, &message).await?;
println!("♟️ Sent move: {} -> {}", parts[1], parts[2]); //println!("♟️ Sent move: {} -> {}", parts[1], parts[2]);
} else { } else {
println!("Usage: move <from> <to> (e.g., move e2 e4)"); println!("Usage: move <from> <to> (e.g., move e2 e4)");
} }
@@ -154,6 +179,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
"help" => { "help" => {
print_help(); print_help();
} }
"requestmoves" => {
if parts.len() >= 2 {
let fen = parts[1..].join(" ");
let message = ClientMessage::RequestLegalMoves { fen };
send_message(&mut write, &message).await?;
}
}
_ => { _ => {
println!( println!(
"Unknown command: {}. Type 'help' for available commands.", "Unknown command: {}. Type 'help' for available commands.",
@@ -191,5 +223,6 @@ fn print_help() {
println!(" resign - Resign from current game"); println!(" resign - Resign from current game");
println!(" help - Show this help"); println!(" help - Show this help");
println!(" quit - Exit the client"); println!(" quit - Exit the client");
println!(" requestmoves - Request the legal moves");
println!(); println!();
} }

View File

@@ -1,6 +1,10 @@
use crate::connection::ClientEvent::*; use crate::connection::ClientEvent::*;
use engine::get_available_moves; use crate::matchmaking;
use engine::chessmove::ChessMove;
use engine::gameend::GameEnd::{self, *};
use engine::{get_available_moves, is_game_over};
use futures_util::{SinkExt, StreamExt}; use futures_util::{SinkExt, StreamExt};
use log::{error, info, warn};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::collections::{HashMap, VecDeque}; use std::collections::{HashMap, VecDeque};
use std::sync::Arc; use std::sync::Arc;
@@ -15,39 +19,68 @@ pub type ConnectionMap = Arc<Mutex<HashMap<Uuid, PlayerConnection>>>;
pub type MatchMap = Arc<Mutex<HashMap<Uuid, GameMatch>>>; pub type MatchMap = Arc<Mutex<HashMap<Uuid, GameMatch>>>;
pub type WaitingQueue = Arc<Mutex<VecDeque<Uuid>>>; pub type WaitingQueue = Arc<Mutex<VecDeque<Uuid>>>;
pub async fn clean_up_match(matches: &MatchMap, match_id: &Uuid) {
matches.lock().await.remove(&match_id);
}
// Helper functions to create new instances // Helper functions to create new instances
pub fn new_connection_map() -> ConnectionMap { pub fn new_connection_map() -> ConnectionMap {
warn!("Created new connection map");
Arc::new(Mutex::new(HashMap::new())) Arc::new(Mutex::new(HashMap::new()))
} }
pub fn new_match_map() -> MatchMap { pub fn new_match_map() -> MatchMap {
warn!("Created new match map");
Arc::new(Mutex::new(HashMap::new())) Arc::new(Mutex::new(HashMap::new()))
} }
pub fn new_waiting_queue() -> WaitingQueue { pub fn new_waiting_queue() -> WaitingQueue {
warn!("Created new waiting queue");
Arc::new(Mutex::new(VecDeque::new())) Arc::new(Mutex::new(VecDeque::new()))
} }
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize)]
pub struct Step { pub enum ServerMessage2 {
pub from: String, GameEnd {
pub to: String, winner: GameEnd,
},
UIUpdate {
fen: String,
turn_player: String,
move_history: Vec<String>,
},
MatchFound {
match_id: Uuid,
color: String,
opponent_name: String,
},
LegalMoves {
moves: Vec<ChessMove>,
},
Ok {
response: Result<(), String>,
},
} }
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize)]
#[serde(tag = "type")] #[serde(tag = "type")]
enum ClientEvent { enum ClientEvent {
Join { username: String }, Join {
username: String,
},
FindMatch, FindMatch,
Move { from: String, to: String }, Move {
step: ChessMove,
turn_player: String,
},
Resign, Resign,
Chat { text: String }, Chat {
RequestLegalMoves { fen: String }, text: String,
} },
RequestLegalMoves {
#[derive(Serialize, Deserialize, Debug)] fen: String,
pub struct EventResponse { },
pub response: Result<(), String>, CloseConnection,
} }
#[derive(Debug)] #[derive(Debug)]
@@ -68,19 +101,20 @@ pub struct GameMatch {
} }
// Message sending utilities // Message sending utilities
pub async fn send_message_to_player( pub async fn send_message_to_player_connection(
connections: &ConnectionMap, connection: Option<&mut PlayerConnection>,
player_id: Uuid,
message: &str, message: &str,
) -> Result<(), Box<dyn std::error::Error>> { ) -> Result<(), tokio_tungstenite::tungstenite::Error> {
let mut connections_lock = connections.lock().await; match connection {
if let Some(connection) = connections_lock.get_mut(&player_id) { Some(connection) => {
connection info!("sending message to: {}", connection.id);
.tx connection.tx.send(Message::Text(message.to_string())).await
.send(Message::Text(message.to_string())) }
.await?; None => {
error!("No connection provided");
Err(tokio_tungstenite::tungstenite::Error::ConnectionClosed)
}
} }
Ok(())
} }
pub async fn broadcast_to_all(connections: &ConnectionMap, message: &str) { pub async fn broadcast_to_all(connections: &ConnectionMap, message: &str) {
@@ -89,7 +123,7 @@ pub async fn broadcast_to_all(connections: &ConnectionMap, message: &str) {
for (id, connection) in connections_lock.iter_mut() { for (id, connection) in connections_lock.iter_mut() {
if let Err(e) = connection.tx.send(Message::Text(message.to_string())).await { if let Err(e) = connection.tx.send(Message::Text(message.to_string())).await {
eprintln!("Failed to send to {}: {}", id, e); error!("Failed to send to {}: {}", id, e);
dead_connections.push(*id); dead_connections.push(*id);
} }
} }
@@ -106,10 +140,19 @@ pub async fn broadcast_to_match(
match_id: Uuid, match_id: Uuid,
message: &str, message: &str,
) -> Result<(), Box<dyn std::error::Error>> { ) -> Result<(), Box<dyn std::error::Error>> {
info!("Broadcasting data to match: {}", &match_id);
let matches_lock = matches.lock().await; let matches_lock = matches.lock().await;
if let Some(game_match) = matches_lock.get(&match_id) { if let Some(game_match) = matches_lock.get(&match_id) {
send_message_to_player(connections, game_match.player_white, message).await?; send_message_to_player_connection(
send_message_to_player(connections, game_match.player_black, message).await?; connections.lock().await.get_mut(&game_match.player_white),
message,
)
.await?;
send_message_to_player_connection(
connections.lock().await.get_mut(&game_match.player_black),
message,
)
.await?;
} }
Ok(()) Ok(())
} }
@@ -125,6 +168,7 @@ pub async fn handle_connection(
let ws_stream = accept_async(stream).await?; let ws_stream = accept_async(stream).await?;
let (write, mut read) = ws_stream.split(); let (write, mut read) = ws_stream.split();
warn!("Accepted new connection");
let player_id = Uuid::new_v4(); let player_id = Uuid::new_v4();
@@ -142,45 +186,39 @@ pub async fn handle_connection(
); );
} }
println!("New connection: {}", player_id); info!("id: {}", &player_id);
// Send welcome message println!("\n\n\n");
let _ = send_message_to_player( println!(
&connections, "{:?}",
player_id, engine::get_available_moves("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1")
&format!(r#"{{"type": "welcome", "player_id": "{}"}}"#, player_id), );
) println!("\n\n\n");
.await;
// Message processing loop // Message processing loop
while let Some(Ok(message)) = read.next().await { while let Some(Ok(message)) = read.next().await {
if message.is_text() { if message.is_text() {
let text = message.to_text()?; let text = message.to_text()?;
println!("Received from {}: {}", player_id, text); info!("Received from {}: {}", player_id, text);
let client_data: ClientEvent = serde_json::from_str(text) let client_data: ClientEvent = serde_json::from_str(text)
.expect("Failed to convert data into json at handle_connection"); .expect("Failed to convert data into json at handle_connection");
println!("client: {:?}", client_data);
match client_data { match client_data {
Join { username } => { Join { username } => {
{ {
let mut conn_map = connections.lock().await; let mut conn_map = connections.lock().await;
let player = conn_map.get_mut(&player_id).unwrap(); let player = conn_map.get_mut(&player_id).unwrap();
player.username = Some(username); player.username = Some(username.clone());
info!("player: {}, set username: {}", &player_id, username);
} }
//respone to client //respone to client
let response: EventResponse = EventResponse { let response = ServerMessage2::Ok { response: Ok(()) };
response: core::result::Result::Ok(()),
};
println!("response: {:?}", response); let mut conn_map = connections.lock().await;
let _ = send_message_to_player_connection(
let _ = send_message_to_player( conn_map.get_mut(&player_id),
&connections,
player_id,
&serde_json::to_string(&response).unwrap(), &serde_json::to_string(&response).unwrap(),
) )
.await; .await;
@@ -188,28 +226,165 @@ pub async fn handle_connection(
FindMatch => { FindMatch => {
let mut wait_queue = waiting_queue.lock().await; let mut wait_queue = waiting_queue.lock().await;
wait_queue.push_back(player_id.clone()); wait_queue.push_back(player_id.clone());
println!("Appended {} to the waiting queue", player_id); info!("Appended {} to the waiting queue", player_id);
println!("queue {:?}", wait_queue); info!("queue {:?}", wait_queue);
} }
Move { from, to } => {} Move { step, turn_player } => {
RequestLegalMoves { fen } => { let match_id = connections
let moves = get_available_moves(&fen); .lock()
let _ = send_message_to_player( .await
.get(&player_id)
.unwrap()
.current_match
.unwrap();
println!("\n\nstep: {:?}\n", step);
{
info!("updating board state in match: {}", &match_id);
let mut matches = matches.lock().await;
matches.get_mut(&match_id).unwrap().board_state =
engine::get_board_after_move(
&matches.get(&match_id).unwrap().board_state,
&step,
);
info!(
"board after engine fn: {}",
matches.get_mut(&match_id).unwrap().board_state.clone()
);
matches
.get_mut(&match_id)
.unwrap()
.move_history
.push(step.clone().notation());
}
let message = ServerMessage2::UIUpdate {
fen: {
let mut matches = matches.lock().await;
matches.get(&match_id).unwrap().board_state.clone()
},
turn_player: turn_player,
move_history: {
let mut matches = matches.lock().await;
matches.get(&match_id).unwrap().move_history.clone()
},
};
let _ = broadcast_to_match(
&connections, &connections,
player_id, &matches,
&serde_json::to_string(&moves).unwrap(), match_id,
&serde_json::to_string(&message).unwrap(),
) )
.await; .await;
println!("Sent moves to player: {}", player_id);
{
let is_game_end = engine::is_game_over(
&matches.lock().await.get(&match_id).unwrap().board_state,
);
match is_game_end {
Some(res) => {
warn!("A player won the match: {}", &match_id);
let message = ServerMessage2::GameEnd { winner: res };
let _ = broadcast_to_match(
&connections,
&matches,
match_id,
&serde_json::to_string(&message).unwrap(),
)
.await;
clean_up_match(&matches, &match_id).await;
}
None => {
info!("No winner match continues. Id: {}", &match_id);
}
}
}
}
RequestLegalMoves { fen } => {
info!("Requesting legal moves player: {}", &player_id);
let moves = get_available_moves(&fen);
let message = ServerMessage2::LegalMoves { moves };
let _ = send_message_to_player_connection(
connections.lock().await.get_mut(&player_id),
&serde_json::to_string(&message).unwrap(),
)
.await;
info!("Sent moves to player: {}", player_id);
}
Resign => {
warn!("Resigned!");
let (fuck, fuck_id): (ServerMessage2, &Uuid) = {
let matches = matches.lock().await;
let curr_match = matches
.get(
&connections
.lock()
.await
.get(&player_id)
.unwrap()
.current_match
.unwrap(),
)
.unwrap();
if player_id == curr_match.player_white {
(
ServerMessage2::GameEnd {
winner: GameEnd::BlackWon("Resigned".to_string()),
},
&connections
.lock()
.await
.get(&player_id)
.unwrap()
.current_match
.unwrap(),
)
} else {
(
ServerMessage2::GameEnd {
winner: GameEnd::WhiteWon("Resigned".to_string()),
},
&connections
.lock()
.await
.get(&player_id)
.unwrap()
.current_match
.unwrap(),
)
}
};
let _ = broadcast_to_match(
&connections,
&matches,
fuck_id.clone(),
&serde_json::to_string(&fuck).unwrap(),
)
.await;
clean_up_match(&matches, fuck_id).await;
}
CloseConnection => {
warn!("Closing connection for: {}", &player_id);
break;
}
_ => {
warn!("Not known client event");
} }
_ => {}
} }
} }
} }
// Cleanup on disconnect // Cleanup on disconnect
cleanup_player(player_id, &connections, &matches, &waiting_queue).await; cleanup_player(player_id, &connections, &matches, &waiting_queue).await;
println!("Connection {} closed", player_id); warn!("Connection {} closed", player_id);
Ok(()) Ok(())
} }
@@ -226,7 +401,7 @@ async fn cleanup_player(
// Remove from connections // Remove from connections
connections.lock().await.remove(&player_id); connections.lock().await.remove(&player_id);
println!("Cleaned up player {}", player_id); warn!("Cleaned up player {}", player_id);
} }
#[cfg(test)] #[cfg(test)]
@@ -239,8 +414,24 @@ mod tests {
let connections = new_connection_map(); let connections = new_connection_map();
let player_id = Uuid::new_v4(); let player_id = Uuid::new_v4();
let result = send_message_to_player(&connections, player_id, "test message").await; // Test 1: Pass None directly (non-existent player)
assert!(result.is_ok(), "Should handle missing player gracefully"); let result = send_message_to_player_connection(None, "test message").await;
assert!(result.is_err(), "Should return error for None connection");
println!("Test passed: Handles None connection correctly");
// Test 2: Try to get non-existent player from map
let mut conn = connections.lock().await;
let non_existent_connection = conn.get_mut(&player_id); // This will be None
let result2 =
send_message_to_player_connection(non_existent_connection, "test message").await;
assert!(
result2.is_err(),
"Should return error for non-existent player"
);
println!("Test passed: Handles non-existent player in map correctly");
} }
#[tokio::test] #[tokio::test]

View File

@@ -1,13 +1,17 @@
mod connection; mod connection;
mod matchmaking; mod matchmaking;
mod messages; use env_logger::Env;
use log::{error, info};
use tokio::net::TcpListener; use tokio::net::TcpListener;
#[tokio::main] #[tokio::main]
async fn main() -> anyhow::Result<()> { async fn main() -> anyhow::Result<()> {
let env = Env::default().filter_or("MY_LOG_LEVEL", "INFO");
env_logger::init_from_env(env);
let address = "0.0.0.0:9001"; let address = "0.0.0.0:9001";
let listener = TcpListener::bind(address).await?; let listener = TcpListener::bind(address).await?;
println!("Server running on ws://{}", address); info!("Server running on ws://{}", address);
// Shared state initialization using the new helper functions // Shared state initialization using the new helper functions
let connections = connection::new_connection_map(); let connections = connection::new_connection_map();
@@ -34,7 +38,7 @@ async fn main() -> anyhow::Result<()> {
if let Err(e) = if let Err(e) =
connection::handle_connection(stream, connections, matches, waiting_queue).await connection::handle_connection(stream, connections, matches, waiting_queue).await
{ {
eprintln!("Connection error: {}", e); error!("Connection error: {}", e);
} }
}); });
} }

View File

@@ -1,4 +1,6 @@
use crate::connection::ServerMessage2;
use crate::connection::{ConnectionMap, GameMatch, MatchMap, WaitingQueue}; use crate::connection::{ConnectionMap, GameMatch, MatchMap, WaitingQueue};
use log::{error, info, warn};
use rand::random; use rand::random;
use uuid::Uuid; use uuid::Uuid;
@@ -20,21 +22,26 @@ impl MatchmakingSystem {
pub async fn run(&self) { pub async fn run(&self) {
loop { loop {
self.try_create_match().await; self.try_create_match().await;
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
} }
} }
async fn try_create_match(&self) { async fn try_create_match(&self) {
//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 {
let player1 = queue.pop_front().unwrap(); let player1 = queue.pop_front().unwrap();
let player2 = queue.pop_front().unwrap(); let player2 = queue.pop_front().unwrap();
info!("Creating new match. Players: {}, {}", &player1, &player2);
let match_id = Uuid::new_v4(); let match_id = Uuid::new_v4();
let (white_player, black_player) = if random::<bool>() { let (white_player, black_player) = if random::<bool>() {
info!("player1 is white, player2 is black");
(player1, player2) (player1, player2)
} else { } else {
info!("player2 is white, player1 is black");
(player2, player1) (player2, player1)
}; };
@@ -46,6 +53,8 @@ impl MatchmakingSystem {
move_history: Vec::new(), move_history: Vec::new(),
}; };
info!("Match id: {}", &game_match.id);
// Store the match // Store the match
self.matches.lock().await.insert(match_id, game_match); self.matches.lock().await.insert(match_id, game_match);
@@ -54,52 +63,69 @@ impl MatchmakingSystem {
let mut conn_map = self.connections.lock().await; let mut conn_map = self.connections.lock().await;
if let Some(player) = conn_map.get_mut(&white_player) { if let Some(player) = conn_map.get_mut(&white_player) {
player.current_match = Some(match_id); player.current_match = Some(match_id);
} else {
error!("Could not store match id for white player");
} }
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 {
error!("Could not store match id for black player");
} }
} }
// Notify players // Notify players
info!(
"Notifying player for a match: {:?} | {:?}",
white_player, black_player
);
self.notify_players(white_player, black_player, match_id) self.notify_players(white_player, black_player, match_id)
.await; .await;
} }
} }
async fn notify_players(&self, white: Uuid, black: Uuid, match_id: Uuid) { async fn notify_players(&self, white: Uuid, black: Uuid, match_id: Uuid) {
let conn_map = self.connections.lock().await; let mut conn_map = self.connections.lock().await;
// Get opponent names
let white_name = conn_map
.get(&black)
.and_then(|c| c.username.as_deref())
.unwrap_or("Opponent");
let black_name = conn_map
.get(&white)
.and_then(|c| c.username.as_deref())
.unwrap_or("Opponent");
// Notify white player // Notify white player
if let Some(_) = conn_map.get(&white) { if let Some(_) = conn_map.get(&white) {
let message = format!( let message = ServerMessage2::MatchFound {
r#"{{"type": "match_found", "match_id": "{}", "opponent": "{}", "color": "white"}}"#, match_id: match_id.clone(),
match_id, black_name color: String::from("white"),
); opponent_name: conn_map
let _ = .get(&white)
crate::connection::send_message_to_player(&self.connections, white, &message).await; .and_then(|c| c.username.as_deref())
.unwrap_or("Opponent")
.to_string(),
};
let _ = crate::connection::send_message_to_player_connection(
conn_map.get_mut(&white),
&serde_json::to_string(&message).unwrap(),
)
.await;
} }
// Notify black player // Notify black player
if let Some(_) = conn_map.get(&black) { if let Some(_) = conn_map.get(&black) {
let message = format!( let message = ServerMessage2::MatchFound {
r#"{{"type": "match_found", "match_id": "{}", "opponent": "{}", "color": "black"}}"#, match_id: match_id.clone(),
match_id, white_name color: String::from("black"),
); opponent_name: conn_map
let _ = .get(&black)
crate::connection::send_message_to_player(&self.connections, black, &message).await; .and_then(|c| c.username.as_deref())
.unwrap_or("Opponent")
.to_string(),
};
let _ = crate::connection::send_message_to_player_connection(
conn_map.get_mut(&black),
&serde_json::to_string(&message).unwrap(),
)
.await;
} }
println!("Match created: {} (white) vs {} (black)", white, black); info!("Match created: {} (white) vs {} (black)", white, black);
} }
} }

View File

@@ -1,36 +0,0 @@
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
#[serde(tag = "type")]
pub enum ServerMessage {
Welcome {
player_id: String,
},
MatchFound {
match_id: String,
opponent: String,
color: String,
},
GameStart {
fen: String,
white_time: u32,
black_time: u32,
},
MoveResult {
valid: bool,
from: String,
to: String,
new_fen: String,
},
OpponentMove {
from: String,
to: String,
},
GameEnd {
result: String,
reason: String,
},
Error {
reason: String,
},
}

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