Compare commits

..

12 Commits

Author SHA1 Message Date
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
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
18 changed files with 703 additions and 1497 deletions

View File

@@ -7,4 +7,5 @@ mod movegen;
pub mod board;
pub(in super) mod bitmove;
pub(in super) mod movebuffer;
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;
pub struct Board {
@@ -12,6 +14,7 @@ pub struct Board {
}
impl Board {
pub const EMPTY_SQUARE: u8 = 12;
pub fn new_clear() -> 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() };
}
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) {
self.occupancy = [0u64; 3];
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};
#[derive(Serialize, Deserialize, Debug, Clone)]
#[derive(Serialize, Deserialize, Debug)]
pub struct BoardSquare {
pub x: usize,
pub y: usize,
@@ -28,10 +28,10 @@ impl BoardSquare {
return Self { x: x, y: y };
}
pub(super) fn from_index(idx: u8) -> Self {
pub(in super) fn from_index(idx: u8) -> Self {
let file = idx % 8;
let rank = idx / 8;
#[cfg(debug_assertions)]
{
if !(0..8).contains(&rank) {
@@ -39,12 +39,10 @@ impl BoardSquare {
}
}
return Self {
x: file as usize,
y: rank as usize,
};
return Self {x: file as usize, y: rank as usize};
}
pub(super) fn to_index(&self) -> u8 {
pub(in super) fn to_index(&self) -> u8 {
return (8 * self.y + self.x) as u8;
}
}

View File

@@ -1,13 +1,10 @@
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, Clone)]
#[derive(Serialize, Deserialize, Debug)]
/*pub struct ChessMove {
pub move_type: MoveType,
pub piece_type: PieceType,
@@ -22,14 +19,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,
@@ -37,15 +34,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 {
@@ -59,7 +56,7 @@ impl ChessMove {
piece_type,
from_square,
to_square,
promotion_piece,
promotion_piece
};
}
@@ -75,7 +72,7 @@ impl ChessMove {
from_square,
to_square,
captured_piece,
promotion_piece,
promotion_piece
};
}
@@ -93,11 +90,11 @@ impl ChessMove {
king_to,
rook_type,
rook_from,
rook_to,
rook_to
};
}
pub(super) fn from_bitmove(bitmove: &BitMove, board: &Board) -> Self {
pub(in super) fn from_bitmove(bitmove: &BitMove, board: &Board) -> Self {
match bitmove.move_type() {
BitMoveType::Quiet => {
let from_square_index = bitmove.from_square();
@@ -106,16 +103,11 @@ 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();
@@ -125,28 +117,18 @@ 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 {
@@ -160,72 +142,44 @@ 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(super) fn to_bitmove(&self) -> BitMove {
pub(in 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

@@ -43,8 +43,13 @@ pub fn is_game_over(fen: &str) -> Option<GameEnd> {
}
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");
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)]

View File

@@ -1,6 +1,6 @@
use serde::{Deserialize, Serialize};
#[derive(Clone, Serialize, Deserialize, Debug)]
#[derive(Serialize, Deserialize, Debug)]
pub enum PieceType {
WhitePawn,
WhiteKnight,
@@ -17,7 +17,8 @@ pub enum PieceType {
}
impl PieceType {
pub(super) fn from_index(idx: u8) -> Self {
pub(in super) fn from_index(idx: u8) -> Self {
return match idx {
0 => PieceType::WhitePawn,
1 => PieceType::WhiteKnight,
@@ -31,10 +32,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(super) fn to_index(&self) -> u8 {
pub(in super) fn to_index(&self) -> u8 {
return match self {
&PieceType::WhitePawn => 0,
&PieceType::WhiteKnight => 1,
@@ -47,8 +48,7 @@ impl PieceType {
&PieceType::BlackBishop => 8,
&PieceType::BlackRook => 9,
&PieceType::BlackQueen => 10,
&PieceType::BlackKing => 11,
};
&PieceType::BlackKing => 11
}
}
}
}

1
server/Cargo.lock generated
View File

@@ -768,7 +768,6 @@ dependencies = [
"env_logger",
"futures-util",
"log",
"futures-util",
"rand 0.9.2",
"serde",
"serde_json",

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,117 +0,0 @@
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