Compare commits

..

143 Commits

Author SHA1 Message Date
Varga Dávid Lajos
ebcc447092 removed unused imports from chessmove.rs 2025-11-21 14:19:33 +01:00
Varga Dávid Lajos
a4982c0fd3 implemented conversion method to_bitmove for enum ChessMove 2025-11-21 14:18:23 +01:00
Varga Dávid Lajos
c414485891 implemented conversion method to_index for struct BoardSquare 2025-11-21 14:09:02 +01:00
Varga Dávid Lajos
f29298731b implemented conversion method to_index for enum PieceType 2025-11-21 14:07:27 +01:00
Varga Dávid Lajos
e1d51fe291 implemented conversion method to_bitmovetype for enum MoveType 2025-11-21 14:04:37 +01:00
Varga Dávid Lajos
f841fba080 implemented constructor from_bitmove for enum ChessMove 2025-11-21 13:55:07 +01:00
Varga Dávid Lajos
821746d7cf changed implementation of ChessMove from struct to enum 2025-11-21 13:29:01 +01:00
Varga Dávid Lajos
5d108602ea implemented constructor by square_index for struct BoardSquare 2025-11-21 13:08:53 +01:00
Varga Dávid Lajos
b137e6ceab implemented constructor by piece_index for enum PieceType 2025-11-21 13:01:38 +01:00
Varga Dávid Lajos
d649afdcfd limited visibility of method from_bitmovetype from enum MoveType to pub(in super) 2025-11-21 12:57:38 +01:00
Varga Dávid Lajos
5e65bcf5ef changed method from_index for enum MoveType to from_bitmovetype 2025-11-21 12:55:18 +01:00
Varga Dávid Lajos
82a6bd8449 implemented constructor for enum MoveType from in-engine move_type index 2025-11-21 12:40:24 +01:00
Hatvani Tamás
23c890f329 Merge pull request #20 from htamas1210/Engine/move-gen 2025-11-20 21:26:58 +01:00
vargadavidlajos
b91777a64f Merge branch 'master' into Engine/move-gen 2025-11-20 21:19:41 +01:00
Varga Dávid Lajos
775083fde7 fixed wrong promotion_piece indexes being saved in bitboard::movegen::pawns 2025-11-20 21:11:41 +01:00
Varga Dávid Lajos
84121fbeba allowed use of move generation methods in case of check 2025-11-20 20:45:26 +01:00
Varga Dávid Lajos
f3d316d3e3 implemented method collect_king_evasion in bitboard::movegen used in move generation 2025-11-20 20:43:35 +01:00
Varga Dávid Lajos
fad1a6d51b implemented method collect_moves_single_check in bitboard::movegen used in move generation 2025-11-20 20:42:44 +01:00
Varga Dávid Lajos
9b43c9ce9a implemented method collect_all_moves in bitboard::movegen used in move generation 2025-11-20 20:39:47 +01:00
Varga Dávid Lajos
dba7aca2cf added method get_safe_king_squares to bitboard::attacks for king safety checks 2025-11-20 20:35:44 +01:00
Varga Dávid Lajos
47a22dbbaa added method get_pseudo_rook_moves_ignore_king in bitboard::attacks for king safety checks 2025-11-20 20:29:27 +01:00
Varga Dávid Lajos
1bbe33f3aa added method get_pseudo_bishop_moves_ignore_king in bitboard::attacks for king safety checks 2025-11-20 20:28:16 +01:00
Varga Dávid Lajos
8c0fa09f1e added LUT KING_SAFETY_BISHOP_MASK in bitboard::attackmaps for king safety checks 2025-11-20 20:25:14 +01:00
Varga Dávid Lajos
d8eae9177b added LUT KING_SAFETY_ROOK_MASK in bitboard::attackmaps for king safety checks 2025-11-20 20:23:40 +01:00
Varga Dávid Lajos
71ea2a05d0 added LUT BISHOP_MOVE_MASK in bitboard::attackmaps for king safety checks 2025-11-20 20:22:08 +01:00
Varga Dávid Lajos
33ca535547 added LUT ROOK_MOVE_MASK in bitboard::attackmaps for king safety checks 2025-11-20 20:21:28 +01:00
Varga Dávid Lajos
08ba7ee436 implemented move generation method for castling moves 2025-11-20 12:41:20 +01:00
Varga Dávid Lajos
5b3e84dab0 implemented move generation method or king capture moves 2025-11-20 12:35:46 +01:00
Varga Dávid Lajos
21d26902f0 implemented general move generation methdod for kings 2025-11-20 12:33:58 +01:00
Varga Dávid Lajos
e9f7663488 added file and module structure for bitboard::movegen::kings 2025-11-20 12:28:46 +01:00
Varga Dávid Lajos
c2abc08206 implemented move generation method for queen capture moves 2025-11-20 12:27:31 +01:00
Varga Dávid Lajos
9fa298ed51 implemented general move generation method for queens 2025-11-20 12:26:16 +01:00
Varga Dávid Lajos
a51d5e2652 added file and module structure for bitboard::movegen::queens 2025-11-20 12:24:40 +01:00
Varga Dávid Lajos
0dd9a3d047 implemented move generation method for rook capture moves 2025-11-20 12:23:14 +01:00
Varga Dávid Lajos
e896aba4ec implemented general move generation method for rooks 2025-11-20 12:18:25 +01:00
Varga Dávid Lajos
9fb3d15bed added file and module structure for bitboard::movegen::rooks 2025-11-20 12:14:31 +01:00
Varga Dávid Lajos
35cb1eeb73 implemented move generation method for bishop capture moves 2025-11-19 21:13:05 +01:00
Varga Dávid Lajos
8165749845 implemented general move generation method for bishops 2025-11-19 21:11:39 +01:00
Varga Dávid Lajos
06cb2b88c2 added file and module structure for bitboard::movegen::bishops 2025-11-19 21:08:45 +01:00
Varga Dávid Lajos
2d646f0ad0 implemented move generation method for knight capture moves 2025-11-19 21:07:18 +01:00
Varga Dávid Lajos
40e2c50209 implemeneted general move generation method for knight moves 2025-11-19 21:05:58 +01:00
Varga Dávid Lajos
2e82a52f27 added file and module structure for bitboard::movegen::knights 2025-11-19 21:03:27 +01:00
Varga Dávid Lajos
372d86b451 changed signature utility functions utils::pop_lsb and utils::pop_msb to reduce unnecessary type conversions 2025-11-19 20:58:56 +01:00
Varga Dávid Lajos
d66787f51d implemented method to collect both quiet and capture moves for pawns 2025-11-19 20:54:01 +01:00
Varga Dávid Lajos
a4c63f19e5 implemented move generation method for pawn capture moves 2025-11-19 20:52:28 +01:00
Varga Dávid Lajos
a2f261778b implemented move generation method for pawn quiet moves 2025-11-19 20:47:44 +01:00
Varga Dávid Lajos
3f7cc2df4d added file and module structure for bitboard::movegen::pawns 2025-11-19 20:39:00 +01:00
Varga Dávid Lajos
48272d6d70 added skeleton for main move generation method to bitboard::movegen 2025-11-19 20:35:46 +01:00
Varga Dávid Lajos
d172afc50c re-added missing code for check tests from past branch 2025-11-19 20:32:12 +01:00
Varga Dávid Lajos
ee61528891 added file and module structure for bitboard::movegen.rs 2025-11-19 20:16:48 +01:00
Hatvani Tamás
0ace485bb6 Merge pull request #19 from htamas1210/Engine/movebuffer
Engine/movebuffer
2025-11-19 20:14:45 +01:00
Hatvani Tamás
1c1b9a96d9 Import time module and add sleep in data upload
Added time.sleep to control row insertion rate.
2025-11-19 17:34:44 +01:00
Hatvani Tamás
e99b2defa3 Merge pull request #18 from htamas1210/Engine/bitmove
Engine/bitmove
2025-11-19 17:10:03 +01:00
Varga Dávid Lajos
f39c113ef9 implemented method append for struct MoveBuffer 2025-11-19 16:13:34 +01:00
Varga Dávid Lajos
f417a7e47c implemented getter for field buffer i struct MoveBuffer 2025-11-19 16:09:31 +01:00
Varga Dávid Lajos
547b0e51cb corrected annotation for method clear in struct MoveBuffer 2025-11-19 16:00:09 +01:00
Varga Dávid Lajos
5340744abe implemented method clear for struct MoveBuffer 2025-11-19 15:56:57 +01:00
Varga Dávid Lajos
f64ebfa47f implemented method get for struct MoveBuffer 2025-11-19 15:53:39 +01:00
Varga Dávid Lajos
4e7ac2a195 added getter for field count in struct MoveBuffer 2025-11-19 15:50:03 +01:00
Varga Dávid Lajos
dc176c103b implemented method add for struct MoveBuffer 2025-11-19 15:40:11 +01:00
Varga Dávid Lajos
85a7fa37ef added parameterless constructor for struct MoveBuffer 2025-11-19 15:22:15 +01:00
Varga Dávid Lajos
a60658763d defined shape of struct MoveBuffer 2025-11-19 15:06:37 +01:00
Varga Dávid Lajos
b76a009e4e added file and module structure for movebuffer.rs 2025-11-19 14:57:36 +01:00
Varga Dávid Lajos
db333a693f added method uci_notation to struct BitMove 2025-11-18 17:38:48 +01:00
Varga Dávid Lajos
fd0d26486b switched from public fields to getters for struct BitMove 2025-11-18 17:30:04 +01:00
Varga Dávid Lajos
e1f4ae717e added constructor for castling moves in bitboard::bitmove.rs 2025-11-18 17:24:11 +01:00
Varga Dávid Lajos
7b9c1edbab added constructor for capture moves in bitboard::bitmove.rs 2025-11-18 17:23:07 +01:00
Varga Dávid Lajos
05294a7736 changed name of value of enum BitMoveType to align with Rust naming conventions 2025-11-18 17:20:40 +01:00
Varga Dávid Lajos
d8da808580 added enum BitMoveType to bitboard::bitmove.rs for readability 2025-11-18 17:19:31 +01:00
Varga Dávid Lajos
c420d8b3dd added constructor for quiet moves in bitboard::bitmove.rs 2025-11-18 17:17:11 +01:00
Varga Dávid Lajos
57af3aaae3 defined shape of struct bitboard::bitmove::BitMove 2025-11-18 17:09:39 +01:00
Varga Dávid Lajos
887b9abed8 adde file and module structure for bitboard::bitmove.rs 2025-11-18 17:02:07 +01:00
vargadavidlajos
a862d31c7d Merge pull request #17 from htamas1210/Server/event
Server/event
2025-11-18 16:58:29 +01:00
48f66aac75 added engine as a crate into server project, implemented request moves event 2025-11-18 16:43:14 +01:00
Hatvani Tamás
431c65e075 Merge pull request #16 from htamas1210/Engine/check-test
Engine/check test
2025-11-18 16:41:49 +01:00
Varga Dávid Lajos
7e64a7ca16 fixed incorrect test parameter in bitboard::legality::tests::check_test_test 2025-11-18 16:20:42 +01:00
Varga Dávid Lajos
6e0efc76f3 added missing method place_piece to struct bitboard::Board 2025-11-18 16:18:19 +01:00
Varga Dávid Lajos
1a9d7ad460 added tests for method bitboard::legality::check_test 2025-11-18 16:15:28 +01:00
6dfe92f211 Merge branch 'master' into Server/event 2025-11-18 16:12:07 +01:00
Varga Dávid Lajos
9209f1c4e0 implemented method check_test in bitboard::checktest.rs 2025-11-18 12:14:22 +01:00
4bb485e833 added findmatch event 2025-11-18 09:28:07 +01:00
Bence
3ebfc61ac7 Merge pull request #15 from htamas1210/Engine/library-functions
Engine/library functions
2025-11-17 15:04:28 +01:00
Hatvani Tamás
d8d8b58ed7 Uploaded presentation for class 2025-11-17 12:24:42 +01:00
Varga Dávid Lajos
a8970053f9 added constructor for castling moves in chessmove.rs 2025-11-16 19:05:52 +01:00
vargadavidlajos
7cd77ab904 Merge pull request #14 from htamas1210/Docs/kovspec
Added point 3 to kovspec.md
2025-11-16 19:05:07 +01:00
Varga Dávid Lajos
fa0a93172d added constructore for captures in chessmove.rs 2025-11-16 19:01:53 +01:00
Varga Dávid Lajos
bb74a486d8 added constructor for quiet moves in chessmove.rs 2025-11-16 19:00:00 +01:00
vargadavidlajos
10c176a0f5 Added point 3 to kovspec.md 2025-11-16 18:39:48 +01:00
Varga Dávid Lajos
d1932762f9 removed field is_promotion from struct ChessMove and added an Option for field promotion_piece 2025-11-16 18:33:04 +01:00
Varga Dávid Lajos
9181b6c4ca added all arguments constructor for struct BoardSquare 2025-11-16 13:51:10 +01:00
Varga Dávid Lajos
b703d8b9a1 added parameterless constructor for struct BoardSquare 2025-11-16 13:44:41 +01:00
Varga Dávid Lajos
acaa7d078a added new library function: get_board_after_move 2025-11-15 20:40:58 +01:00
Varga Dávid Lajos
30448b5f3d switched return type of is_game_over from bool to GameEnd 2025-11-15 20:37:06 +01:00
Varga Dávid Lajos
ff38c5c475 added struct GameEnd 2025-11-15 20:28:33 +01:00
Varga Dávid Lajos
42daeb9971 added file and module structure for gameend.rs 2025-11-15 20:15:17 +01:00
Bence
fc7ece9e94 Fixed app not starting in fullscreen 2025-11-15 20:09:26 +01:00
Varga Dávid Lajos
c8b6bc35d5 added library functions: get_available_moves and is_game_over 2025-11-15 20:08:54 +01:00
Varga Dávid Lajos
5f2a4e1721 added struct ChessMove 2025-11-15 19:57:11 +01:00
c77e534ed8 removed event system file as it was unused and we do not neet it anymore 2025-11-15 19:41:48 +01:00
Varga Dávid Lajos
5c42b6e52a added enum MoveType 2025-11-15 19:37:30 +01:00
Varga Dávid Lajos
f7364e7939 added file and module structure for movetype.rs 2025-11-15 19:35:17 +01:00
1c92918692 finished join event 2025-11-15 19:33:40 +01:00
Varga Dávid Lajos
b4a1f0820f added struct BoardSquare 2025-11-15 19:26:21 +01:00
Varga Dávid Lajos
6d9d5c49ae added file and module structure for boardsquare.rs 2025-11-15 19:24:37 +01:00
Varga Dávid Lajos
1ca44b472b added enum PieceType 2025-11-15 19:21:46 +01:00
Varga Dávid Lajos
79aabeac8c added file and module structure for piecetype.rs 2025-11-15 19:17:50 +01:00
Varga Dávid Lajos
5eb85dab89 added file and module structure for file: chessmove.rs 2025-11-15 19:15:30 +01:00
Varga Dávid Lajos
291b7e71a2 added crate root file lib.rs for library crate 2025-11-15 19:14:08 +01:00
vargadavidlajos
2aaa2aca70 Merge pull request #13 from htamas1210/UI/SettingsAndGame
Created a new branch due to a bug
2025-11-15 19:11:39 +01:00
Bence
456d386551 Created a new branch due to a bug
Previous pull request didn't work (didnt change ui/src/main.rs), created new branch to see if the problem persists
2025-11-15 19:06:25 +01:00
cca852d466 Working on event system, join implemented 2025-11-15 18:32:43 +01:00
Hatvani Tamás
e663d61b9e Merge pull request #11 from htamas1210/Engine/pseudo-moves
Engine/pseudo moves
2025-11-15 18:05:17 +01:00
a098c8051a planning done on how the event system works 2025-11-15 16:41:11 +01:00
Hatvani Tamás
c3ed181b07 Merge pull request #10 from htamas1210/Engine/legality-checks
Engine/legality checks
2025-11-15 15:03:38 +01:00
Hatvani Tamás
5b3f2488d4 Merge pull request #9 from htamas1210/Engine/board-repr
Engine/board repr
2025-11-15 14:53:07 +01:00
Varga Dávid Lajos
659413ca31 implemented pseudo-move generation for queens 2025-11-15 13:47:46 +01:00
Varga Dávid Lajos
4de505bc21 implemented pseudo-move generation for rooks 2025-11-15 13:47:03 +01:00
Varga Dávid Lajos
7c58f0d508 implemented pseudo-move generation for bishops 2025-11-15 13:46:11 +01:00
Varga Dávid Lajos
c9246d1342 added helper function: get_raycast_from_square_in_direction 2025-11-15 13:45:01 +01:00
Varga Dávid Lajos
eab795b6df implemented pseudo-move generation for pawn captures 2025-11-15 13:43:37 +01:00
Varga Dávid Lajos
f8ab14a026 implemented pseudo-move generation for kings 2025-11-15 13:42:41 +01:00
Varga Dávid Lajos
274897a070 implemented pseudo-move generation for knights 2025-11-15 13:41:40 +01:00
Varga Dávid Lajos
8ecbeb9c41 implemented pseudo-move generation for pawn moves 2025-11-15 13:40:40 +01:00
Varga Dávid Lajos
a1482d11f2 added file and module structure for bitboard::attacks.rs 2025-11-15 13:38:48 +01:00
Varga Dávid Lajos
f9a302c9a0 implemented method add_checker for CheckInfo in bitboard::checkinfo.rs 2025-11-15 12:40:52 +01:00
Varga Dávid Lajos
ad530e9155 added constructor for struct CheckInfo in bitboard::checkinfo.rs 2025-11-15 12:39:35 +01:00
Varga Dávid Lajos
182aa59ee1 defined shape of struct CheckInfo in bitboard::checkinfo.rs 2025-11-15 12:37:47 +01:00
Varga Dávid Lajos
296f1f6c3a added file and module structure for checkinfo.rs 2025-11-15 12:36:11 +01:00
Varga Dávid Lajos
f7355f8e74 implemented use of calc_pinned_squares in board.rs 2025-11-15 12:33:18 +01:00
Varga Dávid Lajos
cd58a7a321 added methods for detecting pinned pieces 2025-11-15 12:30:01 +01:00
Varga Dávid Lajos
2beb8ab303 added file and module structure for bitboard::legality.rs 2025-11-15 10:31:02 +01:00
Varga Dávid Lajos
5425ccc5cd added partial constructor for starting from a fen position 2025-11-15 10:26:31 +01:00
Varga Dávid Lajos
1104c8e6c5 added helper method for fen parsing to utils.rs 2025-11-15 10:21:00 +01:00
Varga Dávid Lajos
274ffcf5ec added method to get the current square of a king 2025-11-15 10:14:37 +01:00
Varga Dávid Lajos
5854dbc20b set each field to pub(in super) for later use 2025-11-15 10:12:52 +01:00
Varga Dávid Lajos
f36a196b2f added getters for fields 2025-11-15 10:11:34 +01:00
Varga Dávid Lajos
11f26809df used calc_occupancy and calc_piece_board methods in the initial state constructor 2025-11-15 10:07:23 +01:00
Varga Dávid Lajos
c88fbe68e3 added and used necessary methods the initial state constructor 2025-11-15 10:06:12 +01:00
Varga Dávid Lajos
7f4c53ddb7 added partial constructor for initial board state to board.rs 2025-11-15 10:03:24 +01:00
Varga Dávid Lajos
38b38845d6 added constructor for clear board to board.rs 2025-11-15 09:58:38 +01:00
Varga Dávid Lajos
66dd2877b2 defined board representation shape in board.rs 2025-11-15 09:56:17 +01:00
Varga Dávid Lajos
3cd53c7d70 added file and module structure for board representation 2025-11-15 09:51:07 +01:00
Bence
5b3bdc750f Merge pull request #8 from htamas1210/Server/websocket
Server/websocket
2025-11-13 19:12:00 +01:00
36 changed files with 6530 additions and 199 deletions

