Compare commits
102 Commits
Server/web
...
Server/eve
| Author | SHA1 | Date | |
|---|---|---|---|
| 5ccca3ab8e | |||
| 622bef963f | |||
| 6fc1b6c3fd | |||
| a985182c99 | |||
| 3b78a8e925 | |||
| ab369f179c | |||
| be6a86bebf | |||
| 5336aadf97 | |||
|
|
0ace485bb6 | ||
|
|
1c1b9a96d9 | ||
|
|
e99b2defa3 | ||
|
|
f39c113ef9 | ||
|
|
f417a7e47c | ||
|
|
547b0e51cb | ||
|
|
5340744abe | ||
|
|
f64ebfa47f | ||
|
|
4e7ac2a195 | ||
|
|
dc176c103b | ||
|
|
85a7fa37ef | ||
|
|
a60658763d | ||
|
|
b76a009e4e | ||
|
|
db333a693f | ||
|
|
fd0d26486b | ||
| 8d559f4b11 | |||
|
|
e1f4ae717e | ||
|
|
7b9c1edbab | ||
|
|
05294a7736 | ||
|
|
d8da808580 | ||
|
|
c420d8b3dd | ||
|
|
57af3aaae3 | ||
|
|
887b9abed8 | ||
|
|
a862d31c7d | ||
| 48f66aac75 | |||
|
|
431c65e075 | ||
|
|
7e64a7ca16 | ||
|
|
6e0efc76f3 | ||
|
|
1a9d7ad460 | ||
| 6dfe92f211 | |||
|
|
9209f1c4e0 | ||
| 4bb485e833 | |||
|
|
3ebfc61ac7 | ||
|
|
d8d8b58ed7 | ||
|
|
a8970053f9 | ||
|
|
7cd77ab904 | ||
|
|
fa0a93172d | ||
|
|
bb74a486d8 | ||
|
|
10c176a0f5 | ||
|
|
d1932762f9 | ||
|
|
9181b6c4ca | ||
|
|
b703d8b9a1 | ||
|
|
acaa7d078a | ||
|
|
30448b5f3d | ||
|
|
ff38c5c475 | ||
|
|
42daeb9971 | ||
|
|
fc7ece9e94 | ||
|
|
c8b6bc35d5 | ||
|
|
5f2a4e1721 | ||
| c77e534ed8 | |||
|
|
5c42b6e52a | ||
|
|
f7364e7939 | ||
| 1c92918692 | |||
|
|
b4a1f0820f | ||
|
|
6d9d5c49ae | ||
|
|
1ca44b472b | ||
|
|
79aabeac8c | ||
|
|
5eb85dab89 | ||
|
|
291b7e71a2 | ||
|
|
2aaa2aca70 | ||
|
|
456d386551 | ||
| cca852d466 | |||
|
|
e663d61b9e | ||
| a098c8051a | |||
|
|
c3ed181b07 | ||
|
|
5b3f2488d4 | ||
|
|
659413ca31 | ||
|
|
4de505bc21 | ||
|
|
7c58f0d508 | ||
|
|
c9246d1342 | ||
|
|
eab795b6df | ||
|
|
f8ab14a026 | ||
|
|
274897a070 | ||
|
|
8ecbeb9c41 | ||
|
|
a1482d11f2 | ||
|
|
f9a302c9a0 | ||
|
|
ad530e9155 | ||
|
|
182aa59ee1 | ||
|
|
296f1f6c3a | ||
|
|
f7355f8e74 | ||
|
|
cd58a7a321 | ||
|
|
2beb8ab303 | ||
|
|
5425ccc5cd | ||
|
|
1104c8e6c5 | ||
|
|
274ffcf5ec | ||
|
|
5854dbc20b | ||
|
|
f36a196b2f | ||
|
|
11f26809df | ||
|
|
c88fbe68e3 | ||
|
|
7f4c53ddb7 | ||
|
|
38b38845d6 | ||
|
|
66dd2877b2 | ||
|
|
3cd53c7d70 | ||
|
|
5b3bdc750f |
3
.github/workflows/upload_data.yml
vendored
3
.github/workflows/upload_data.yml
vendored
@@ -20,7 +20,7 @@ jobs:
|
||||
echo "$GOOGLE_SERVICE_ACCOUNT_JSON" > service_account.json
|
||||
|
||||
python <<'PYCODE'
|
||||
import gspread, json, subprocess
|
||||
import gspread, json, subprocess, time
|
||||
|
||||
creds = json.load(open("service_account.json"))
|
||||
gc = gspread.service_account_from_dict(creds)
|
||||
@@ -38,6 +38,7 @@ jobs:
|
||||
|
||||
for i, row in enumerate(rows_to_append):
|
||||
worksheet.insert_row(row, start_row + i)
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
with open(f"{v}/test_data.log", "r") as f:
|
||||
|
||||
@@ -22,6 +22,68 @@ A vágyálom rendszer alapját egy központi szerver képezné, amely kezeli a f
|
||||
A platform célja a megbízható és folyamatos működés, akár nagyobb terhelés mellett is. A rendszer fejlesztése során kiemelt szempont lenne a biztonság (adatvédelem, csalás elleni védelem), a stabil hálózati kommunikáció, valamint a bővíthetőség – például ranglisták, versenyek vagy mobilalkalmazás későbbi integrálásának lehetősége.
|
||||
|
||||
Összességében a vágyálom rendszer egy minden szempontból teljes értékű, közösségorientált sakkalkalmazás lenne, amely a mostani, helyi hálózaton működő változatból fejlődne tovább egy interneten keresztül bárhonnan elérhető platformmá.
|
||||
|
||||
## 3. Igényelt funkciók
|
||||
|
||||
### Alapok
|
||||
- Két játékos közti sakkjátszma lebonyolítása.
|
||||
- Teljes szabályrendszer megvalósítása (érvényes lépések, sakk/sakkmatt/patt felismerése).
|
||||
- Új játék indítása.
|
||||
- Játékosok nevének megadása a játszma elején.
|
||||
- Felhasználóbarát grafikus felület (UI) – látható tábla, figurák, órák, státuszjelzések.
|
||||
- Játékoslépések vizuális kiemelése (pl. kijelölt mező, lehetséges lépések megjelenítése).
|
||||
- A játék állapotának kijelzése (folyamatban, sakk, matt, döntetlen).
|
||||
|
||||
### LAN és hálózati funkciók
|
||||
- „Szerver indítása” funkció – a játékos hostként indíthat egy helyi szervert.
|
||||
- „Csatlakozás” funkció – másik játékos IP-cím alapján tud csatlakozni.
|
||||
- Helyi hálózaton keresztüli valós idejű kommunikáció.
|
||||
- LAN játék automatikus felfedezése (broadcast keresés).
|
||||
- Játék mentése és visszatöltése hálózati módban.
|
||||
|
||||
### Online vágyálom funkciók
|
||||
- Felhasználói regisztráció és bejelentkezés.
|
||||
- Jelszóval védett fiókok, email- vagy OAuth-alapú hitelesítés (Google, GitHub stb.).
|
||||
- Profiloldal megtekintése (név, avatar, statisztikák, értékszám).
|
||||
- Automatikus matchmaking rendszer.
|
||||
- Kézi játékindítás – meghívó küldése barátnak.
|
||||
- Játszmák mentése és visszajátszása.
|
||||
- Játszmaelemzés – lépések listázása, hibák kiemelése.
|
||||
- Webes felület vagy mobilalkalmazás támogatása.
|
||||
- Játék előzményeinek és statisztikáinak megtekintése (győzelmek, vereségek, döntetlenek).
|
||||
- Automatikus szervermentés és adatbázis szinkronizáció.
|
||||
|
||||
### Felhasználói felület
|
||||
- Letisztult, reszponzív, platformfüggetlen felület (asztali és webes verzió).
|
||||
- Sötét/világos téma lehetősége.
|
||||
- Egyéni figurakészlet vagy tábla kinézet választása.
|
||||
- Animált figuramozgások.
|
||||
- Egérrel és billentyűzettel is vezérelhető játék.
|
||||
- Hangjelzések a lépésekhez és az idő lejártához.
|
||||
- Lépéselőzmények (move list) megjelenítése oldalt.
|
||||
- Tábla forgatásának lehetősége (pl. a fehér vagy fekete nézőpontból).
|
||||
- Állapotjelzők (sakk, matt, döntetlen, várakozás az ellenfélre).
|
||||
- Teljes képernyős mód.
|
||||
|
||||
### Technikai / fejlesztői funkciók
|
||||
- Kliens–szerver architektúra.
|
||||
- REST API vagy WebSocket alapú kommunikáció.
|
||||
- Adatbázis a felhasználói adatok és meccsek tárolására (pl. SQLite, PostgreSQL, MongoDB).
|
||||
- Logolási és hibakezelési rendszer.
|
||||
- Automatikus mentés és adatvisszaállítás.
|
||||
- Verziókezelés (Git).
|
||||
- Tesztelhető, moduláris kódszerkezet (külön modulok: logika, UI, hálózat, adat).
|
||||
- Cross-platform működés (Windows, Linux, esetleg web).
|
||||
|
||||
### További funkciók
|
||||
- Egyszemélyes mód (ember vs. gép, AI-bot).
|
||||
- Több nehézségi szintű AI.
|
||||
- Oktató mód (javasolt lépések, hibák magyarázata).
|
||||
- Hivatalos FEN/PGN formátum export/import.
|
||||
- Beépített sakkfeladványok, kihívások.
|
||||
- Érintéses vezérlés mobilon.
|
||||
- Többnyelvű felület (pl. magyar, angol).
|
||||
|
||||
## 4. Rendszer követelmények
|
||||
|
||||
A rendszer célja egy kétjátékos sakkalkalmazás megvalósítása, amely alapvetően hálózati kapcsolat (LAN vagy internet) segítségével biztosítja a valós idejű játékot. A rendszer kliens–szerver architektúrán alapul, ahol az egyes komponensek jól elkülönülten, meghatározott feladatokat látnak el.
|
||||
|
||||
@@ -4,4 +4,6 @@ version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
once_cell = "1.19"
|
||||
once_cell = "1.19"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
|
||||
@@ -1,2 +1,9 @@
|
||||
mod attackmaps;
|
||||
mod utils;
|
||||
mod utils;
|
||||
mod legality;
|
||||
mod checkinfo;
|
||||
mod attacks;
|
||||
mod bitmove;
|
||||
mod movebuffer;
|
||||
|
||||
pub mod board;
|
||||
89
engine/src/bitboard/attacks.rs
Normal file
89
engine/src/bitboard/attacks.rs
Normal file
@@ -0,0 +1,89 @@
|
||||
use super::board::Board;
|
||||
use super::attackmaps::*;
|
||||
|
||||
impl Board {
|
||||
|
||||
const RANK_2: u64 = 0x0000_0000_0000_FF00;
|
||||
const RANK_7: u64 = 0x00FF_0000_0000_0000;
|
||||
|
||||
pub fn get_pseudo_pawn_moves(&self, sq: u32) -> u64 {
|
||||
let pawn: u64 = 1 << sq;
|
||||
let mut move_mask: u64 = 0u64;
|
||||
let move_offset: i8 = 8 - 16 * self.side_to_move as i8;
|
||||
|
||||
let next_sq: u64 = if move_offset > 0 {pawn << move_offset} else {pawn >> -move_offset};
|
||||
if (self.occupancy[2] & next_sq) == 0 {
|
||||
move_mask |= next_sq;
|
||||
|
||||
if (self.side_to_move == 0 && pawn & Self::RANK_2 != 0)
|
||||
|| (self.side_to_move == 1 && pawn & Self::RANK_7 != 0) {
|
||||
|
||||
let next_sq: u64 = if move_offset > 0 {next_sq << move_offset} else {next_sq >> -move_offset};
|
||||
if (self.occupancy[2] & next_sq) == 0 {
|
||||
move_mask |= next_sq;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return move_mask;
|
||||
}
|
||||
#[inline]
|
||||
pub fn get_pseudo_knight_moves(&self, sq: u32) -> u64 {
|
||||
return KNIGHT_ATTACK_MAP[sq as usize];
|
||||
}
|
||||
#[inline]
|
||||
pub fn get_pseudo_king_moves(&self, sq: u32) -> u64 {
|
||||
return KING_ATTACK_MAP[sq as usize];
|
||||
}
|
||||
#[inline]
|
||||
pub fn get_pseudo_pawn_captures(&self, sq: u32) -> u64 {
|
||||
return PAWN_ATTACK_MAP[sq as usize][self.side_to_move as usize];
|
||||
}
|
||||
#[inline]
|
||||
pub fn get_pseudo_opponent_pawn_captures(&self, sq: u32) -> u64 {
|
||||
return PAWN_ATTACK_MAP[sq as usize][1 - self.side_to_move as usize];
|
||||
}
|
||||
#[inline]
|
||||
pub fn get_pseudo_bishop_moves(&self, sq: u32) -> u64 {
|
||||
let mut moves = 0u64;
|
||||
let sq = sq as usize;
|
||||
let occupancy = self.occupancy[2];
|
||||
moves |= get_raycast_from_square_in_direction(occupancy, sq, 1);
|
||||
moves |= get_raycast_from_square_in_direction(occupancy, sq, 3);
|
||||
moves |= get_raycast_from_square_in_direction(occupancy, sq, 5);
|
||||
moves |= get_raycast_from_square_in_direction(occupancy, sq, 7);
|
||||
|
||||
return moves;
|
||||
}
|
||||
#[inline]
|
||||
pub fn get_pseudo_rook_moves(&self, sq: u32) -> u64 {
|
||||
let mut moves: u64 = 0u64;
|
||||
let occupancy = self.occupancy[2];
|
||||
let sq = sq as usize;
|
||||
moves |= get_raycast_from_square_in_direction(occupancy, sq, 0);
|
||||
moves |= get_raycast_from_square_in_direction(occupancy, sq, 2);
|
||||
moves |= get_raycast_from_square_in_direction(occupancy, sq, 4);
|
||||
moves |= get_raycast_from_square_in_direction(occupancy, sq, 6);
|
||||
|
||||
return moves;
|
||||
}
|
||||
#[inline(always)]
|
||||
pub fn get_pseudo_queen_moves(&self, sq: u32) -> u64 {
|
||||
return self.get_pseudo_bishop_moves(sq) | self.get_pseudo_rook_moves(sq);
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn get_raycast_from_square_in_direction(occupancy: u64, sq: usize, dir: usize) -> u64 {
|
||||
let is_up: bool = dir / 4 == 0;
|
||||
let mut ray: u64 = RAY_TABLE[sq][dir];
|
||||
let blockers: u64 = occupancy & ray;
|
||||
|
||||
if blockers != 0 {
|
||||
let first_blocker: u32 = if is_up { blockers.trailing_zeros() } else { 63 - blockers.leading_zeros() };
|
||||
|
||||
ray &= !RAY_TABLE[first_blocker as usize][dir];
|
||||
}
|
||||
|
||||
return ray;
|
||||
}
|
||||
77
engine/src/bitboard/bitmove.rs
Normal file
77
engine/src/bitboard/bitmove.rs
Normal file
@@ -0,0 +1,77 @@
|
||||
use super::utils::*;
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Eq)]
|
||||
pub struct BitMove {
|
||||
|
||||
move_type: BitMoveType,
|
||||
from_square: u8,
|
||||
to_square: u8,
|
||||
promotion_piece: Option<u8>
|
||||
}
|
||||
|
||||
impl BitMove {
|
||||
|
||||
#[inline]
|
||||
pub fn quiet(from: u8, to: u8, promotion_piece: Option<u8>) -> Self {
|
||||
return Self {
|
||||
move_type: BitMoveType::Quiet,
|
||||
from_square: from,
|
||||
to_square: to,
|
||||
promotion_piece: promotion_piece
|
||||
};
|
||||
}
|
||||
#[inline]
|
||||
pub fn capture(from: u8, to: u8, promotion_piece: Option<u8>) -> Self {
|
||||
return Self {
|
||||
move_type: BitMoveType::Capture,
|
||||
from_square: from,
|
||||
to_square: to,
|
||||
promotion_piece: promotion_piece
|
||||
};
|
||||
}
|
||||
#[inline]
|
||||
pub fn castle(from: u8, to: u8) -> Self {
|
||||
return Self {
|
||||
move_type: BitMoveType::Castle,
|
||||
from_square: from,
|
||||
to_square: to,
|
||||
promotion_piece: None
|
||||
};
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn move_type(&self) -> BitMoveType {
|
||||
return self.move_type;
|
||||
}
|
||||
#[inline(always)]
|
||||
pub fn from_square(&self) -> u8 {
|
||||
return self.from_square;
|
||||
}
|
||||
#[inline(always)]
|
||||
pub fn to_square(&self) -> u8 {
|
||||
return self.to_square;
|
||||
}
|
||||
#[inline(always)]
|
||||
pub fn promotion_piece(&self) -> Option<u8> {
|
||||
return self.promotion_piece;
|
||||
}
|
||||
|
||||
pub fn uci_notation(&self) -> String {
|
||||
let mut notation = notation_from_square_number(self.from_square());
|
||||
notation.push_str(¬ation_from_square_number(self.to_square()));
|
||||
|
||||
if let Some(promotion_piece) = self.promotion_piece {
|
||||
notation.push(get_character_by_piece_id(promotion_piece).to_ascii_lowercase());
|
||||
}
|
||||
|
||||
return notation;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Eq)]
|
||||
pub enum BitMoveType {
|
||||
Quiet,
|
||||
Capture,
|
||||
Castle,
|
||||
EnPassant
|
||||
}
|
||||
199
engine/src/bitboard/board.rs
Normal file
199
engine/src/bitboard/board.rs
Normal file
@@ -0,0 +1,199 @@
|
||||
use super::utils::try_get_square_number_from_notation;
|
||||
|
||||
pub struct Board {
|
||||
pub(in super) bitboards: [u64; 12], // 0-5 -> white pieces (P, N, B, R, Q, K), 6-11 -> black pieces (p, n, b, r, q, k)
|
||||
pub(in super) piece_board: [u8; 64], // same as board indexes, 12 -> empty square
|
||||
pub(in super) occupancy: [u64; 3], // 0 -> white, 1 -> black, 2 -> combined
|
||||
pub(in super) castling_rights: u8, // 0b0000_KQkq
|
||||
pub(in super) pinned_squares: [u8; 64], // 0 -> E-W, 1 -> NE-SW, 2 -> N-S, 3 -> SE-NW, 4 -> no pin
|
||||
pub(in super) pin_mask: u64, // 1 -> pin, 0 -> no pin
|
||||
pub(in super) en_passant_square: u64, // 1 -> ep square, 0 -> no ep square
|
||||
pub(in super) side_to_move: u8 // 0 -> white to play, 1 -> black to play
|
||||
}
|
||||
|
||||
impl Board {
|
||||
|
||||
pub fn new_clear() -> Self {
|
||||
let mut bit_board: Self = Self {
|
||||
bitboards: [0x0000_0000_0000_0000; 12],
|
||||
piece_board: [12; 64],
|
||||
occupancy: [0x0000_0000_0000_0000; 3],
|
||||
castling_rights: 0b0000_0000,
|
||||
pinned_squares: [4; 64],
|
||||
pin_mask: 0u64,
|
||||
en_passant_square: 0x0000_0000_0000_0000,
|
||||
side_to_move: 0
|
||||
};
|
||||
|
||||
return bit_board;
|
||||
}
|
||||
pub fn new() -> Self {
|
||||
let mut bit_board: Board = Self {
|
||||
bitboards: [0x0000_0000_0000_FF00,
|
||||
0x0000_0000_0000_0042,
|
||||
0x0000_0000_0000_0024,
|
||||
0x0000_0000_0000_0081,
|
||||
0x0000_0000_0000_0008,
|
||||
0x0000_0000_0000_0010,
|
||||
0x00FF_0000_0000_0000,
|
||||
0x4200_0000_0000_0000,
|
||||
0x2400_0000_0000_0000,
|
||||
0x8100_0000_0000_0000,
|
||||
0x0800_0000_0000_0000,
|
||||
0x1000_0000_0000_0000],
|
||||
piece_board: [12; 64],
|
||||
occupancy: [0; 3],
|
||||
castling_rights: 0b0000_1111,
|
||||
pinned_squares: [4; 64],
|
||||
pin_mask: 0u64,
|
||||
en_passant_square: 0x0000_0000_0000_0000,
|
||||
side_to_move: 0
|
||||
};
|
||||
bit_board.calc_occupancy();
|
||||
bit_board.calc_piece_board();
|
||||
|
||||
return bit_board;
|
||||
}
|
||||
pub fn build(fen: &str) -> Self {
|
||||
let mut board: Board = Board::new_clear();
|
||||
|
||||
let mut col: i32 = 0;
|
||||
let mut row: i32 = 7;
|
||||
let pieces: [char; 12] = ['p', 'n', 'b', 'r', 'q', 'k', 'P', 'N', 'B', 'R', 'Q', 'K'];
|
||||
let mut coming_up: &str = fen;
|
||||
|
||||
for (i, c) in coming_up.chars().enumerate() {
|
||||
if pieces.contains(&c) {
|
||||
board.place_piece(row*8 + col, c);
|
||||
col += 1;
|
||||
}
|
||||
else if ('1'..='8').contains(&c) {
|
||||
col += c.to_string().parse::<i32>().unwrap();
|
||||
}
|
||||
else if c == '/' {
|
||||
row -= 1;
|
||||
col = 0;
|
||||
}
|
||||
else {
|
||||
coming_up = &coming_up[i+1..];
|
||||
break;
|
||||
}
|
||||
}
|
||||
board.calc_occupancy();
|
||||
|
||||
match coming_up.chars().next().unwrap() {
|
||||
'w' => board.side_to_move = 0,
|
||||
'b' => board.side_to_move = 1,
|
||||
_ => panic!("invalid fen notation / to be handled later")
|
||||
}
|
||||
coming_up = &coming_up[2..];
|
||||
|
||||
for (i, c) in coming_up.chars().enumerate() {
|
||||
match c {
|
||||
'K' => board.castling_rights |= 1 << 3,
|
||||
'Q' => board.castling_rights |= 1 << 2,
|
||||
'k' => board.castling_rights |= 1 << 1,
|
||||
'q' => board.castling_rights |= 1,
|
||||
'-' => {
|
||||
coming_up = &coming_up[i+2..];
|
||||
break;
|
||||
}
|
||||
_ => {
|
||||
coming_up = &coming_up[i+1..];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
match coming_up.chars().next().unwrap() {
|
||||
'-' => {
|
||||
coming_up = &coming_up[1..];
|
||||
}
|
||||
_ => {
|
||||
let notation = coming_up.split(' ').next().unwrap();
|
||||
if let Ok(epsq_index) = try_get_square_number_from_notation(notation) {
|
||||
board.en_passant_square = 1 << epsq_index;
|
||||
}
|
||||
}
|
||||
}
|
||||
board.calc_pinned_squares();
|
||||
board.calc_piece_board();
|
||||
|
||||
return board;
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn bitboards(&self, index: usize) -> u64 {
|
||||
return self.bitboards[index];
|
||||
}
|
||||
#[inline(always)]
|
||||
pub fn piece_board(&self, sq: u8) -> u8 {
|
||||
return self.piece_board[sq as usize];
|
||||
}
|
||||
#[inline(always)]
|
||||
pub fn occupancy(&self, side: usize) -> u64 {
|
||||
return self.occupancy[side];
|
||||
}
|
||||
#[inline(always)]
|
||||
pub fn castling_rights(&self) -> u8 {
|
||||
return self.castling_rights;
|
||||
}
|
||||
#[inline(always)]
|
||||
pub fn pinned_squares(&self, sq: usize) -> u8 {
|
||||
return self.pinned_squares[sq];
|
||||
}
|
||||
#[inline(always)]
|
||||
pub fn pin_mask(&self) -> u64 {
|
||||
return self.pin_mask;
|
||||
}
|
||||
#[inline(always)]
|
||||
pub fn en_passant_square(&self) -> u64 {
|
||||
return self.en_passant_square;
|
||||
}
|
||||
#[inline(always)]
|
||||
pub fn side_to_move(&self) -> u8 {
|
||||
return self.side_to_move;
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn current_king_square(&self) -> u32 {
|
||||
return if self.side_to_move == 0 { self.bitboards[5].trailing_zeros() } else { self.bitboards[11].trailing_zeros() };
|
||||
}
|
||||
|
||||
fn calc_occupancy(&mut self) {
|
||||
self.occupancy = [0u64; 3];
|
||||
for b in 0..6 {
|
||||
self.occupancy[0] |= self.bitboards[b];
|
||||
}
|
||||
for b in 6..12 {
|
||||
self.occupancy[1] |= self.bitboards[b];
|
||||
}
|
||||
self.occupancy[2] = self.occupancy[0] | self.occupancy[1];
|
||||
}
|
||||
fn calc_piece_board(&mut self) {
|
||||
for sq in 0..64 {
|
||||
for b in 0..12 {
|
||||
if (self.bitboards[b as usize] & 1 << sq) != 0 {
|
||||
self.piece_board[sq] = b;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn place_piece(&mut self, sq: i32, piece: char) {
|
||||
match piece {
|
||||
'p' => {self.bitboards[6] |= 1 << sq}
|
||||
'n' => {self.bitboards[7] |= 1 << sq}
|
||||
'b' => {self.bitboards[8] |= 1 << sq}
|
||||
'r' => {self.bitboards[9] |= 1 << sq}
|
||||
'q' => {self.bitboards[10] |= 1 << sq}
|
||||
'k' => {self.bitboards[11] |= 1 << sq}
|
||||
'P' => {self.bitboards[0] |= 1 << sq}
|
||||
'N' => {self.bitboards[1] |= 1 << sq}
|
||||
'B' => {self.bitboards[2] |= 1 << sq}
|
||||
'R' => {self.bitboards[3] |= 1 << sq}
|
||||
'Q' => {self.bitboards[4] |= 1 << sq}
|
||||
'K' => {self.bitboards[5] |= 1 << sq}
|
||||
_ => ()
|
||||
}
|
||||
}
|
||||
}
|
||||
21
engine/src/bitboard/checkinfo.rs
Normal file
21
engine/src/bitboard/checkinfo.rs
Normal file
@@ -0,0 +1,21 @@
|
||||
|
||||
pub struct CheckInfo {
|
||||
pub check_count: u8,
|
||||
pub move_mask: u64
|
||||
}
|
||||
|
||||
impl CheckInfo {
|
||||
|
||||
pub fn new() -> Self {
|
||||
return Self {
|
||||
check_count: 0,
|
||||
move_mask: 0xFFFF_FFFF_FFFF_FFFF
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn add_checker(&mut self, move_mask: u64) {
|
||||
self.move_mask &= move_mask;
|
||||
self.check_count += 1;
|
||||
}
|
||||
}
|
||||
127
engine/src/bitboard/legality.rs
Normal file
127
engine/src/bitboard/legality.rs
Normal file
@@ -0,0 +1,127 @@
|
||||
use super::board::Board;
|
||||
use super::attackmaps::RAY_TABLE;
|
||||
use super::checkinfo::CheckInfo;
|
||||
use super::attacks::get_raycast_from_square_in_direction;
|
||||
|
||||
impl Board {
|
||||
|
||||
pub fn check_test(&self) -> CheckInfo {
|
||||
let mut check_info: CheckInfo = CheckInfo::new();
|
||||
let offset: usize = 6 * self.side_to_move as usize;
|
||||
let king: u64 = self.bitboards[5 + offset];
|
||||
let king_sq = king.trailing_zeros() as usize;
|
||||
let occupancy = self.occupancy[2];
|
||||
|
||||
// queen-rook checks (+)
|
||||
let attacker_mask = self.bitboards[10 - offset] | self.bitboards[9 - offset];
|
||||
|
||||
for dir in [0, 2, 4, 6] {
|
||||
let threat_mask: u64 = get_raycast_from_square_in_direction(occupancy, king_sq, dir);
|
||||
if threat_mask & attacker_mask != 0 {
|
||||
check_info.add_checker(threat_mask);
|
||||
}
|
||||
}
|
||||
|
||||
// queen-bishop checks (x)
|
||||
let attacker_mask = self.bitboards[10 - offset] | self.bitboards[8 - offset];
|
||||
|
||||
for dir in [1, 3, 5, 7] {
|
||||
let threat_mask = get_raycast_from_square_in_direction(occupancy, king_sq, dir);
|
||||
if threat_mask & attacker_mask != 0 {
|
||||
check_info.add_checker(threat_mask);
|
||||
}
|
||||
}
|
||||
|
||||
// knight checks (L)
|
||||
let attacker_mask = self.bitboards[7 - offset];
|
||||
let threat_mask = self.get_pseudo_knight_moves(king_sq as u32);
|
||||
let checker = threat_mask & attacker_mask;
|
||||
if checker != 0 {
|
||||
check_info.add_checker(checker);
|
||||
}
|
||||
|
||||
// pawn checks (v)
|
||||
let attacker_mask = self.bitboards[6 - offset];
|
||||
let threat_mask = self.get_pseudo_pawn_captures(king_sq as u32);
|
||||
let checker = threat_mask & attacker_mask;
|
||||
if checker != 0 {
|
||||
check_info.add_checker(checker);
|
||||
}
|
||||
|
||||
return check_info;
|
||||
}
|
||||
|
||||
pub(in super) fn calc_pinned_squares(&mut self) {
|
||||
self.pinned_squares = [4; 64];
|
||||
self.pin_mask = 0u64;
|
||||
|
||||
let friendly_pieces: u64 = self.occupancy[self.side_to_move as usize];
|
||||
let offset: usize = 6 * self.side_to_move as usize;
|
||||
let king_board: u64 = self.bitboards[5 + offset];
|
||||
let king_sq: u32 = king_board.trailing_zeros();
|
||||
let opponent_queen_bishop_mask: u64 = self.bitboards[8 - offset] | self.bitboards[10 - offset];
|
||||
let opponent_queen_rook_mask: u64 = self.bitboards[9 - offset] | self.bitboards[10 - offset];
|
||||
|
||||
// Queen-Rook directions
|
||||
self.set_pinned_in_ray_direction(king_sq, friendly_pieces, opponent_queen_rook_mask, 0);
|
||||
self.set_pinned_in_ray_direction(king_sq, friendly_pieces, opponent_queen_rook_mask, 2);
|
||||
self.set_pinned_in_ray_direction(king_sq, friendly_pieces, opponent_queen_rook_mask, 4);
|
||||
self.set_pinned_in_ray_direction(king_sq, friendly_pieces, opponent_queen_rook_mask, 6);
|
||||
|
||||
// Queen-Bishop directions
|
||||
self.set_pinned_in_ray_direction(king_sq, friendly_pieces, opponent_queen_bishop_mask, 1);
|
||||
self.set_pinned_in_ray_direction(king_sq, friendly_pieces, opponent_queen_bishop_mask, 3);
|
||||
self.set_pinned_in_ray_direction(king_sq, friendly_pieces, opponent_queen_bishop_mask, 5);
|
||||
self.set_pinned_in_ray_direction(king_sq, friendly_pieces, opponent_queen_bishop_mask, 7);
|
||||
}
|
||||
|
||||
pub(in super) fn set_pinned_in_ray_direction(&mut self, king_sq: u32, friendly_pieces: u64, attackers: u64, dir: u8) {
|
||||
let is_up: bool = dir / 4 == 0;
|
||||
let mask: u64 = RAY_TABLE[king_sq as usize][dir as usize];
|
||||
let blockers: u64 = self.occupancy[2] & mask;
|
||||
if blockers == 0 { return; }
|
||||
let first_blocker_sq: u32 = if is_up { blockers.trailing_zeros() } else { 63 - blockers.leading_zeros() };
|
||||
if (friendly_pieces & 1 << first_blocker_sq) != 0 {
|
||||
let blockers: u64 = blockers & !(1 << first_blocker_sq);
|
||||
if blockers == 0 { return; }
|
||||
let second_blocker_sq: u32 = if is_up { blockers.trailing_zeros() } else { 63 - blockers.leading_zeros() };
|
||||
|
||||
if (attackers & 1 << second_blocker_sq) != 0 {
|
||||
self.pinned_squares[first_blocker_sq as usize] = dir % 4;
|
||||
self.pin_mask |= 1 << first_blocker_sq;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// <----- TESTS ----->
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn check_test_test() {
|
||||
|
||||
let fens = [
|
||||
"rnb1k1nr/pppppppp/4q3/8/1b6/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", // no check
|
||||
"rnb1k1nr/pppppppp/4q3/8/1b1P4/8/PPP1PPPP/RNBQKBNR w KQkq d3 0 1", // single check
|
||||
"rnb1k1nr/ppp1p2p/3pq1p1/8/1b1P1P2/8/PPP2PPP/RNBQKBNR w KQkq - 0 1" // double check
|
||||
];
|
||||
let expected_results = [
|
||||
CheckInfo { check_count: 0, move_mask: 0xFFFF_FFFF_FFFF_FFFF },
|
||||
CheckInfo { check_count: 1, move_mask: 0x0000_0000_0204_0800 },
|
||||
CheckInfo { check_count: 2, move_mask: 0x0000_0000_0000_0000 }
|
||||
];
|
||||
|
||||
for test_nr in 0..3 {
|
||||
let fen = fens[test_nr];
|
||||
let board = Board::build(fen);
|
||||
let check_test_actual = board.check_test();
|
||||
assert_eq!(check_test_actual.check_count, expected_results[test_nr].check_count);
|
||||
assert_eq!(check_test_actual.move_mask, expected_results[test_nr].move_mask);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
44
engine/src/bitboard/movebuffer.rs
Normal file
44
engine/src/bitboard/movebuffer.rs
Normal file
@@ -0,0 +1,44 @@
|
||||
use super::bitmove::BitMove;
|
||||
|
||||
pub struct MoveBuffer {
|
||||
|
||||
buffer: [BitMove; 256],
|
||||
count: usize
|
||||
}
|
||||
|
||||
impl MoveBuffer {
|
||||
|
||||
pub fn new() -> Self {
|
||||
return Self {
|
||||
buffer: [BitMove::quiet(0, 0, None); 256],
|
||||
count: 0
|
||||
};
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn add(&mut self, bitmove: BitMove) {
|
||||
self.buffer[self.count] = bitmove;
|
||||
self.count += 1;
|
||||
}
|
||||
#[inline]
|
||||
pub fn append(&mut self, other: &MoveBuffer) {
|
||||
self.buffer[self.count..self.count + other.count()].copy_from_slice(other.contents());
|
||||
self.count += other.count();
|
||||
}
|
||||
#[inline(always)]
|
||||
pub fn clear(&mut self) {
|
||||
self.count = 0;
|
||||
}
|
||||
#[inline(always)]
|
||||
pub fn count(&self) -> usize{
|
||||
return self.count;
|
||||
}
|
||||
#[inline(always)]
|
||||
pub fn get(&self, idx: usize) -> &BitMove {
|
||||
return &self.buffer[idx];
|
||||
}
|
||||
#[inline(always)]
|
||||
pub fn contents(&self) -> &[BitMove] {
|
||||
return &self.buffer[0..self.count];
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,32 @@ pub fn notation_from_square_number(sq: u8) -> String {
|
||||
return notation;
|
||||
}
|
||||
|
||||
pub fn try_get_square_number_from_notation(notation: &str) -> Result<u8, ()> {
|
||||
|
||||
let file = match notation.chars().nth(0).unwrap() {
|
||||
'a' => 0,
|
||||
'b' => 1,
|
||||
'c' => 2,
|
||||
'd' => 3,
|
||||
'e' => 4,
|
||||
'f' => 5,
|
||||
'g' => 6,
|
||||
'h' => 7,
|
||||
_ => { return Result::Err(()); }
|
||||
};
|
||||
if let Some(rank) = notation.chars().nth(1) {
|
||||
return Result::Ok(file + 8 * (rank.to_digit(10).unwrap() as u8) - 8);
|
||||
}
|
||||
else {
|
||||
return Result::Err(());
|
||||
}
|
||||
}
|
||||
|
||||
const PIECE_CHARACTERS: [char; 12] = ['P', 'N', 'B', 'R', 'Q', 'K', 'p', 'n', 'b', 'r', 'q', 'k'];
|
||||
pub fn get_character_by_piece_id(id: u8) -> char {
|
||||
return PIECE_CHARACTERS[id as usize];
|
||||
}
|
||||
|
||||
|
||||
// <----- TESTS ----->
|
||||
|
||||
|
||||
31
engine/src/boardsquare.rs
Normal file
31
engine/src/boardsquare.rs
Normal file
@@ -0,0 +1,31 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct BoardSquare {
|
||||
pub x: usize,
|
||||
pub y: usize,
|
||||
}
|
||||
|
||||
impl BoardSquare {
|
||||
pub fn new() -> Self {
|
||||
return Self { x: 0, y: 0 };
|
||||
}
|
||||
|
||||
pub fn from_coord(x: usize, y: usize) -> Self {
|
||||
#[cfg(debug_assertions)]
|
||||
{
|
||||
if x > 7 {
|
||||
println!(
|
||||
"Warning: x coordinate of square is bigger than 7, it might not be on the board!"
|
||||
);
|
||||
}
|
||||
if y > 7 {
|
||||
println!(
|
||||
"Warning: y coordinate of square is bigger than 7, it might not be on the board!"
|
||||
);
|
||||
}
|
||||
}
|
||||
return Self { x: x, y: y };
|
||||
}
|
||||
}
|
||||
|
||||
71
engine/src/chessmove.rs
Normal file
71
engine/src/chessmove.rs
Normal file
@@ -0,0 +1,71 @@
|
||||
use crate::piecetype;
|
||||
|
||||
use super::boardsquare::BoardSquare;
|
||||
use super::movetype::MoveType;
|
||||
use super::piecetype::PieceType;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct ChessMove {
|
||||
pub move_type: MoveType,
|
||||
pub piece_type: PieceType,
|
||||
pub from_square: BoardSquare,
|
||||
pub to_square: BoardSquare,
|
||||
pub rook_from: BoardSquare,
|
||||
pub rook_to: BoardSquare,
|
||||
pub promotion_piece: Option<PieceType>,
|
||||
}
|
||||
|
||||
impl ChessMove {
|
||||
pub fn quiet(
|
||||
piece_type: PieceType,
|
||||
from_square: BoardSquare,
|
||||
to_square: BoardSquare,
|
||||
promotion_piece: Option<PieceType>,
|
||||
) -> Self {
|
||||
return Self {
|
||||
move_type: MoveType::Quiet,
|
||||
piece_type: piece_type,
|
||||
from_square: from_square,
|
||||
to_square: to_square,
|
||||
rook_from: BoardSquare::new(),
|
||||
rook_to: BoardSquare::new(),
|
||||
promotion_piece: promotion_piece,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn capture(
|
||||
piece_type: PieceType,
|
||||
from_square: BoardSquare,
|
||||
to_square: BoardSquare,
|
||||
promotion_piece: Option<PieceType>,
|
||||
) -> Self {
|
||||
return Self {
|
||||
move_type: MoveType::Capture,
|
||||
piece_type: piece_type,
|
||||
from_square: from_square,
|
||||
to_square: to_square,
|
||||
rook_from: BoardSquare::new(),
|
||||
rook_to: BoardSquare::new(),
|
||||
promotion_piece: promotion_piece,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn castle(
|
||||
piece_type: PieceType,
|
||||
from_square: BoardSquare,
|
||||
to_square: BoardSquare,
|
||||
rook_from: BoardSquare,
|
||||
rook_to: BoardSquare,
|
||||
) -> Self {
|
||||
return Self {
|
||||
move_type: MoveType::Quiet,
|
||||
piece_type: piece_type,
|
||||
from_square: from_square,
|
||||
to_square: to_square,
|
||||
rook_from: rook_from,
|
||||
rook_to: rook_to,
|
||||
promotion_piece: None,
|
||||
};
|
||||
}
|
||||
}
|
||||
9
engine/src/gameend.rs
Normal file
9
engine/src/gameend.rs
Normal file
@@ -0,0 +1,9 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub enum GameEnd {
|
||||
WhiteWon(String),
|
||||
BlackWon(String),
|
||||
Draw(String),
|
||||
}
|
||||
|
||||
24
engine/src/lib.rs
Normal file
24
engine/src/lib.rs
Normal file
@@ -0,0 +1,24 @@
|
||||
mod bitboard;
|
||||
pub mod chessmove;
|
||||
pub mod piecetype;
|
||||
pub mod boardsquare;
|
||||
pub mod movetype;
|
||||
pub mod gameend;
|
||||
|
||||
use chessmove::ChessMove;
|
||||
use gameend::GameEnd;
|
||||
|
||||
pub fn get_available_moves(fen: &str) -> Vec<ChessMove> {
|
||||
println!("get_available_moves answered");
|
||||
return vec![];
|
||||
}
|
||||
|
||||
pub fn is_game_over(fen: &str) -> Option<GameEnd> {
|
||||
println!("is_game_over answered");
|
||||
return None;
|
||||
}
|
||||
|
||||
pub fn get_board_after_move(fen: &str, chess_move: &ChessMove) -> String {
|
||||
println!("get_board_after_move answered");
|
||||
return String::from("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
|
||||
}
|
||||
11
engine/src/movetype.rs
Normal file
11
engine/src/movetype.rs
Normal file
@@ -0,0 +1,11 @@
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub enum MoveType {
|
||||
Quiet,
|
||||
Capture,
|
||||
Castle,
|
||||
EnPassant,
|
||||
}
|
||||
|
||||
18
engine/src/piecetype.rs
Normal file
18
engine/src/piecetype.rs
Normal file
@@ -0,0 +1,18 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub enum PieceType {
|
||||
WhitePawn,
|
||||
WhiteKnight,
|
||||
WhiteBishop,
|
||||
WhiteRook,
|
||||
WhiteQueen,
|
||||
WhiteKing,
|
||||
BlackPawn,
|
||||
BlackKnight,
|
||||
BlackBishop,
|
||||
BlackRook,
|
||||
BlackQueen,
|
||||
BlackKing,
|
||||
}
|
||||
|
||||
1080
server/Cargo.lock
generated
Normal file
1080
server/Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
@@ -14,6 +14,8 @@ url = "2.5.7"
|
||||
uuid = {version = "1.18.1", features = ["v4", "serde"] }
|
||||
anyhow = "1.0.100"
|
||||
rand = "0.9.2"
|
||||
engine = {path = "../engine/"}
|
||||
|
||||
|
||||
[[bin]]
|
||||
name = "client"
|
||||
|
||||
@@ -1,17 +1,27 @@
|
||||
use engine::gameend::GameEnd;
|
||||
use engine::{boardsquare::BoardSquare, chessmove::ChessMove, piecetype::PieceType};
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::io::{self, Write};
|
||||
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 {
|
||||
Join { username: String },
|
||||
FindMatch,
|
||||
Move { from: String, to: String },
|
||||
Move { step: ChessMove, fen: String },
|
||||
Resign,
|
||||
Chat { text: String },
|
||||
RequestLegalMoves { fen: String },
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
@@ -25,6 +35,21 @@ struct ServerMessage {
|
||||
reason: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub enum ServerMessage2 {
|
||||
GameEnd {
|
||||
winner: GameEnd,
|
||||
},
|
||||
UIUpdate {
|
||||
fen: String,
|
||||
},
|
||||
MatchFound {
|
||||
match_id: Uuid,
|
||||
color: String,
|
||||
opponent_name: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
println!("Knightly Chess Client");
|
||||
@@ -60,29 +85,21 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
println!("\nServer: {}", text);
|
||||
|
||||
// Try to parse as structured message
|
||||
if let Ok(parsed) = serde_json::from_str::<ServerMessage>(text) {
|
||||
match parsed.message_type.as_str() {
|
||||
"welcome" => {
|
||||
if let Some(player_id) = parsed.player_id {
|
||||
println!("Welcome! Your player ID: {}", player_id);
|
||||
}
|
||||
if let Ok(parsed) = serde_json::from_str::<ServerMessage2>(text) {
|
||||
match parsed {
|
||||
ServerMessage2::MatchFound {
|
||||
match_id,
|
||||
color,
|
||||
opponent_name,
|
||||
} => {
|
||||
println!(
|
||||
"opponent: {}, match_id: {}, color: {}",
|
||||
opponent_name, match_id, color
|
||||
);
|
||||
}
|
||||
"match_found" => {
|
||||
if let (Some(opponent), Some(color), Some(match_id)) =
|
||||
(parsed.opponent, parsed.color, parsed.match_id)
|
||||
{
|
||||
println!(
|
||||
"Match found! Opponent: {}, Color: {}, Match ID: {}",
|
||||
opponent, color, match_id
|
||||
);
|
||||
}
|
||||
_ => {
|
||||
println!("cucc");
|
||||
}
|
||||
"error" => {
|
||||
if let Some(reason) = parsed.reason {
|
||||
println!("Error: {}", reason);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -141,11 +158,20 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
}
|
||||
"move" => {
|
||||
if parts.len() >= 3 {
|
||||
let from = parts[1].to_string();
|
||||
let to = parts[2].to_string();
|
||||
let message = ClientMessage::Move { from, to };
|
||||
//let from = parts[1].to_string();
|
||||
//let to = parts[2].to_string();
|
||||
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?;
|
||||
println!("♟️ Sent move: {} -> {}", parts[1], parts[2]);
|
||||
//println!("♟️ Sent move: {} -> {}", parts[1], parts[2]);
|
||||
} else {
|
||||
println!("Usage: move <from> <to> (e.g., move e2 e4)");
|
||||
}
|
||||
@@ -167,6 +193,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
"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!(
|
||||
"Unknown command: {}. Type 'help' for available commands.",
|
||||
@@ -204,5 +237,6 @@ fn print_help() {
|
||||
println!(" resign - Resign from current game");
|
||||
println!(" help - Show this help");
|
||||
println!(" quit - Exit the client");
|
||||
println!(" requestmoves - Request the legal moves");
|
||||
println!();
|
||||
}
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
use crate::connection::ClientEvent::*;
|
||||
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 serde::{Deserialize, Serialize};
|
||||
use std::char::from_u32_unchecked;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::sync::Arc;
|
||||
use tokio::net::TcpStream;
|
||||
@@ -13,6 +19,10 @@ pub type ConnectionMap = Arc<Mutex<HashMap<Uuid, PlayerConnection>>>;
|
||||
pub type MatchMap = Arc<Mutex<HashMap<Uuid, GameMatch>>>;
|
||||
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
|
||||
pub fn new_connection_map() -> ConnectionMap {
|
||||
Arc::new(Mutex::new(HashMap::new()))
|
||||
@@ -26,6 +36,53 @@ pub fn new_waiting_queue() -> WaitingQueue {
|
||||
Arc::new(Mutex::new(VecDeque::new()))
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct Step {
|
||||
pub from: String,
|
||||
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 {
|
||||
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 ClientEvent {
|
||||
Join { username: String },
|
||||
FindMatch,
|
||||
Move { step: ChessMove },
|
||||
Resign,
|
||||
Chat { text: String },
|
||||
RequestLegalMoves { fen: String },
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct PlayerConnection {
|
||||
pub id: Uuid,
|
||||
@@ -40,29 +97,24 @@ pub struct GameMatch {
|
||||
pub player_white: Uuid,
|
||||
pub player_black: Uuid,
|
||||
pub board_state: String,
|
||||
pub move_history: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct Step {
|
||||
pub from: String,
|
||||
pub to: String,
|
||||
pub move_history: Vec<Step>,
|
||||
}
|
||||
|
||||
// Message sending utilities
|
||||
pub async fn send_message_to_player(
|
||||
connections: &ConnectionMap,
|
||||
player_id: Uuid,
|
||||
pub async fn send_message_to_player_connection(
|
||||
connection: Option<&mut PlayerConnection>,
|
||||
message: &str,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut connections_lock = connections.lock().await;
|
||||
if let Some(connection) = connections_lock.get_mut(&player_id) {
|
||||
connection
|
||||
.tx
|
||||
.send(Message::Text(message.to_string()))
|
||||
.await?;
|
||||
) -> Result<(), tokio_tungstenite::tungstenite::Error> {
|
||||
match connection {
|
||||
Some(connection) => {
|
||||
println!("sending message to: {}", connection.id);
|
||||
connection.tx.send(Message::Text(message.to_string())).await
|
||||
}
|
||||
None => {
|
||||
eprintln!("No connection provided");
|
||||
Err(tokio_tungstenite::tungstenite::Error::ConnectionClosed)
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn broadcast_to_all(connections: &ConnectionMap, message: &str) {
|
||||
@@ -90,8 +142,16 @@ pub async fn broadcast_to_match(
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let matches_lock = matches.lock().await;
|
||||
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(connections, game_match.player_black, message).await?;
|
||||
send_message_to_player_connection(
|
||||
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(())
|
||||
}
|
||||
@@ -102,7 +162,6 @@ pub async fn handle_connection(
|
||||
connections: ConnectionMap,
|
||||
matches: MatchMap,
|
||||
waiting_queue: WaitingQueue,
|
||||
event_system: crate::events::EventSystem,
|
||||
) -> anyhow::Result<()> {
|
||||
use tokio_tungstenite::accept_async;
|
||||
|
||||
@@ -127,22 +186,170 @@ pub async fn handle_connection(
|
||||
|
||||
println!("New connection: {}", player_id);
|
||||
|
||||
// Send welcome message
|
||||
let _ = send_message_to_player(
|
||||
&connections,
|
||||
player_id,
|
||||
&format!(r#"{{"type": "welcome", "player_id": "{}"}}"#, player_id),
|
||||
)
|
||||
.await;
|
||||
|
||||
// Message processing loop
|
||||
while let Some(Ok(message)) = read.next().await {
|
||||
if message.is_text() {
|
||||
let text = message.to_text()?;
|
||||
println!("Received from {}: {}", player_id, text);
|
||||
|
||||
// TODO: Parse and handle message with event system
|
||||
// This will be implemented when we integrate the event system
|
||||
let client_data: ClientEvent = serde_json::from_str(text)
|
||||
.expect("Failed to convert data into json at handle_connection");
|
||||
|
||||
match client_data {
|
||||
Join { username } => {
|
||||
{
|
||||
let mut conn_map = connections.lock().await;
|
||||
let player = conn_map.get_mut(&player_id).unwrap();
|
||||
player.username = Some(username);
|
||||
}
|
||||
|
||||
//respone to client
|
||||
let response = ServerMessage2::Ok { response: Ok(()) };
|
||||
|
||||
let mut conn_map = connections.lock().await;
|
||||
let _ = send_message_to_player_connection(
|
||||
conn_map.get_mut(&player_id),
|
||||
&serde_json::to_string(&response).unwrap(),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
FindMatch => {
|
||||
let mut wait_queue = waiting_queue.lock().await;
|
||||
wait_queue.push_back(player_id.clone());
|
||||
println!("Appended {} to the waiting queue", player_id);
|
||||
println!("queue {:?}", wait_queue);
|
||||
}
|
||||
Move { step } => {
|
||||
let match_id = connections
|
||||
.lock()
|
||||
.await
|
||||
.get(&player_id)
|
||||
.unwrap()
|
||||
.current_match
|
||||
.unwrap();
|
||||
|
||||
{
|
||||
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,
|
||||
);
|
||||
}
|
||||
let message = ServerMessage2::UIUpdate {
|
||||
fen: matches
|
||||
.lock()
|
||||
.await
|
||||
.get(&match_id)
|
||||
.unwrap()
|
||||
.board_state
|
||||
.clone(),
|
||||
};
|
||||
|
||||
let _ = broadcast_to_match(
|
||||
&connections,
|
||||
&matches,
|
||||
match_id,
|
||||
&serde_json::to_string(&message).unwrap(),
|
||||
)
|
||||
.await;
|
||||
|
||||
{
|
||||
let is_game_end = engine::is_game_over(
|
||||
&matches.lock().await.get(&match_id).unwrap().board_state,
|
||||
);
|
||||
|
||||
match is_game_end {
|
||||
Some(res) => {
|
||||
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);
|
||||
}
|
||||
None => {
|
||||
println!("No winner match continues.")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
RequestLegalMoves { fen } => {
|
||||
let moves = get_available_moves(&fen);
|
||||
let _ = send_message_to_player_connection(
|
||||
connections.lock().await.get_mut(&player_id),
|
||||
&serde_json::to_string(&moves).unwrap(),
|
||||
)
|
||||
.await;
|
||||
println!("Sent moves to player: {}", player_id);
|
||||
}
|
||||
Resign => {
|
||||
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(),
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
broadcast_to_match(
|
||||
&connections,
|
||||
&matches,
|
||||
connections
|
||||
.lock()
|
||||
.await
|
||||
.get(&player_id)
|
||||
.unwrap()
|
||||
.current_match
|
||||
.unwrap(),
|
||||
&serde_json::to_string(&fuck).unwrap(),
|
||||
)
|
||||
.await;
|
||||
clean_up_match(&matches, fuck_id);
|
||||
}
|
||||
_ => {
|
||||
println!("Not known client event");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -178,8 +385,24 @@ mod tests {
|
||||
let connections = new_connection_map();
|
||||
let player_id = Uuid::new_v4();
|
||||
|
||||
let result = send_message_to_player(&connections, player_id, "test message").await;
|
||||
assert!(result.is_ok(), "Should handle missing player gracefully");
|
||||
// Test 1: Pass None directly (non-existent player)
|
||||
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]
|
||||
|
||||
@@ -1,126 +0,0 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::sync::mpsc;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct Step {
|
||||
pub from: String,
|
||||
pub to: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
#[serde(tag = "type")]
|
||||
pub enum ClientEvent {
|
||||
Join { username: String },
|
||||
FindMatch,
|
||||
Move { from: String, to: String },
|
||||
Resign,
|
||||
Chat { text: String },
|
||||
RequestLegalMoves { fen: String },
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ServerEvent {
|
||||
PlayerJoined(Uuid, String),
|
||||
PlayerLeft(Uuid),
|
||||
PlayerJoinedQueue(Uuid),
|
||||
PlayerJoinedMatch(Uuid, Uuid), // player_id, match_id
|
||||
PlayerMove(Uuid, Step),
|
||||
PlayerResigned(Uuid),
|
||||
MatchCreated(Uuid, Uuid, Uuid), // match_id, white_id, black_id
|
||||
}
|
||||
|
||||
pub struct EventSystem {
|
||||
sender: mpsc::UnboundedSender<(Uuid, ClientEvent)>,
|
||||
receiver: Arc<Mutex<mpsc::UnboundedReceiver<(Uuid, ClientEvent)>>>,
|
||||
}
|
||||
|
||||
impl Clone for EventSystem {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
sender: self.sender.clone(),
|
||||
receiver: Arc::clone(&self.receiver),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl EventSystem {
|
||||
pub fn new() -> Self {
|
||||
let (sender, receiver) = mpsc::unbounded_channel();
|
||||
Self {
|
||||
sender,
|
||||
receiver: Arc::new(Mutex::new(receiver)),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn send_event(
|
||||
&self,
|
||||
player_id: Uuid,
|
||||
event: ClientEvent,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
self.sender.send((player_id, event))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn next_event(&self) -> Option<(Uuid, ClientEvent)> {
|
||||
let mut receiver = self.receiver.lock().await;
|
||||
receiver.recv().await
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for EventSystem {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_event_system_send_and_receive() {
|
||||
let event_system = EventSystem::new();
|
||||
let player_id = Uuid::new_v4();
|
||||
|
||||
let join_event = ClientEvent::Join {
|
||||
username: "test_user".to_string(),
|
||||
};
|
||||
|
||||
let send_result = event_system.send_event(player_id, join_event).await;
|
||||
assert!(send_result.is_ok(), "Should send event successfully");
|
||||
|
||||
let received = event_system.next_event().await;
|
||||
assert!(received.is_some(), "Should receive sent event");
|
||||
|
||||
let (received_id, received_event) = received.unwrap();
|
||||
assert_eq!(received_id, player_id, "Should receive correct player ID");
|
||||
|
||||
match received_event {
|
||||
ClientEvent::Join { username } => {
|
||||
assert_eq!(username, "test_user", "Should receive correct username");
|
||||
}
|
||||
_ => panic!("Should receive Join event"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_event_system_clone() {
|
||||
let event_system1 = EventSystem::new();
|
||||
let event_system2 = event_system1.clone();
|
||||
|
||||
let player_id = Uuid::new_v4();
|
||||
let event = ClientEvent::FindMatch;
|
||||
|
||||
event_system1.send_event(player_id, event).await.unwrap();
|
||||
|
||||
let received = event_system2.next_event().await;
|
||||
assert!(
|
||||
received.is_some(),
|
||||
"Cloned event system should receive events"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
mod connection;
|
||||
mod events;
|
||||
mod matchmaking;
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
@@ -14,15 +13,11 @@ async fn main() -> anyhow::Result<()> {
|
||||
let matches = connection::new_match_map();
|
||||
let waiting_queue = connection::new_waiting_queue();
|
||||
|
||||
// Event system for communication between components
|
||||
let event_system = events::EventSystem::new();
|
||||
|
||||
// Start matchmaking background task
|
||||
let matchmaker = matchmaking::MatchmakingSystem::new(
|
||||
connections.clone(),
|
||||
matches.clone(),
|
||||
waiting_queue.clone(),
|
||||
event_system.clone(),
|
||||
);
|
||||
tokio::spawn(async move {
|
||||
matchmaker.run().await;
|
||||
@@ -33,17 +28,10 @@ async fn main() -> anyhow::Result<()> {
|
||||
let connections = connections.clone();
|
||||
let matches = matches.clone();
|
||||
let waiting_queue = waiting_queue.clone();
|
||||
let event_system = event_system.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = connection::handle_connection(
|
||||
stream,
|
||||
connections,
|
||||
matches,
|
||||
waiting_queue,
|
||||
event_system,
|
||||
)
|
||||
.await
|
||||
if let Err(e) =
|
||||
connection::handle_connection(stream, connections, matches, waiting_queue).await
|
||||
{
|
||||
eprintln!("Connection error: {}", e);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::connection::ServerMessage2;
|
||||
use crate::connection::{ConnectionMap, GameMatch, MatchMap, WaitingQueue};
|
||||
use crate::events::EventSystem;
|
||||
use rand::random;
|
||||
use uuid::Uuid;
|
||||
|
||||
@@ -7,31 +7,28 @@ pub struct MatchmakingSystem {
|
||||
connections: ConnectionMap,
|
||||
matches: MatchMap,
|
||||
waiting_queue: WaitingQueue,
|
||||
event_system: EventSystem,
|
||||
}
|
||||
|
||||
impl MatchmakingSystem {
|
||||
pub fn new(
|
||||
connections: ConnectionMap,
|
||||
matches: MatchMap,
|
||||
waiting_queue: WaitingQueue,
|
||||
event_system: EventSystem,
|
||||
) -> Self {
|
||||
pub fn new(connections: ConnectionMap, matches: MatchMap, waiting_queue: WaitingQueue) -> Self {
|
||||
Self {
|
||||
connections,
|
||||
matches,
|
||||
waiting_queue,
|
||||
event_system,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn run(&self) {
|
||||
loop {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn clean_up(&self, match_id: Uuid) {
|
||||
self.matches.lock().await.remove(&match_id);
|
||||
}
|
||||
|
||||
async fn try_create_match(&self) {
|
||||
let mut queue = self.waiting_queue.lock().await;
|
||||
|
||||
@@ -69,42 +66,54 @@ impl MatchmakingSystem {
|
||||
}
|
||||
|
||||
// Notify players
|
||||
println!(
|
||||
"Notifying player for a match: {:?} | {:?}",
|
||||
white_player, black_player
|
||||
);
|
||||
self.notify_players(white_player, black_player, match_id)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn notify_players(&self, white: Uuid, black: Uuid, match_id: Uuid) {
|
||||
let 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");
|
||||
let mut conn_map = self.connections.lock().await;
|
||||
|
||||
// Notify white player
|
||||
if let Some(_) = conn_map.get(&white) {
|
||||
let message = format!(
|
||||
r#"{{"type": "match_found", "match_id": "{}", "opponent": "{}", "color": "white"}}"#,
|
||||
match_id, black_name
|
||||
);
|
||||
let _ =
|
||||
crate::connection::send_message_to_player(&self.connections, white, &message).await;
|
||||
let message = ServerMessage2::MatchFound {
|
||||
match_id: match_id.clone(),
|
||||
color: String::from("white"),
|
||||
opponent_name: conn_map
|
||||
.get(&white)
|
||||
.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
|
||||
if let Some(_) = conn_map.get(&black) {
|
||||
let message = format!(
|
||||
r#"{{"type": "match_found", "match_id": "{}", "opponent": "{}", "color": "black"}}"#,
|
||||
match_id, white_name
|
||||
);
|
||||
let _ =
|
||||
crate::connection::send_message_to_player(&self.connections, black, &message).await;
|
||||
let message = ServerMessage2::MatchFound {
|
||||
match_id: match_id.clone(),
|
||||
color: String::from("black"),
|
||||
opponent_name: conn_map
|
||||
.get(&black)
|
||||
.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;
|
||||
}
|
||||
|
||||
println!("Match created: {} (white) vs {} (black)", white, black);
|
||||
@@ -114,7 +123,6 @@ impl MatchmakingSystem {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::events::EventSystem;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::connection::new_connection_map;
|
||||
@@ -126,14 +134,9 @@ mod tests {
|
||||
let connections = new_connection_map();
|
||||
let matches = new_match_map();
|
||||
let waiting_queue = new_waiting_queue();
|
||||
let event_system = EventSystem::new();
|
||||
|
||||
let matchmaking = MatchmakingSystem::new(
|
||||
connections.clone(),
|
||||
matches.clone(),
|
||||
waiting_queue.clone(),
|
||||
event_system.clone(),
|
||||
);
|
||||
let matchmaking =
|
||||
MatchmakingSystem::new(connections.clone(), matches.clone(), waiting_queue.clone());
|
||||
|
||||
let player1 = Uuid::new_v4();
|
||||
let player2 = Uuid::new_v4();
|
||||
@@ -172,14 +175,9 @@ mod tests {
|
||||
let connections = new_connection_map();
|
||||
let matches = new_match_map();
|
||||
let waiting_queue = new_waiting_queue();
|
||||
let event_system = EventSystem::new();
|
||||
|
||||
let matchmaking = MatchmakingSystem::new(
|
||||
connections.clone(),
|
||||
matches.clone(),
|
||||
waiting_queue.clone(),
|
||||
event_system.clone(),
|
||||
);
|
||||
let matchmaking =
|
||||
MatchmakingSystem::new(connections.clone(), matches.clone(), waiting_queue.clone());
|
||||
|
||||
let player1 = Uuid::new_v4();
|
||||
{
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
}
|
||||
4371
ui/Cargo.lock
generated
Normal file
4371
ui/Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
@@ -4,3 +4,7 @@ version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
eframe = "0.33.0"
|
||||
egui = "0.33.0"
|
||||
tokio-tungstenite = "0.28.0"
|
||||
winit = "0.30.12"
|
||||
|
||||
BIN
ui/fonts/DejaVuSans.ttf
Normal file
BIN
ui/fonts/DejaVuSans.ttf
Normal file
Binary file not shown.
432
ui/src/main.rs
432
ui/src/main.rs
@@ -1,3 +1,431 @@
|
||||
fn main() {
|
||||
println!("Hello, world!");
|
||||
use eframe::egui;
|
||||
|
||||
fn main() -> eframe::Result<()> {
|
||||
let options = eframe::NativeOptions{
|
||||
viewport: egui::ViewportBuilder::default()
|
||||
.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()))
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Debug)]
|
||||
enum Piece {
|
||||
King(char),
|
||||
Queen(char),
|
||||
Rook(char),
|
||||
Bishop(char),
|
||||
Knight(char),
|
||||
Pawn(char),
|
||||
Empty,
|
||||
}
|
||||
|
||||
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('b') => "♚",
|
||||
Piece::Queen('b') => "♛",
|
||||
Piece::Rook('b') => "♜",
|
||||
Piece::Bishop('b') => "♝",
|
||||
Piece::Knight('b') => "♞",
|
||||
Piece::Pawn('b') => "♟︎",
|
||||
Piece::Empty => "",
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Debug)]
|
||||
enum Turn {
|
||||
White,
|
||||
Black,
|
||||
}
|
||||
|
||||
enum AppState {
|
||||
MainMenu,
|
||||
InGame,
|
||||
Settings,
|
||||
}
|
||||
|
||||
struct ChessApp {
|
||||
fullscreen: bool,
|
||||
resolutions: Vec<(u32, u32)>,
|
||||
selected_resolution: usize,
|
||||
state: AppState,
|
||||
board: [[Piece; 8]; 8],
|
||||
selected: Option<(usize, usize)>,
|
||||
turn: Turn,
|
||||
pending_settings: PendingSettings,
|
||||
server_port: String,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct PendingSettings {
|
||||
fullscreen: bool,
|
||||
selected_resolution: usize,
|
||||
server_port: String,
|
||||
}
|
||||
|
||||
impl Default for ChessApp {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
fullscreen: true,
|
||||
resolutions: vec![
|
||||
(1280, 720),
|
||||
(1600, 900),
|
||||
(1920, 1080),
|
||||
(2560, 1440),
|
||||
(3840, 2160),
|
||||
(7680, 4320),
|
||||
],
|
||||
selected_resolution: 2, // Default to 1920x1080
|
||||
state: AppState::MainMenu,
|
||||
board: Self::starting_board(),
|
||||
selected: None,
|
||||
turn: Turn::White,
|
||||
pending_settings: PendingSettings::default(),
|
||||
server_port: "8080".to_string(), // Default port
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ChessApp {
|
||||
fn starting_board() -> [[Piece; 8]; 8] {
|
||||
use Piece::*;
|
||||
[
|
||||
[
|
||||
Rook('b'),
|
||||
Knight('b'),
|
||||
Bishop('b'),
|
||||
Queen('b'),
|
||||
King('b'),
|
||||
Bishop('b'),
|
||||
Knight('b'),
|
||||
Rook('b'),
|
||||
],
|
||||
[Pawn('b'); 8],
|
||||
[Empty; 8],
|
||||
[Empty; 8],
|
||||
[Empty; 8],
|
||||
[Empty; 8],
|
||||
[Pawn('w'); 8],
|
||||
[
|
||||
Rook('w'),
|
||||
Knight('w'),
|
||||
Bishop('w'),
|
||||
Queen('w'),
|
||||
King('w'),
|
||||
Bishop('w'),
|
||||
Knight('w'),
|
||||
Rook('w'),
|
||||
],
|
||||
]
|
||||
}
|
||||
|
||||
fn handle_click(&mut self, row: usize, col: usize) {
|
||||
if let Some((r, c)) = self.selected {
|
||||
let piece = self.board[r][c];
|
||||
self.board[r][c] = Piece::Empty;
|
||||
self.board[row][col] = piece;
|
||||
self.selected = None;
|
||||
self.turn = if self.turn == Turn::White {
|
||||
Turn::Black
|
||||
} else {
|
||||
Turn::White
|
||||
};
|
||||
} else {
|
||||
if self.board[row][col] != Piece::Empty {
|
||||
self.selected = Some((row, col));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_settings(&mut self, ctx: &egui::Context) {
|
||||
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::Fullscreen(self.fullscreen));
|
||||
}
|
||||
|
||||
fn enter_settings(&mut self) {
|
||||
self.pending_settings.fullscreen = self.fullscreen;
|
||||
self.pending_settings.selected_resolution = self.selected_resolution;
|
||||
self.pending_settings.server_port = self.server_port.clone();
|
||||
self.state = AppState::Settings;
|
||||
}
|
||||
}
|
||||
|
||||
impl eframe::App for ChessApp {
|
||||
fn update(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
|
||||
match self.state {
|
||||
AppState::MainMenu => {
|
||||
egui::CentralPanel::default().show(ctx, |ui| {
|
||||
ui.vertical_centered(|ui| {
|
||||
ui.heading("♞ Knightly ♞");
|
||||
ui.add_space(30.0);
|
||||
|
||||
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() {
|
||||
self.enter_settings();
|
||||
}
|
||||
ui.add_space(8.0);
|
||||
|
||||
if ui
|
||||
.add_sized([300.0, 60.0], egui::Button::new("Quit"))
|
||||
.clicked()
|
||||
{
|
||||
std::process::exit(0);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
AppState::Settings => {
|
||||
egui::CentralPanel::default().show(ctx, |ui| {
|
||||
ui.vertical_centered(|ui| {
|
||||
ui.heading("Settings");
|
||||
ui.add_space(30.0);
|
||||
|
||||
// Fullscreen toggle
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Fullscreen:");
|
||||
if ui.checkbox(&mut self.pending_settings.fullscreen, "").changed() {
|
||||
// If enabling fullscreen, we might want to disable resolution selection
|
||||
}
|
||||
});
|
||||
ui.add_space(10.0);
|
||||
|
||||
// Resolution dropdown
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Resolution:");
|
||||
egui::ComboBox::new("resolution_combo", "")
|
||||
.selected_text(format!(
|
||||
"{}x{}",
|
||||
self.resolutions[self.pending_settings.selected_resolution].0,
|
||||
self.resolutions[self.pending_settings.selected_resolution].1
|
||||
))
|
||||
.show_ui(ui, |ui| {
|
||||
for (i, &(width, height)) in self.resolutions.iter().enumerate() {
|
||||
ui.selectable_value(
|
||||
&mut self.pending_settings.selected_resolution,
|
||||
i,
|
||||
format!("{}x{}", width, height),
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.add_space(10.0);
|
||||
|
||||
// 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("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() {
|
||||
self.apply_settings(ctx);
|
||||
self.state = AppState::MainMenu;
|
||||
}
|
||||
|
||||
if ui.add_sized([140.0, 40.0], egui::Button::new("Cancel")).clicked() {
|
||||
self.state = AppState::MainMenu;
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
AppState::InGame => {
|
||||
egui::TopBottomPanel::top("menu_bar").show(ctx, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button("Main Menu").clicked() {
|
||||
self.state = AppState::MainMenu;
|
||||
}
|
||||
if ui.button("Settings").clicked() {
|
||||
self.enter_settings();
|
||||
}
|
||||
if ui.button("New Game").clicked() {
|
||||
*self = ChessApp::default();
|
||||
self.state = AppState::InGame;
|
||||
}
|
||||
ui.separator();
|
||||
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()
|
||||
);
|
||||
|
||||
let board_rect = egui::Rect::from_center_size(
|
||||
full_avail.center(),
|
||||
egui::vec2(board_size, board_size)
|
||||
);
|
||||
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn test_initial_board_setup() {
|
||||
let app = ChessApp::default();
|
||||
assert!(matches!(app.board[0][0], Piece::Rook('b')));
|
||||
assert!(matches!(app.board[7][0], Piece::Rook('w')));
|
||||
|
||||
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();
|
||||
app.handle_click(6, 0);
|
||||
assert_eq!(app.selected, Some((6, 0)));
|
||||
app.handle_click(6, 0);
|
||||
assert_eq!(app.selected, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_piece_movement() {
|
||||
let mut app = ChessApp::default();
|
||||
// Select and move a piece
|
||||
app.handle_click(6, 0); // Select white pawn
|
||||
app.handle_click(5, 0); // Move to empty square
|
||||
assert_eq!(app.board[6][0], Piece::Empty);
|
||||
assert!(matches!(app.board[5][0], Piece::Pawn('w')));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_turn_switching() {
|
||||
let mut app = ChessApp::default();
|
||||
assert_eq!(app.turn, Turn::White);
|
||||
app.handle_click(6, 0); // White selects
|
||||
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();
|
||||
assert_eq!(app.server_port, "8080");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user