added clone to engine structs, added private session launch with starting server from ui

This commit is contained in:
2025-11-29 18:55:10 +01:00
parent a0bca32733
commit bc03cead82
4 changed files with 170 additions and 61 deletions

View File

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

View File

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

View File

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

View File

@@ -4,6 +4,9 @@ use env_logger::Env;
use futures_util::{SinkExt, StreamExt}; use futures_util::{SinkExt, StreamExt};
use log::{error, info, warn}; use log::{error, info, warn};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::os::unix::process::CommandExt;
use std::path::Path;
use std::process::Command;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use tokio::sync::mpsc; use tokio::sync::mpsc;
use tokio_tungstenite::{connect_async, tungstenite::Message}; use tokio_tungstenite::{connect_async, tungstenite::Message};
@@ -82,6 +85,7 @@ struct GameState {
opponent_name: Option<String>, opponent_name: Option<String>,
match_id: Option<Uuid>, match_id: Option<Uuid>,
game_over: Option<String>, game_over: Option<String>,
available_moves: Option<Vec<ChessMove>>,
} }
impl Default for GameState { impl Default for GameState {
@@ -92,6 +96,7 @@ impl Default for GameState {
opponent_name: None, opponent_name: None,
match_id: None, match_id: None,
game_over: None, game_over: None,
available_moves: None,
} }
} }
} }
@@ -99,6 +104,7 @@ impl Default for GameState {
// UI state // UI state
enum AppState { enum AppState {
MainMenu, MainMenu,
PrivatePlayConnect,
Connecting, Connecting,
FindingMatch, FindingMatch,
InGame, InGame,
@@ -110,7 +116,8 @@ struct ChessApp {
game_state: Arc<Mutex<GameState>>, game_state: Arc<Mutex<GameState>>,
server_port: String, server_port: String,
username: String, username: String,
server_ip: String,
start_local_server_instance: bool,
// Channels for communication with network tasks // Channels for communication with network tasks
tx_to_network: Option<mpsc::UnboundedSender<ClientEvent>>, tx_to_network: Option<mpsc::UnboundedSender<ClientEvent>>,
rx_from_network: Option<mpsc::UnboundedReceiver<ServerMessage2>>, rx_from_network: Option<mpsc::UnboundedReceiver<ServerMessage2>>,
@@ -129,6 +136,9 @@ impl Default for ChessApp {
tx_to_network: None, tx_to_network: None,
rx_from_network: None, rx_from_network: None,
selected_square: None, selected_square: None,
server_ip: "127.0.0.1".to_string(), // TODO: change to dns when we figure out hosting
// for the online server (reverse proxy?)
start_local_server_instance: false,
} }
} }
} }
@@ -138,6 +148,7 @@ impl ChessApp {
let server_port = self.server_port.clone(); let server_port = self.server_port.clone();
let username = self.username.clone(); let username = self.username.clone();
let game_state = self.game_state.clone(); let game_state = self.game_state.clone();
let server_address = self.server_ip.clone();
// Create channels for communication // Create channels for communication
let (tx_to_network, rx_from_ui) = mpsc::unbounded_channel(); let (tx_to_network, rx_from_ui) = mpsc::unbounded_channel();
@@ -150,8 +161,15 @@ impl ChessApp {
// Spawn network connection task // Spawn network connection task
tokio::spawn(async move { tokio::spawn(async move {
if let Err(e) = if let Err(e) = Self::network_handler(
Self::network_handler(server_port, username, rx_from_ui, tx_to_ui, game_state).await server_port,
server_address,
username,
rx_from_ui,
tx_to_ui,
game_state,
)
.await
{ {
error!("Network handler error: {}", e); error!("Network handler error: {}", e);
} }
@@ -160,13 +178,14 @@ impl ChessApp {
async fn network_handler( async fn network_handler(
server_port: String, server_port: String,
server_ip: String,
username: String, username: String,
mut rx_from_ui: mpsc::UnboundedReceiver<ClientEvent>, mut rx_from_ui: mpsc::UnboundedReceiver<ClientEvent>,
tx_to_ui: mpsc::UnboundedSender<ServerMessage2>, tx_to_ui: mpsc::UnboundedSender<ServerMessage2>,
game_state: Arc<Mutex<GameState>>, game_state: Arc<Mutex<GameState>>,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
// Build WebSocket URL // Build WebSocket URL
let server_address = format!("ws://127.0.0.1:{}", server_port); let server_address = format!("ws://{}:{}", server_ip, server_port);
let url = Url::parse(&server_address)?; let url = Url::parse(&server_address)?;
info!("Connecting to: {}", server_address); info!("Connecting to: {}", server_address);
@@ -366,17 +385,17 @@ impl eframe::App for ChessApp {
ui.text_edit_singleline(&mut self.username); ui.text_edit_singleline(&mut self.username);
}); });
ui.horizontal(|ui| {
ui.label("Server Port:");
ui.text_edit_singleline(&mut self.server_port);
});
ui.add_space(20.0); ui.add_space(20.0);
if ui.button("Connect & Play").clicked() { if ui.button("Online Play").clicked() {
self.server_ip = "random.dns.com".to_string();
self.connect_to_server(); self.connect_to_server();
} }
if ui.button("Private Play").clicked() {
self.state = AppState::PrivatePlayConnect;
}
if ui.button("Quit").clicked() { if ui.button("Quit").clicked() {
std::process::exit(0); std::process::exit(0);
} }
@@ -384,6 +403,47 @@ impl eframe::App for ChessApp {
}); });
} }
AppState::PrivatePlayConnect => {
egui::CentralPanel::default().show(ctx, |ui| {
ui.vertical_centered(|ui| {
ui.horizontal(|ui| {
ui.label("Server ip address");
ui.text_edit_singleline(&mut self.server_ip);
});
ui.horizontal(|ui| {
ui.label("Server Port:");
ui.text_edit_singleline(&mut self.server_port);
});
ui.horizontal(|ui| {
ui.checkbox(&mut self.start_local_server_instance, "Host Server");
});
ui.add_space(20.0);
if ui.button("Play").clicked() {
if self.start_local_server_instance == true {
// TODO: Spawn server instance here
let path = if cfg!(windows) {
"./server.exe"
} else {
"./server"
};
if !Path::new(path).exists() {
error!("Server binary does not exist, cfg: {}", path);
} else {
let _ = Command::new(path).spawn();
std::thread::sleep(std::time::Duration::from_secs(1));
}
}
self.connect_to_server();
}
})
});
}
AppState::Connecting => { AppState::Connecting => {
egui::CentralPanel::default().show(ctx, |ui| { egui::CentralPanel::default().show(ctx, |ui| {
// TODO: go back to menu btn // TODO: go back to menu btn
@@ -399,6 +459,7 @@ impl eframe::App for ChessApp {
egui::CentralPanel::default().show(ctx, |ui| { egui::CentralPanel::default().show(ctx, |ui| {
// TODO: go back to menu btn // TODO: go back to menu btn
// TODO: how do we delete the player from the waiting queue // TODO: how do we delete the player from the waiting queue
// FIX: disconnect the player from the server which will clean up connection
ui.vertical_centered(|ui| { ui.vertical_centered(|ui| {
ui.heading("Finding Match..."); ui.heading("Finding Match...");
ui.add_space(20.0); ui.add_space(20.0);