View File

@@ -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:

View File

@@ -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
- Kliensszerver 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 kliensszerver architektúrán alapul, ahol az egyes komponensek jól elkülönülten, meghatározott feladatokat látnak el.

BIN
Knightly prezentáció.pptx Normal file

Binary file not shown.

View File

@@ -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"

View File

@@ -1,2 +1,10 @@
mod attackmaps;
mod utils;
mod utils;
mod legality;
mod checkinfo;
mod attacks;
mod movebuffer;
mod movegen;
pub mod board;
pub(in super) mod bitmove;

View File

@@ -94,6 +94,64 @@ pub static RAY_TABLE: Lazy<[[u64; 8]; 64]> = Lazy::new(|| {
return table;
});
// ROOK_MOVE_MASK[<square_index>]
pub static ROOK_MOVE_MASK: Lazy<[u64; 64]> = Lazy::new(|| {
let mut table = [0u64; 64];
for sq in 0..64 {
for dir in [0, 2, 4, 6] {
table[sq] |= RAY_TABLE[sq][dir];
}
}
table
});
// BISHOP_MOVE_MASK[<square_index>]
pub static BISHOP_MOVE_MASK: Lazy<[u64; 64]> = Lazy::new(|| {
let mut table = [0u64; 64];
for sq in 0..64 {
for dir in [1, 3, 5, 7] {
table[sq] |= RAY_TABLE[sq][dir];
}
}
table
});
// KING_SAFETY_ROOK_MASK[<square_index>]
pub static KING_SAFETY_ROOK_MASK: Lazy<[u64; 64]> = Lazy::new(|| {
let mut table = [0u64; 64];
for sq in 0..64 {
let mut mask = KING_ATTACK_MAP[sq];
while mask != 0 {
let next_sq = mask.trailing_zeros();
table[sq] |= ROOK_MOVE_MASK[next_sq as usize];
mask &= !(1 << next_sq);
}
}
table
});
// KING_SAFETY_BISHOP_MASK[<square_index>]
pub static KING_SAFETY_BISHOP_MASK: Lazy<[u64; 64]> = Lazy::new(|| {
let mut table = [0u64; 64];
for sq in 0..64 {
let mut mask = KING_ATTACK_MAP[sq];
while mask != 0 {
let next_sq = mask.trailing_zeros();
table[sq] |= BISHOP_MOVE_MASK[next_sq as usize];
mask &= !(1 << next_sq);
}
}
table
});
// <----- TESTS ----->

