Compare commits
12 Commits
UI/RotateB
...
Engine/mak
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fe8f8621d7 | ||
|
|
767e7d14fd | ||
|
|
074f181791 | ||
|
|
542dd39aa6 | ||
|
|
6db4ae6d07 | ||
|
|
171a7b8020 | ||
|
|
205e8811d5 | ||
|
|
2394da84ce | ||
|
|
e7c7743682 | ||
|
|
2375f28ee3 | ||
|
|
5b6318442e | ||
|
|
24ddc74573 |
@@ -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;
|
||||
@@ -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(¬ation_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;
|
||||
}
|
||||
}
|
||||
38
engine/src/bitboard/makemove.rs
Normal file
38
engine/src/bitboard/makemove.rs
Normal 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;
|
||||
}
|
||||
}
|
||||
82
engine/src/bitboard/makemove/captures.rs
Normal file
82
engine/src/bitboard/makemove/captures.rs
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
35
engine/src/bitboard/makemove/castles.rs
Normal file
35
engine/src/bitboard/makemove/castles.rs
Normal 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);
|
||||
}
|
||||
}
|
||||
61
engine/src/bitboard/makemove/quiets.rs
Normal file
61
engine/src/bitboard/makemove/quiets.rs
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)]
|
||||
|
||||
1
server/Cargo.lock
generated
1
server/Cargo.lock
generated
@@ -768,7 +768,6 @@ dependencies = [
|
||||
"env_logger",
|
||||
"futures-util",
|
||||
"log",
|
||||
"futures-util",
|
||||
"rand 0.9.2",
|
||||
"serde",
|
||||
"serde_json",
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -1,96 +0,0 @@
|
||||
use engine::{chessmove::ChessMove, gameend::GameEnd};
|
||||
use futures_util::StreamExt;
|
||||
use local_ip_address::local_ip;
|
||||
use log::{error, info, warn};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
error::Error,
|
||||
net::{IpAddr, Ipv4Addr},
|
||||
};
|
||||
use tokio_tungstenite::connect_async;
|
||||
use url::Url;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[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) -> 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();
|
||||
|
||||
let read_handle = 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,
|
||||
} => {}
|
||||
ServerMessage2::Ok { response } => {}
|
||||
_ => {
|
||||
error!("Received unkown servermessage2");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Error receiving message: {}", e);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Ok(())
|
||||
}
|
||||
342
ui/src/main.rs
342
ui/src/main.rs
@@ -1,42 +1,31 @@
|
||||
use eframe::egui;
|
||||
use env_logger::Env;
|
||||
use log::{error, info, warn};
|
||||
|
||||
use crate::connection::handle_connection;
|
||||
mod connection;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<(), eframe::Error> {
|
||||
//set up for logging
|
||||
let env = Env::default().filter_or("MY_LOG_LEVEL", "INFO");
|
||||
env_logger::init_from_env(env);
|
||||
warn!("Initialized logger");
|
||||
|
||||
let options = eframe::NativeOptions {
|
||||
fn main() -> eframe::Result<()> {
|
||||
let options = eframe::NativeOptions{
|
||||
viewport: egui::ViewportBuilder::default()
|
||||
.with_fullscreen(false)
|
||||
.with_fullscreen(true)
|
||||
.with_min_inner_size(egui::vec2(800.0, 600.0)) // Minimum width, height
|
||||
.with_inner_size(egui::vec2(7680.0, 4320.0)), // Initial size
|
||||
..Default::default()
|
||||
};
|
||||
eframe::run_native(
|
||||
"Knightly",
|
||||
options,
|
||||
Box::new(|cc| {
|
||||
let mut fonts = egui::FontDefinitions::default();
|
||||
fonts.font_data.insert(
|
||||
"symbols".to_owned(),
|
||||
egui::FontData::from_static(include_bytes!("../fonts/DejaVuSans.ttf")).into(),
|
||||
);
|
||||
fonts
|
||||
.families
|
||||
.entry(egui::FontFamily::Proportional)
|
||||
.or_default()
|
||||
.insert(0, "symbols".to_owned());
|
||||
cc.egui_ctx.set_fonts(fonts);
|
||||
Ok(Box::new(ChessApp::default()))
|
||||
}),
|
||||
)
|
||||
"Knightly",
|
||||
options,
|
||||
Box::new(|cc| {
|
||||
let mut fonts = egui::FontDefinitions::default();
|
||||
fonts.font_data.insert(
|
||||
"symbols".to_owned(),
|
||||
egui::FontData::from_static(include_bytes!("../fonts/DejaVuSans.ttf")).into(),
|
||||
);
|
||||
fonts
|
||||
.families
|
||||
.entry(egui::FontFamily::Proportional)
|
||||
.or_default()
|
||||
.insert(0, "symbols".to_owned());
|
||||
cc.egui_ctx.set_fonts(fonts);
|
||||
Ok(Box::new(ChessApp::default()))
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Debug)]
|
||||
@@ -53,12 +42,12 @@ enum Piece {
|
||||
impl Piece {
|
||||
fn symbol(&self) -> &'static str {
|
||||
match self {
|
||||
Piece::King('w') => "♚",
|
||||
Piece::Queen('w') => "♛",
|
||||
Piece::Rook('w') => "♜",
|
||||
Piece::Bishop('w') => "♝",
|
||||
Piece::Knight('w') => "♞",
|
||||
Piece::Pawn('w') => "♟︎",
|
||||
Piece::King('w') => "♔",
|
||||
Piece::Queen('w') => "♕",
|
||||
Piece::Rook('w') => "♖",
|
||||
Piece::Bishop('w') => "♗",
|
||||
Piece::Knight('w') => "♘",
|
||||
Piece::Pawn('w') => "♙",
|
||||
Piece::King('b') => "♚",
|
||||
Piece::Queen('b') => "♛",
|
||||
Piece::Rook('b') => "♜",
|
||||
@@ -120,7 +109,7 @@ impl Default for ChessApp {
|
||||
selected: None,
|
||||
turn: Turn::White,
|
||||
pending_settings: PendingSettings::default(),
|
||||
server_port: "9001".to_string(), // Default port
|
||||
server_port: "8080".to_string(), // Default port
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -180,14 +169,13 @@ impl ChessApp {
|
||||
self.fullscreen = self.pending_settings.fullscreen;
|
||||
self.selected_resolution = self.pending_settings.selected_resolution;
|
||||
self.server_port = self.pending_settings.server_port.clone();
|
||||
|
||||
|
||||
if let Some(resolution) = self.resolutions.get(self.selected_resolution) {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::InnerSize(egui::Vec2::new(
|
||||
resolution.0 as f32,
|
||||
resolution.1 as f32,
|
||||
)));
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::InnerSize(
|
||||
egui::Vec2::new(resolution.0 as f32, resolution.1 as f32)
|
||||
));
|
||||
}
|
||||
|
||||
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Fullscreen(self.fullscreen));
|
||||
}
|
||||
|
||||
@@ -208,31 +196,16 @@ impl eframe::App for ChessApp {
|
||||
ui.heading("♞ Knightly ♞");
|
||||
ui.add_space(30.0);
|
||||
|
||||
if ui
|
||||
.add_sized([300.0, 60.0], egui::Button::new("Play"))
|
||||
.clicked()
|
||||
{
|
||||
let port = self.server_port.clone();
|
||||
info!("\nstarting connection\n");
|
||||
|
||||
//create a TCPlistener with tokio and bind machine ip for connection
|
||||
tokio::spawn(async move {
|
||||
info!("tokoi");
|
||||
handle_connection(&port).await
|
||||
});
|
||||
|
||||
if ui.add_sized([300.0, 60.0], egui::Button::new("Play")).clicked() {
|
||||
self.state = AppState::InGame;
|
||||
}
|
||||
ui.add_space(8.0);
|
||||
|
||||
if ui
|
||||
.add_sized([300.0, 60.0], egui::Button::new("Settings"))
|
||||
.clicked()
|
||||
{
|
||||
|
||||
if ui.add_sized([300.0, 60.0], egui::Button::new("Settings")).clicked() {
|
||||
self.enter_settings();
|
||||
}
|
||||
ui.add_space(8.0);
|
||||
|
||||
|
||||
if ui
|
||||
.add_sized([300.0, 60.0], egui::Button::new("Quit"))
|
||||
.clicked()
|
||||
@@ -252,10 +225,7 @@ impl eframe::App for ChessApp {
|
||||
// Fullscreen toggle
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Fullscreen:");
|
||||
if ui
|
||||
.checkbox(&mut self.pending_settings.fullscreen, "")
|
||||
.changed()
|
||||
{
|
||||
if ui.checkbox(&mut self.pending_settings.fullscreen, "").changed() {
|
||||
// If enabling fullscreen, we might want to disable resolution selection
|
||||
}
|
||||
});
|
||||
@@ -271,8 +241,7 @@ impl eframe::App for ChessApp {
|
||||
self.resolutions[self.pending_settings.selected_resolution].1
|
||||
))
|
||||
.show_ui(ui, |ui| {
|
||||
for (i, &(width, height)) in self.resolutions.iter().enumerate()
|
||||
{
|
||||
for (i, &(width, height)) in self.resolutions.iter().enumerate() {
|
||||
ui.selectable_value(
|
||||
&mut self.pending_settings.selected_resolution,
|
||||
i,
|
||||
@@ -286,28 +255,20 @@ impl eframe::App for ChessApp {
|
||||
// Server port input field
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Local Server Port:");
|
||||
ui.add(
|
||||
egui::TextEdit::singleline(&mut self.pending_settings.server_port)
|
||||
.desired_width(100.0)
|
||||
.hint_text("9001"),
|
||||
);
|
||||
ui.add(egui::TextEdit::singleline(&mut self.pending_settings.server_port)
|
||||
.desired_width(100.0)
|
||||
.hint_text("8080"));
|
||||
});
|
||||
ui.add_space(30.0);
|
||||
|
||||
// Apply and Cancel buttons
|
||||
ui.horizontal(|ui| {
|
||||
if ui
|
||||
.add_sized([140.0, 40.0], egui::Button::new("Apply"))
|
||||
.clicked()
|
||||
{
|
||||
if ui.add_sized([140.0, 40.0], egui::Button::new("Apply")).clicked() {
|
||||
self.apply_settings(ctx);
|
||||
self.state = AppState::MainMenu;
|
||||
}
|
||||
|
||||
if ui
|
||||
.add_sized([140.0, 40.0], egui::Button::new("Cancel"))
|
||||
.clicked()
|
||||
{
|
||||
|
||||
if ui.add_sized([140.0, 40.0], egui::Button::new("Cancel")).clicked() {
|
||||
self.state = AppState::MainMenu;
|
||||
}
|
||||
});
|
||||
@@ -332,164 +293,81 @@ impl eframe::App for ChessApp {
|
||||
ui.label(format!("Turn: {:?}", self.turn));
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
egui::CentralPanel::default().show(ctx, |ui| {
|
||||
ui.vertical_centered(|ui| {
|
||||
let full_avail = ui.available_rect_before_wrap();
|
||||
let board_tile = (full_avail.width().min(full_avail.height())) / 8.0;
|
||||
let board_size = board_tile * 8.0;
|
||||
|
||||
|
||||
// Create a child UI at the board position
|
||||
let (response, painter) = ui.allocate_painter(
|
||||
egui::Vec2::new(board_size, board_size),
|
||||
egui::Sense::click(),
|
||||
egui::Sense::click()
|
||||
);
|
||||
|
||||
|
||||
let board_rect = egui::Rect::from_center_size(
|
||||
full_avail.center(),
|
||||
egui::vec2(board_size, board_size),
|
||||
egui::vec2(board_size, board_size)
|
||||
);
|
||||
|
||||
// Draw the chess board
|
||||
let player = "black";
|
||||
if player =="white"{
|
||||
let tile_size = board_size / 8.0;
|
||||
for row in 0..8 {
|
||||
for col in 0..8 {
|
||||
let color = if (row + col) % 2 == 0 {
|
||||
egui::Color32::from_rgb(217, 217, 217)
|
||||
} else {
|
||||
egui::Color32::from_rgb(100, 97, 97)
|
||||
};
|
||||
|
||||
let rect = egui::Rect::from_min_size(
|
||||
egui::Pos2::new(
|
||||
board_rect.min.x + col as f32 * tile_size,
|
||||
board_rect.min.y + row as f32 * tile_size,
|
||||
),
|
||||
egui::Vec2::new(tile_size, tile_size),
|
||||
);
|
||||
|
||||
painter.rect_filled(rect, 0.0, color);
|
||||
|
||||
// Draw piece
|
||||
let piece = self.board[row][col];
|
||||
if piece != Piece::Empty {
|
||||
let symbol = piece.symbol();
|
||||
let font_id = egui::FontId::proportional(tile_size * 0.75);
|
||||
painter.text(
|
||||
rect.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
symbol,
|
||||
font_id,
|
||||
if matches!(
|
||||
piece,
|
||||
Piece::King('w')
|
||||
| Piece::Queen('w')
|
||||
| Piece::Rook('w')
|
||||
| Piece::Bishop('w')
|
||||
| Piece::Knight('w')
|
||||
| Piece::Pawn('w')
|
||||
) {
|
||||
egui::Color32::WHITE
|
||||
} else {
|
||||
egui::Color32::BLACK
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// Draw selection highlight
|
||||
if self.selected == Some((row, col)) {
|
||||
painter.rect_stroke(
|
||||
rect,
|
||||
0.0,
|
||||
egui::Stroke::new(3.0, egui::Color32::RED),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
}
|
||||
|
||||
// Handle clicks
|
||||
if ui.ctx().input(|i| i.pointer.primary_clicked()) {
|
||||
let click_pos =
|
||||
ui.ctx().input(|i| i.pointer.interact_pos()).unwrap();
|
||||
if rect.contains(click_pos) {
|
||||
self.handle_click(row, col);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if player=="black"{
|
||||
{
|
||||
let tile_size = board_size / 8.0;
|
||||
for row in 0..8 {
|
||||
for col in 0..8 {
|
||||
let color = if (row + col) % 2 == 0 {
|
||||
egui::Color32::from_rgb(217, 217, 217)
|
||||
} else {
|
||||
egui::Color32::from_rgb(100, 97, 97)
|
||||
};
|
||||
|
||||
let rect = egui::Rect::from_min_size(
|
||||
egui::Pos2::new(
|
||||
board_rect.min.x + col as f32 * tile_size,
|
||||
board_rect.min.y + row as f32 * tile_size,
|
||||
),
|
||||
egui::Vec2::new(tile_size, tile_size),
|
||||
);
|
||||
|
||||
painter.rect_filled(rect, 0.0, color);
|
||||
|
||||
// Draw piece
|
||||
let piece = self.board[row][col];
|
||||
if piece != Piece::Empty {
|
||||
let symbol = piece.symbol();
|
||||
let font_id = egui::FontId::proportional(tile_size * 0.75);
|
||||
painter.text(
|
||||
rect.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
symbol,
|
||||
font_id,
|
||||
if matches!(
|
||||
piece,
|
||||
Piece::King('w')
|
||||
| Piece::Queen('w')
|
||||
| Piece::Rook('w')
|
||||
| Piece::Bishop('w')
|
||||
| Piece::Knight('w')
|
||||
| Piece::Pawn('w')
|
||||
) {
|
||||
egui::Color32::BLACK
|
||||
} else {
|
||||
egui::Color32::WHITE
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// Draw selection highlight
|
||||
if self.selected == Some((row, col)) {
|
||||
painter.rect_stroke(
|
||||
rect,
|
||||
0.0,
|
||||
egui::Stroke::new(3.0, egui::Color32::RED),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
}
|
||||
|
||||
// Handle clicks
|
||||
if ui.ctx().input(|i| i.pointer.primary_clicked()) {
|
||||
let click_pos =
|
||||
ui.ctx().input(|i| i.pointer.interact_pos()).unwrap();
|
||||
if rect.contains(click_pos) {
|
||||
self.handle_click(row, col);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Draw the chess board
|
||||
let tile_size = board_size / 8.0;
|
||||
for row in 0..8 {
|
||||
for col in 0..8 {
|
||||
let color = if (row + col) % 2 == 0 {
|
||||
egui::Color32::from_rgb(100, 97, 97)
|
||||
} else {
|
||||
egui::Color32::from_rgb(217, 217, 217)
|
||||
};
|
||||
|
||||
let rect = egui::Rect::from_min_size(
|
||||
egui::Pos2::new(
|
||||
board_rect.min.x + col as f32 * tile_size,
|
||||
board_rect.min.y + row as f32 * tile_size
|
||||
),
|
||||
egui::Vec2::new(tile_size, tile_size)
|
||||
);
|
||||
|
||||
painter.rect_filled(rect, 0.0, color);
|
||||
|
||||
// Draw piece
|
||||
let piece = self.board[row][col];
|
||||
if piece != Piece::Empty {
|
||||
let symbol = piece.symbol();
|
||||
let font_id = egui::FontId::proportional(tile_size * 0.75);
|
||||
painter.text(
|
||||
rect.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
symbol,
|
||||
font_id,
|
||||
if matches!(piece, Piece::King('w') | Piece::Queen('w') | Piece::Rook('w') | Piece::Bishop('w') | Piece::Knight('w') | Piece::Pawn('w')) {
|
||||
egui::Color32::WHITE
|
||||
} else {
|
||||
egui::Color32::BLACK
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
// Draw selection highlight
|
||||
if self.selected == Some((row, col)) {
|
||||
painter.rect_stroke(
|
||||
rect,
|
||||
0.0,
|
||||
egui::Stroke::new(3.0, egui::Color32::RED),
|
||||
egui::StrokeKind::Inside
|
||||
);
|
||||
}
|
||||
|
||||
// Handle clicks
|
||||
if ui.ctx().input(|i| i.pointer.primary_clicked()) {
|
||||
let click_pos = ui.ctx().input(|i| i.pointer.interact_pos()).unwrap();
|
||||
if rect.contains(click_pos) {
|
||||
self.handle_click(row, col);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -509,14 +387,14 @@ mod tests {
|
||||
assert!(matches!(app.board[1][0], Piece::Pawn('b')));
|
||||
assert!(matches!(app.board[6][0], Piece::Pawn('w')));
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn test_piece_symbols() {
|
||||
assert_eq!(Piece::King('w').symbol(), "♔");
|
||||
assert_eq!(Piece::King('b').symbol(), "♚");
|
||||
assert_eq!(Piece::Empty.symbol(), "");
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn test_piece_selection() {
|
||||
let mut app = ChessApp::default();
|
||||
@@ -525,7 +403,7 @@ mod tests {
|
||||
app.handle_click(6, 0);
|
||||
assert_eq!(app.selected, None);
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn test_piece_movement() {
|
||||
let mut app = ChessApp::default();
|
||||
@@ -544,7 +422,7 @@ mod tests {
|
||||
app.handle_click(5, 0); // White moves
|
||||
assert_eq!(app.turn, Turn::Black); // Should now be Black's turn
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn test_server_port_default() {
|
||||
let app = ChessApp::default();
|
||||
|
||||
Reference in New Issue
Block a user