View File

@@ -0,0 +1,196 @@
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;
const A_FILE: u64 = 0x0101_0101_0101_0101;
const H_FILE: u64 = 0x8080_8080_8080_8080;
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]
pub fn get_pseudo_bishop_moves_ignore_king(&self, sq: u32) -> u64 {
let mut moves = 0u64;
let sq = sq as usize;
let king = self.bitboards[5 + 6*self.side_to_move as usize];
let occupancy = self.occupancy[2] & !king;
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_ignore_king(&self, sq: u32) -> u64 {
let mut moves: u64 = 0u64;
let sq = sq as usize;
let king = self.bitboards[5 + 6*self.side_to_move as usize];
let occupancy = self.occupancy[2] & !king;
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]
pub fn is_square_attacked(&self, king_sq: u32) -> bool {
let offset: usize = 6 * self.side_to_move as usize;
// rook-queen checks (+)
let mut threat_mask: u64 = self.get_pseudo_rook_moves(king_sq);
let mut attacker_mask: u64 = self.bitboards[10 - offset] | self.bitboards[9 - offset];
if threat_mask & attacker_mask != 0 { return true; }
// bishop-queen checks (x)
threat_mask = self.get_pseudo_bishop_moves(king_sq);
attacker_mask = self.bitboards[10 - offset] | self.bitboards[8 - offset];
if threat_mask & attacker_mask != 0 { return true; }
// knight checks (L)
threat_mask = KNIGHT_ATTACK_MAP[king_sq as usize];
attacker_mask = self.bitboards[7 - offset];
if threat_mask & attacker_mask != 0 { return true; }
// pawn checks (v)
threat_mask = PAWN_ATTACK_MAP[king_sq as usize][self.side_to_move as usize];
attacker_mask = self.bitboards[6 - offset];
return threat_mask & attacker_mask != 0;
}
pub fn get_safe_king_squares(&self) -> u64 {
let offset: usize = 6 * (1 - self.side_to_move as usize);
let king_sq = self.bitboards[11 - offset].trailing_zeros() as usize;
let bishop_mask = KING_SAFETY_BISHOP_MASK[king_sq];
let rook_mask = KING_SAFETY_ROOK_MASK[king_sq];
let mut attack_map: u64 = 0u64;
let mut board: u64 = self.bitboards[offset];
if self.side_to_move() == 0 {
attack_map |= (board >> 9 & !Self::H_FILE) | (board >> 7 & !Self::A_FILE);
}
else {
attack_map |= (board << 9 & !Self::A_FILE) | (board << 7 & !Self::H_FILE);
}
board = self.bitboards[offset + 1];
while board != 0 {
let piece_sq: u32 = board.trailing_zeros();
board &= !(1 << piece_sq);
attack_map |= self.get_pseudo_knight_moves(piece_sq);
}
board = self.bitboards[offset + 2] & bishop_mask;
while board != 0 {
let piece_sq: u32 = board.trailing_zeros();
board &= !(1 << piece_sq);
attack_map |= self.get_pseudo_bishop_moves_ignore_king(piece_sq);
}
board = self.bitboards[offset + 3] & rook_mask;
while board != 0 {
let piece_sq: u32 = board.trailing_zeros();
board &= !(1 << piece_sq);
attack_map |= self.get_pseudo_rook_moves_ignore_king(piece_sq);
}
board = self.bitboards[offset + 4] & (bishop_mask | rook_mask);
while board != 0 {
let piece_sq: u32 = board.trailing_zeros();
board &= !(1 << piece_sq);
attack_map |= self.get_pseudo_rook_moves_ignore_king(piece_sq) | self.get_pseudo_bishop_moves_ignore_king(piece_sq);
}
board = self.bitboards[offset + 5];
let piece_sq: u32 = board.trailing_zeros();
attack_map |= self.get_pseudo_king_moves(piece_sq);
return !attack_map;
}
}
#[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;
}

View 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(&notation_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
}

View 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}
_ => ()
}
}
}

View 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;
}
}

View File

@@ -0,0 +1,134 @@
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;
}
}
}
#[inline]
pub(in super) fn get_pin_masked_moves(&self, moves: u64, sq: u32) -> u64 {
let sq: usize = sq as usize;
if self.pinned_squares[sq] == 4 { return moves; }
let dir: u8 = self.pinned_squares[sq];
return moves & (RAY_TABLE[sq][dir as usize] | RAY_TABLE[sq][4 + dir as usize]);
}
}
// <----- 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);
}
}
}

View 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];
}
}

View File

@@ -0,0 +1,67 @@
mod pawns;
mod knights;
mod bishops;
mod rooks;
mod queens;
mod kings;
use super::board::Board;
use super::movebuffer::MoveBuffer;
use super::bitmove::BitMove;
use super::checkinfo::CheckInfo;
use super::utils::*;
impl Board {
const NO_FILTER: u64 = 0xFFFF_FFFF_FFFF_FFFF;
pub fn collect_moves(&mut self, buffer: &mut MoveBuffer, temp_buffer: &mut MoveBuffer) -> bool {
buffer.clear();
self.calc_pinned_squares();
let check_info = self.check_test();
match check_info.check_count {
0 => self.collect_all_moves(buffer, temp_buffer),
1 => self.collect_moves_single_check(buffer, temp_buffer, &check_info),
2 => self.collect_king_evasion(buffer, temp_buffer),
_ => panic!("More than 2 checking pieces found as the same time!")
}
return check_info.check_count > 0;
}
pub(in super) fn collect_all_moves(&self, buffer: &mut MoveBuffer, temp_buffer: &mut MoveBuffer) {
let safe_squares = self.get_safe_king_squares();
self.add_pawn_moves(buffer, temp_buffer, Self::NO_FILTER);
self.add_knight_moves(buffer, temp_buffer, Self::NO_FILTER);
self.add_bishop_moves(buffer, temp_buffer, Self::NO_FILTER);
self.add_rook_moves(buffer, temp_buffer, Self::NO_FILTER);
self.add_queen_moves(buffer, temp_buffer, Self::NO_FILTER);
self.add_king_moves(buffer, temp_buffer, safe_squares);
self.add_king_castles(buffer, safe_squares);
buffer.append(temp_buffer);
temp_buffer.clear();
}
pub(in super) fn collect_moves_single_check(&self, buffer: &mut MoveBuffer, temp_buffer: &mut MoveBuffer, check_info: &CheckInfo) {
let safe_squares = self.get_safe_king_squares();
self.add_pawn_moves(buffer, temp_buffer, check_info.move_mask);
self.add_knight_moves(buffer, temp_buffer, check_info.move_mask);
self.add_bishop_moves(buffer, temp_buffer, check_info.move_mask);
self.add_rook_moves(buffer, temp_buffer, check_info.move_mask);
self.add_queen_moves(buffer, temp_buffer, check_info.move_mask);
self.add_king_moves(buffer, temp_buffer, safe_squares);
buffer.append(temp_buffer);
temp_buffer.clear();
}
pub(in super) fn collect_king_evasion(&self, buffer: &mut MoveBuffer, temp_buffer: &mut MoveBuffer) {
let safe_squares = self.get_safe_king_squares();
self.add_king_moves(buffer, temp_buffer, safe_squares);
buffer.append(&temp_buffer);
temp_buffer.clear();
}
}

View File

@@ -0,0 +1,55 @@
use super::*;
impl Board {
pub fn add_bishop_moves(&self, capture_buffer: &mut MoveBuffer, quiet_buffer: &mut MoveBuffer, move_mask: u64) {
let piece_index = 2 + self.side_to_move * 6;
let mut bishops = self.bitboards[piece_index as usize];
let empty = !self.occupancy[2];
let opponents = self.occupancy[1 - self.side_to_move as usize];
while bishops != 0 {
let from_sq = pop_lsb(&mut bishops);
let raw_move_map = self.get_pseudo_bishop_moves(from_sq) & move_mask;
let move_map = self.get_pin_masked_moves(raw_move_map, from_sq);
let mut quiet_map = move_map & empty;
let mut capture_map = move_map & opponents;
while quiet_map != 0 {
let to_sq = pop_lsb(&mut quiet_map);
quiet_buffer.add(BitMove::quiet(
from_sq as u8,
to_sq as u8,
None
));
}
while capture_map != 0 {
let to_sq = pop_lsb(&mut capture_map);
capture_buffer.add(BitMove::capture(
from_sq as u8,
to_sq as u8,
None
));
}
}
}
pub fn add_bishop_captures(&self, buffer: &mut MoveBuffer, move_mask: u64) {
let offset = 6 * self.side_to_move as usize;
let mut bishops: u64 = self.bitboards[2 + offset];
let opponents = self.occupancy[1 - self.side_to_move as usize];
while bishops != 0 {
let next_sq: u32 = pop_lsb(&mut bishops);
let mut attacks: u64 = self.get_pseudo_bishop_moves(next_sq) & opponents & move_mask;
attacks = self.get_pin_masked_moves(attacks, next_sq);
while attacks != 0 {
let to_sq = pop_lsb(&mut attacks);
buffer.add(BitMove::capture(
next_sq as u8,
to_sq as u8,
None
));
}
}
}
}

View File

@@ -0,0 +1,88 @@
use super::*;
impl Board {
pub fn add_king_moves(&self, capture_buffer: &mut MoveBuffer, quiet_buffer: &mut MoveBuffer, move_mask: u64) {
let piece_index = 5 + self.side_to_move * 6;
let mut kings = self.bitboards[piece_index as usize];
let empty = !self.occupancy[2];
let opponents = self.occupancy[1 - self.side_to_move as usize];
while kings != 0 {
let from_sq = pop_lsb(&mut kings);
let move_map = self.get_pseudo_king_moves(from_sq) & move_mask;
let mut quiet_map = move_map & empty;
let mut capture_map = move_map & opponents;
while quiet_map != 0 {
let to_sq = pop_lsb(&mut quiet_map);
quiet_buffer.add(BitMove::quiet(
from_sq as u8,
to_sq as u8,
None
));
}
while capture_map != 0 {
let to_sq = pop_lsb(&mut capture_map);
capture_buffer.add(BitMove::capture(
from_sq as u8,
to_sq as u8,
None
));
}
}
}
pub fn add_king_captures(&self, buffer: &mut MoveBuffer, move_mask: u64) {
let offset = 6 * self.side_to_move as usize;
let mut kings: u64 = self.bitboards[5 + offset];
let opponents = self.occupancy[1 - self.side_to_move as usize];
while kings != 0 {
let next_sq: u32 = pop_lsb(&mut kings);
let mut attacks: u64 = self.get_pseudo_king_moves(next_sq) & opponents & move_mask;
attacks = self.get_pin_masked_moves(attacks, next_sq);
while attacks != 0 {
let to_sq = pop_lsb(&mut attacks);
buffer.add(BitMove::capture(
next_sq as u8,
to_sq as u8,
None
));
}
}
}
pub fn add_king_castles(&self, buffer: &mut MoveBuffer, move_mask: u64) {
if self.castling_rights & (0b11 << (2 - 2 * self.side_to_move)) == 0 {
return;
}
let offset = 5 + 6 * self.side_to_move as u8;
let castle_offset = 2 - 2 * self.side_to_move as u8;
let castling_rights = self.castling_rights & 3 << castle_offset;
let occupied = self.occupancy[2];
let king_sq = self.bitboards[offset as usize].trailing_zeros();
let queenside_mask = 0b111 << (king_sq - 3);
let kingside_mask = 0b11 << (king_sq + 1);
if (castling_rights & 1 << castle_offset) != 0
&& queenside_mask & occupied == 0
&& !move_mask & 0b11 << (king_sq - 2) == 0
&& !self.is_square_attacked(king_sq - 2) {
buffer.add(BitMove::castle(
king_sq as u8,
(king_sq - 2) as u8
));
}
if (castling_rights & 2 << castle_offset) != 0
&& kingside_mask & occupied == 0
&& !move_mask & 0b11 << (king_sq + 1) == 0
&& !self.is_square_attacked(king_sq + 2) {
buffer.add(BitMove::castle(
king_sq as u8,
(king_sq + 2) as u8
));
}
}
}

View File

@@ -0,0 +1,55 @@
use super::*;
impl Board {
pub fn add_knight_moves(&self, capture_buffer: &mut MoveBuffer, quiet_buffer: &mut MoveBuffer, move_mask: u64) {
let piece_index = 1 + self.side_to_move * 6;
let mut knights = self.bitboards[piece_index as usize];
let empty = !self.occupancy[2];
let opponents = self.occupancy[1 - self.side_to_move as usize];
while knights != 0 {
let from_sq = pop_lsb(&mut knights);
let raw_move_map = self.get_pseudo_knight_moves(from_sq) & move_mask;
let move_map = self.get_pin_masked_moves(raw_move_map, from_sq);
let mut quiet_map = move_map & empty;
let mut capture_map = move_map & opponents;
while quiet_map != 0 {
let to_sq = pop_lsb(&mut quiet_map);
quiet_buffer.add(BitMove::quiet(
from_sq as u8,
to_sq as u8,
None
));
}
while capture_map != 0 {
let to_sq = pop_lsb(&mut capture_map);
capture_buffer.add(BitMove::capture(
from_sq as u8,
to_sq as u8,
None
));
}
}
}
pub fn add_knight_captures(&self, buffer: &mut MoveBuffer, move_mask: u64) {
let offset = 6 * self.side_to_move as usize;
let mut knights: u64 = self.bitboards[1 + offset];
let opponents = self.occupancy[1 - self.side_to_move as usize];
while knights != 0 {
let next_sq: u32 = pop_lsb(&mut knights);
let mut attacks: u64 = self.get_pseudo_knight_moves(next_sq) & opponents & move_mask;
attacks = self.get_pin_masked_moves(attacks, next_sq);
while attacks != 0 {
let to_sq = pop_lsb(&mut attacks);
buffer.add(BitMove::capture(
next_sq as u8,
to_sq as u8,
None
));
}
}
}
}

View File

@@ -0,0 +1,76 @@
use super::*;
impl Board {
pub fn add_pawn_quiets(&self, buffer: &mut MoveBuffer, move_mask: u64) {
let offset: u8 = self.side_to_move * 6;
let mut pawns: u64 = self.bitboards[offset as usize];
while pawns != 0 {
let next_sq = pop_lsb(&mut pawns);
let mut quiets: u64 = self.get_pseudo_pawn_moves(next_sq) & move_mask;
quiets = self.get_pin_masked_moves(quiets, next_sq);
while quiets != 0 {
let to_sq = quiets.trailing_zeros();
if (self.side_to_move == 0 && quiets.trailing_zeros() / 8 == 7)
|| (self.side_to_move == 1 && quiets.trailing_zeros() / 8 == 0) {
for piece_type in [4, 3, 2, 1] {
buffer.add(BitMove::quiet(
next_sq as u8,
to_sq as u8,
Some(piece_type)
));
}
}
else {
buffer.add(BitMove::quiet(
next_sq as u8,
to_sq as u8,
None
));
}
quiets &= !(1 << to_sq);
}
}
}
pub fn add_pawn_captures(&self, buffer: &mut MoveBuffer, move_mask: u64) {
let offset = 6 * self.side_to_move as usize;
let mut pawns: u64 = self.bitboards[offset];
let opponents = self.occupancy[1 - self.side_to_move as usize];
while pawns != 0 {
let next_sq = pop_lsb(&mut pawns);
let mut attacks: u64 = self.get_pseudo_pawn_captures(next_sq) & move_mask;
attacks = self.get_pin_masked_moves(attacks, next_sq);
attacks &= opponents;
while attacks != 0 {
let to_sq = attacks.trailing_zeros();
if (self.side_to_move == 0 && attacks.trailing_zeros() / 8 == 7)
|| (self.side_to_move == 1 && attacks.trailing_zeros() / 8 == 0) {
for piece_type in [4, 3, 2, 1] {
buffer.add(BitMove::capture(
next_sq as u8,
to_sq as u8,
Some(piece_type)
));
}
}
else {
buffer.add(BitMove::capture(
next_sq as u8,
to_sq as u8,
None
));
}
attacks &= !(1 << to_sq);
}
}
}
pub fn add_pawn_moves(&self, capture_buffer: &mut MoveBuffer, quiet_buffer: &mut MoveBuffer, move_mask: u64) {
self.add_pawn_captures(capture_buffer, move_mask);
self.add_pawn_quiets(quiet_buffer, move_mask);
}
}

View File

@@ -0,0 +1,55 @@
use super::*;
impl Board {
pub fn add_queen_moves(&self, capture_buffer: &mut MoveBuffer, quiet_buffer: &mut MoveBuffer, move_mask: u64) {
let piece_index = 4 + self.side_to_move * 6;
let mut queens = self.bitboards[piece_index as usize];
let empty = !self.occupancy[2];
let opponents = self.occupancy[1 - self.side_to_move as usize];
while queens != 0 {
let from_sq = pop_lsb(&mut queens);
let raw_move_map = self.get_pseudo_queen_moves(from_sq) & move_mask;
let move_map = self.get_pin_masked_moves(raw_move_map, from_sq);
let mut quiet_map = move_map & empty;
let mut capture_map = move_map & opponents;
while quiet_map != 0 {
let to_sq = pop_lsb(&mut quiet_map);
quiet_buffer.add(BitMove::quiet(
from_sq as u8,
to_sq as u8,
None
));
}
while capture_map != 0 {
let to_sq = pop_lsb(&mut capture_map);
capture_buffer.add(BitMove::capture(
from_sq as u8,
to_sq as u8,
None
));
}
}
}
pub fn add_queen_captures(&self, buffer: &mut MoveBuffer, move_mask: u64) {
let offset = 6 * self.side_to_move as usize;
let mut queens: u64 = self.bitboards[4 + offset];
let opponents = self.occupancy[1 - self.side_to_move as usize];
while queens != 0 {
let next_sq: u32 = pop_lsb(&mut queens);
let mut attacks: u64 = self.get_pseudo_queen_moves(next_sq) & opponents & move_mask;
attacks = self.get_pin_masked_moves(attacks, next_sq);
while attacks != 0 {
let to_sq = pop_lsb(&mut attacks);
buffer.add(BitMove::capture(
next_sq as u8,
to_sq as u8,
None
));
}
}
}
}

View File

@@ -0,0 +1,55 @@
use super::*;
impl Board {
pub fn add_rook_moves(&self, capture_buffer: &mut MoveBuffer, quiet_buffer: &mut MoveBuffer, move_mask: u64) {
let piece_index = 3 + self.side_to_move * 6;
let mut rooks = self.bitboards[piece_index as usize];
let empty = !self.occupancy[2];
let opponents = self.occupancy[1 - self.side_to_move as usize];
while rooks != 0 {
let from_sq = pop_lsb(&mut rooks);
let raw_move_map = self.get_pseudo_rook_moves(from_sq) & move_mask;
let move_map = self.get_pin_masked_moves(raw_move_map, from_sq);
let mut quiet_map = move_map & empty;
let mut capture_map = move_map & opponents;
while quiet_map != 0 {
let to_sq = pop_lsb(&mut quiet_map);
quiet_buffer.add(BitMove::quiet(
from_sq as u8,
to_sq as u8,
None
));
}
while capture_map != 0 {
let to_sq = pop_lsb(&mut capture_map);
capture_buffer.add(BitMove::capture(
from_sq as u8,
to_sq as u8,
None
));
}
}
}
pub fn add_rook_captures(&self, buffer: &mut MoveBuffer, move_mask: u64) {
let offset = 6 * self.side_to_move as usize;
let mut rooks: u64 = self.bitboards[3 + offset];
let opponents = self.occupancy[1 - self.side_to_move as usize];
while rooks != 0 {
let next_sq: u32 = pop_lsb(&mut rooks);
let mut attacks: u64 = self.get_pseudo_rook_moves(next_sq) & opponents & move_mask;
attacks = self.get_pin_masked_moves(attacks, next_sq);
while attacks != 0 {
let to_sq = pop_lsb(&mut attacks);
buffer.add(BitMove::capture(
next_sq as u8,
to_sq as u8,
None
));
}
}
}
}

View File

@@ -1,13 +1,13 @@
#[inline(always)]
pub fn pop_lsb(value: &mut u64) -> usize {
let idx = value.trailing_zeros() as usize;
pub fn pop_lsb(value: &mut u64) -> u32 {
let idx = value.trailing_zeros();
*value &= !(1 << idx);
return idx;
}
#[inline(always)]
pub fn pop_msb(value: &mut u64) -> usize {
let idx = 63 - value.leading_zeros() as usize;
pub fn pop_msb(value: &mut u64) -> u32 {
let idx = 63 - value.leading_zeros();
*value &= !(1 << idx);
return idx;
}
@@ -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 ----->
@@ -46,7 +72,7 @@ mod tests {
0xBEAC_DBE0_903A_AC00,
0x01E8_C895_A6F0_0000
];
let expected_values: [usize; 6] = [63, 0, 4, 2, 10, 20];
let expected_values: [u32; 6] = [63, 0, 4, 2, 10, 20];
// tests
for index in 0..6 {
@@ -66,7 +92,7 @@ mod tests {
0x0000_C1C3_201C_0DB1,
0x0000_0203_0DE4_E944
];
let expected_values: [usize; 6] = [63, 0, 61, 57, 47, 41];
let expected_values: [u32; 6] = [63, 0, 61, 57, 47, 41];
// tests
for index in 0..6 {

48
engine/src/boardsquare.rs Normal file
View File

@@ -0,0 +1,48 @@
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 };
}
pub(in super) fn from_index(idx: u8) -> Self {
let file = idx % 8;
let rank = idx / 8;
#[cfg(debug_assertions)]
{
if !(0..8).contains(&rank) {
println!("Warning: internal engine issue, given index is not on the board!");
}
}
return Self {x: file as usize, y: rank as usize};
}
pub(in super) fn to_index(&self) -> u8 {
return (8 * self.y + self.x) as u8;
}
}

192
engine/src/chessmove.rs Normal file
View File

@@ -0,0 +1,192 @@
use crate::{bitboard::{bitmove::{BitMove, BitMoveType}, board::Board}};
use super::boardsquare::BoardSquare;
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>,
}*/
pub enum ChessMove {
Quiet {
piece_type: PieceType,
from_square: BoardSquare,
to_square: BoardSquare,
promotion_piece: Option<PieceType>
},
Capture {
piece_type: PieceType,
from_square: BoardSquare,
to_square: BoardSquare,
captured_piece: PieceType,
promotion_piece: Option<PieceType>
},
Castle {
king_type: PieceType,
king_from: BoardSquare,
king_to: BoardSquare,
rook_type: PieceType,
rook_from: BoardSquare,
rook_to: BoardSquare
},
EnPassant {
pawn_type: PieceType,
from_square: BoardSquare,
to_square: BoardSquare,
captured_piece: PieceType,
captured_from: BoardSquare
}
}
impl ChessMove {
pub fn quiet(
piece_type: PieceType,
from_square: BoardSquare,
to_square: BoardSquare,
promotion_piece: Option<PieceType>,
) -> Self {
return Self::Quiet {
piece_type,
from_square,
to_square,
promotion_piece
};
}
pub fn capture(
piece_type: PieceType,
from_square: BoardSquare,
to_square: BoardSquare,
captured_piece: PieceType,
promotion_piece: Option<PieceType>,
) -> Self {
return Self::Capture {
piece_type,
from_square,
to_square,
captured_piece,
promotion_piece
};
}
pub fn castle(
king_type: PieceType,
king_from: BoardSquare,
king_to: BoardSquare,
rook_type: PieceType,
rook_from: BoardSquare,
rook_to: BoardSquare,
) -> Self {
return Self::Castle {
king_type,
king_from,
king_to,
rook_type,
rook_from,
rook_to
};
}
pub(in super) fn from_bitmove(bitmove: &BitMove, board: Board) -> Self {
match bitmove.move_type() {
BitMoveType::Quiet => {
let from_square_index = bitmove.from_square();
let piece_type = PieceType::from_index(board.piece_board(from_square_index));
let from_square = BoardSquare::from_index(from_square_index);
let to_square = BoardSquare::from_index(bitmove.to_square());
let promotion_piece = match bitmove.promotion_piece() {
Some(piece) => Some(PieceType::from_index(piece)),
None => None
};
return ChessMove::Quiet { piece_type, from_square, to_square, promotion_piece }
},
BitMoveType::Capture => {
let from_square_index = bitmove.from_square();
let to_square_index = bitmove.to_square();
let piece_type = PieceType::from_index(board.piece_board(from_square_index));
let from_square = BoardSquare::from_index(from_square_index);
let to_square = BoardSquare::from_index(to_square_index);
let captured_piece = PieceType::from_index(board.piece_board(to_square_index));
let promotion_piece = match bitmove.promotion_piece() {
Some(piece) => Some(PieceType::from_index(piece)),
None => None
};
return ChessMove::Capture { piece_type, from_square, to_square, captured_piece, promotion_piece }
},
BitMoveType::Castle => {
let from_square_index = bitmove.from_square();
let to_square_index = bitmove.to_square();
let king_type = PieceType::from_index(board.piece_board(from_square_index));
let king_from = BoardSquare::from_index(from_square_index);
let king_to = BoardSquare::from_index(to_square_index);
let promotion_piece = match bitmove.promotion_piece() {
Some(piece) => Some(PieceType::from_index(piece)),
None => None
};
let rook_type = if bitmove.from_square() < 32 { PieceType::WhiteRook } else { PieceType::BlackRook };
let rook_from_index = if bitmove.to_square() > bitmove.from_square() {
bitmove.from_square() + 3
} else {
bitmove.from_square() - 4
};
let rook_from = BoardSquare::from_index(rook_from_index);
let rook_to_index = if bitmove.to_square() > bitmove.from_square() {
bitmove.from_square() + 1
} else {
bitmove.from_square() - 1
};
let rook_to = BoardSquare::from_index(rook_to_index);
return ChessMove::Castle { king_type, king_from, king_to, rook_type, rook_from, rook_to }
},
BitMoveType::EnPassant => {
panic!("ChessMove::from_bitmove was left unimplemented");
}
}
}
pub(in super) fn to_bitmove(&self) -> BitMove {
let bitmove = match self {
ChessMove::Quiet { piece_type, from_square, to_square, promotion_piece } => {
let promotion_piece = match promotion_piece {
Some(piece) => Some(piece.to_index()),
None => None
};
return BitMove::quiet(
from_square.to_index(),
to_square.to_index(),
promotion_piece
);
},
ChessMove::Capture { piece_type, from_square, to_square, captured_piece, promotion_piece } => {
let promotion_piece = match promotion_piece {
Some(piece) => Some(piece.to_index()),
None => None
};
return BitMove::capture(
from_square.to_index(),
to_square.to_index(),
promotion_piece
);
},
ChessMove::Castle { king_type, king_from, king_to, rook_type, rook_from, rook_to } => {
return BitMove::castle(
king_from.to_index(),
king_to.to_index()
);
},
ChessMove::EnPassant { pawn_type, from_square, to_square, captured_piece, captured_from } => {
panic!("ChessMove::to_bitmove was left unimplemented");
}
};
return bitmove;
}
}

6
engine/src/gameend.rs Normal file
View File

@@ -0,0 +1,6 @@
pub enum GameEnd {
WhiteWon(String),
BlackWon(String),
Draw(String)
}

24
engine/src/lib.rs Normal file
View 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");
}

31
engine/src/movetype.rs Normal file
View File

@@ -0,0 +1,31 @@
use serde::Deserialize;
use serde::Serialize;
use super::bitboard::bitmove::BitMoveType;
#[derive(Serialize, Deserialize)]
pub enum MoveType {
Quiet,
Capture,
Castle,
EnPassant,
}
impl MoveType {
pub(in super) fn from_bitmovetype(move_type: BitMoveType) -> Self {
return match move_type {
BitMoveType::Quiet => Self::Quiet,
BitMoveType::Capture => Self::Capture,
BitMoveType::Castle => Self::Castle,
BitMoveType::EnPassant => Self::EnPassant,
_ => panic!("invalid move_type index! should NEVER appear")
}
}
pub(in super) fn to_bitmoveType(&self) -> BitMoveType {
return match self {
&MoveType::Quiet => BitMoveType::Quiet,
&MoveType::Capture => BitMoveType::Capture,
&MoveType::Castle => BitMoveType::Castle,
&MoveType::EnPassant => BitMoveType::EnPassant
};
}
}

54
engine/src/piecetype.rs Normal file
View File

@@ -0,0 +1,54 @@
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
pub enum PieceType {
WhitePawn,
WhiteKnight,
WhiteBishop,
WhiteRook,
WhiteQueen,
WhiteKing,
BlackPawn,
BlackKnight,
BlackBishop,
BlackRook,
BlackQueen,
BlackKing,
}
impl PieceType {
pub(in super) fn from_index(idx: u8) -> Self {
return match idx {
0 => PieceType::WhitePawn,
1 => PieceType::WhiteKnight,
2 => PieceType::WhiteBishop,
3 => PieceType::WhiteRook,
4 => PieceType::WhiteQueen,
5 => PieceType::WhiteKing,
6 => PieceType::BlackPawn,
7 => PieceType::BlackKnight,
8 => PieceType::BlackBishop,
9 => PieceType::BlackRook,
10 => PieceType::BlackQueen,
11 => PieceType::BlackKing,
_ => panic!("invalid piece index! should NEVER appear")
}
}
pub(in super) fn to_index(&self) -> u8 {
return match self {
&PieceType::WhitePawn => 0,
&PieceType::WhiteKnight => 1,
&PieceType::WhiteBishop => 2,
&PieceType::WhiteRook => 3,
&PieceType::WhiteQueen => 4,
&PieceType::WhiteKing => 5,
&PieceType::BlackPawn => 6,
&PieceType::BlackKnight => 7,
&PieceType::BlackBishop => 8,
&PieceType::BlackRook => 9,
&PieceType::BlackQueen => 10,
&PieceType::BlackKing => 11
}
}
}

View File

@@ -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"

View File

@@ -67,22 +67,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("Welcome! Your player ID: {}", player_id);
}
}
"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: {:?}", parsed);
}
"error" => {
if let Some(reason) = parsed.reason {
println!("Error: {}", reason);
}
}
_ => {}
}
}
}

View File

@@ -1,3 +1,5 @@
use crate::connection::ClientEvent::*;
use engine::get_available_moves;
use futures_util::{SinkExt, StreamExt};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, VecDeque};
@@ -26,6 +28,28 @@ pub fn new_waiting_queue() -> WaitingQueue {
Arc::new(Mutex::new(VecDeque::new()))
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Step {
pub from: String,
pub to: String,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(tag = "type")]
enum ClientEvent {
Join { username: String },
FindMatch,
Move { from: String, to: String },
Resign,
Chat { text: String },
RequestLegalMoves { fen: String },
}
#[derive(Serialize, Deserialize, Debug)]
pub struct EventResponse {
pub response: Result<(), String>,
}
#[derive(Debug)]
pub struct PlayerConnection {
pub id: Uuid,
@@ -43,12 +67,6 @@ pub struct GameMatch {
pub move_history: Vec<String>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Step {
pub from: String,
pub to: String,
}
// Message sending utilities
pub async fn send_message_to_player(
connections: &ConnectionMap,
@@ -102,7 +120,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;
@@ -141,8 +158,52 @@ pub async fn handle_connection(
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");
println!("client: {:?}", client_data);
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: EventResponse = EventResponse {
response: core::result::Result::Ok(()),
};
println!("response: {:?}", response);
let _ = send_message_to_player(
&connections,
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 { from, to } => {}
RequestLegalMoves { fen } => {
let moves = get_available_moves(&fen);
let _ = send_message_to_player(
&connections,
player_id,
&serde_json::to_string(&moves).unwrap(),
)
.await;
println!("Sent moves to player: {}", player_id);
}
_ => {}
}
}
}

View File

@@ -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"
);
}
}

View File

@@ -1,6 +1,6 @@
mod connection;
mod events;
mod matchmaking;
mod messages;
use tokio::net::TcpListener;
#[tokio::main]
@@ -14,15 +14,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 +29,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);
}

View File

@@ -1,5 +1,4 @@
use crate::connection::{ConnectionMap, GameMatch, MatchMap, WaitingQueue};
use crate::events::EventSystem;
use rand::random;
use uuid::Uuid;
@@ -7,21 +6,14 @@ 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,
}
}
@@ -114,7 +106,6 @@ impl MatchmakingSystem {
#[cfg(test)]
mod tests {
use super::*;
use crate::events::EventSystem;
use uuid::Uuid;
use crate::connection::new_connection_map;
@@ -126,14 +117,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 +158,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();
{

4371
ui/Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -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

Binary file not shown.

View File

@@ -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");
}
}