-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChess.cpp
More file actions
2884 lines (2441 loc) · 90.6 KB
/
Copy pathChess.cpp
File metadata and controls
2884 lines (2441 loc) · 90.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <SFML/Graphics.hpp>
#include <iostream>
#include <SFML/Audio.hpp>
#include <cctype>
#include <cstring>
#include <stack>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <cmath>
#include <limits>
#include <random>
#include "ChessPuzzleSystem.h"
using namespace sf;
using namespace std;
SoundBuffer capture;
SoundBuffer castling;
SoundBuffer stalemate;
SoundBuffer checkmate;
SoundBuffer moveBuffer;
SoundBuffer startBuffer;
SoundBuffer completingBuffer;
Sound captureSound;
Music backgroundSound;
Sound castlingSound;
Sound stalemateSound;
Sound checkmateSound;
Sound moveSound;
Sound startSound;
Sound completingSound;
bool gameOver = false;
bool whiteKingMoved = false;
bool blackKingMoved = false;
bool whiteRookLeftMoved = false;
bool whiteRookRightMoved = false;
bool blackRookLeftMoved = false;
bool blackRookRightMoved = false;
// ==============
// CHESS LOGIC
// ==============
const int SIZE = 8;
char boardLogic[SIZE][SIZE];
bool whiteTurn = true;
// =========================
// EN PASSANT VARIABLES
// =========================
int enPassantCol = -1;
int enPassantRow = -1;
Color lightColor = Color::White;
Color darkColor = Color(100, 160, 100);
char whiteCaptured[16]; // stores captured white pieces
char blackCaptured[16]; // stores captured black pieces
int whiteCapCount = 0; // number of captured white pieces
int blackCapCount = 0; // number of captured white pieces
// =============Globel variables for AI===========
char aiBoard[8][8];
sf::Clock aiThinkClock;
const float AI_TIME_LIMIT = 1.8f;
bool AIenabled = false; // whether AI is enabled
bool AIisWhite = false; // if AI is white (true) or black (false)
bool isValidMove(int sx, int sy, int dx, int dy);
bool isValidPawnMove(int sx, int sy, int dx, int dy, char piece);
bool isvalidRookmove(int sx, int sy, int dx, int dy, char p);
bool isvalidKinghtmove(int sx, int sy, int dx, int dy, char p);
bool isValidBishopMove(int sx, int sy, int dx, int dy, char p);
bool isValidQueenMove(int sx, int sy, int dx, int dy, char p);
bool isvalidKingmove(int sx, int sy, int dx, int dy, char p);
bool kingexpose(int sx, int sy, int dx, int dy);
void updateboard();
void findKing(char kingChar, int& kx, int& ky);
bool isSquareAttacked(int dx, int dy, bool byWhite);
bool isInCheck(bool whiteTurn);
bool hasAnyLegalMove(bool turn);
bool isCheckmate(bool whiteTurn);
bool isStalemate(bool whiteTurn);
bool kingExists(bool white);
struct Move
{
int sx, sy, dx, dy;
Move() : sx(-1), sy(-1), dx(-1), dy(-1) {}
Move(int a, int b, int c, int d) : sx(a), sy(b), dx(c), dy(d) {}
};
struct GameState {
char board[8][8];
bool whiteTurn;
// Castling
bool whiteKingMoved;
bool blackKingMoved;
bool whiteRookLeftMoved;
bool whiteRookRightMoved;
bool blackRookLeftMoved;
bool blackRookRightMoved;
// En Passant
int enPassantRow;
int enPassantCol;
// Captured pieces
char whiteCaptured[16];
char blackCaptured[16];
int whiteCapCount;
int blackCapCount;
};
std::stack<GameState> undoStack;
std::stack<GameState> redoStack;
GameState captureGameState() {
GameState s;
memcpy(s.board, boardLogic, sizeof(boardLogic));
s.whiteTurn = whiteTurn;
s.whiteKingMoved = whiteKingMoved;
s.blackKingMoved = blackKingMoved;
s.whiteRookLeftMoved = whiteRookLeftMoved;
s.whiteRookRightMoved = whiteRookRightMoved;
s.blackRookLeftMoved = blackRookLeftMoved;
s.blackRookRightMoved = blackRookRightMoved;
s.enPassantRow = enPassantRow;
s.enPassantCol = enPassantCol;
memcpy(s.whiteCaptured, whiteCaptured, sizeof(whiteCaptured));
memcpy(s.blackCaptured, blackCaptured, sizeof(blackCaptured));
s.whiteCapCount = whiteCapCount;
s.blackCapCount = blackCapCount;
return s;
}
void restoreGameState(const GameState& s) {
memcpy(boardLogic, s.board, sizeof(boardLogic));
whiteTurn = s.whiteTurn;
whiteKingMoved = s.whiteKingMoved;
blackKingMoved = s.blackKingMoved;
whiteRookLeftMoved = s.whiteRookLeftMoved;
whiteRookRightMoved = s.whiteRookRightMoved;
blackRookLeftMoved = s.blackRookLeftMoved;
blackRookRightMoved = s.blackRookRightMoved;
enPassantRow = s.enPassantRow;
enPassantCol = s.enPassantCol;
memcpy(whiteCaptured, s.whiteCaptured, sizeof(whiteCaptured));
memcpy(blackCaptured, s.blackCaptured, sizeof(blackCaptured));
whiteCapCount = s.whiteCapCount;
blackCapCount = s.blackCapCount;
updateboard();
}
void recordStateBeforeMove() {
undoStack.push(captureGameState());
while (!redoStack.empty()) redoStack.pop();
}
void undoMove(bool aiThinking) {
if (aiThinking) return;
if (undoStack.empty()) return;
redoStack.push(captureGameState());
GameState prev = undoStack.top();
undoStack.pop();
restoreGameState(prev);
}
void redoMove(bool aiThinking) {
if (aiThinking) return;
if (redoStack.empty()) return;
undoStack.push(captureGameState());
GameState next = redoStack.top();
redoStack.pop();
restoreGameState(next);
}
bool isInsideBoard(int r, int c)
{
if (r >= 0 && r < 8 && c >= 0 && c < 8) // tackle the Pieces must not go outside board
return true;
return false;
}
void initializeBoardLogic() //Set Character Board
{
for (int row = 0; row < SIZE; row++)
{
for (int col = 0; col < SIZE; col++)
{
boardLogic[row][col] = ' ';
}
}
for (int i = 0; i < SIZE; i++)
{
boardLogic[6][i] = 'P'; // White-pawn at 2nd Row from Bottom
boardLogic[1][i] = 'p'; // Black-pawn at 2nd Row from Top
}
// for White Pieces (Upper-Case)
boardLogic[7][4] = 'K';
boardLogic[7][5] = 'B';
boardLogic[7][6] = 'N';
boardLogic[7][7] = 'R';
boardLogic[7][0] = 'R';
boardLogic[7][1] = 'N';
boardLogic[7][2] = 'B';
boardLogic[7][3] = 'Q';
//Black Pieces (Lower-case)
boardLogic[0][0] = 'r';
boardLogic[0][1] = 'n';
boardLogic[0][2] = 'b';
boardLogic[0][3] = 'q';
boardLogic[0][4] = 'k';
boardLogic[0][5] = 'b';
boardLogic[0][6] = 'n';
boardLogic[0][7] = 'r';
}
bool isValidMove(int sx, int sy, int dx, int dy)
{
if (!isInsideBoard(dx, dy)) //Destination Box Must be inside Board 8*8
{
return false;
}
char piece = boardLogic[sx][sy]; //Check if the source square has a piece or not(empty)
if (piece == ' ')
{
return false;
}
if (whiteTurn && islower(piece)) //Check whether Valid Turn or Not
{
return false;
}
if (!whiteTurn && isupper(piece))
{
return false;
}
switch (tolower(piece)) //Check if the move is valid according to the piece type
{
case 'p':
return isValidPawnMove(sx, sy, dx, dy, piece);
case 'r':
return isvalidRookmove(sx, sy, dx, dy, piece);
case 'n':
return isvalidKinghtmove(sx, sy, dx, dy, piece);
case 'b':
return isValidBishopMove(sx, sy, dx, dy, piece);
case 'q':
return isValidQueenMove(sx, sy, dx, dy, piece);
case 'k':
return isvalidKingmove(sx, sy, dx, dy, piece);
}
return false;
}
bool isValidPawnMove(int sx, int sy, int dx, int dy, char piece)
{
int dir = (isupper(piece)) ? -1 : +1; // White (-1), Black (+1)
// 1 — Forward 1 step
if (sy == dy && dx == sx + dir && boardLogic[dx][dy] == ' ')
return true;
// 2 — Forward 2 steps (first move only)
if (sy == dy && dx == sx + 2 * dir &&
boardLogic[sx + dir][sy] == ' ' &&
boardLogic[dx][dy] == ' ' &&
((isupper(piece) && sx == 6) || (islower(piece) && sx == 1)))
return true;
// 3 — Normal Capture
if (abs(dy - sy) == 1 && dx == sx + dir &&
boardLogic[dx][dy] != ' ' &&
isupper(piece) != isupper(boardLogic[dx][dy]))
return true;
// 4 — EN PASSANT
if (abs(dy - sy) == 1 && dx == sx + dir &&
boardLogic[dx][dy] == ' ' && // destination empty
dx == enPassantRow && dy == enPassantCol) // matches EP target
return true;
return false;
}
bool isvalidRookmove(int sx, int sy, int dx, int dy, char piece)
{
if (dx != sx && dy != sy) // for same row because weather the row or column should be same
return false;
int stepX = 0, stepY = 0;
if (dx > sx) // if moving down dx > sx (0 >> 7) stepX should be increase
{
stepX = +1;
}
else if (sx > dx) // if moving up sx > dx (7 >> 0) stepX should be decrease
{
stepX = -1;
}
else if (dy > sy) // if moving right then dy > sy (0 >> 7) stepY should be increase
{
stepY = +1;
}
else if (sy > dy) // if moving left then sy > dy (7 >> 0) stepY should be Decrease
{
stepY = -1;
}
int x = sx + stepX, y = sy + stepY;
while (y != dy || x != dx) // check one coordinate before the destination
{
if (boardLogic[x][y] != ' ') // checking for whether the path is block or not
{
return false;
}
x += stepX, y += stepY; // increment or decrement for next checking
}
if (boardLogic[dx][dy] == ' ') // if not space then return true for making move
{
return true;
}
if (isupper(piece) != isupper(boardLogic[dx][dy]))
{
return true;
}
return false;
}
bool isValidBishopMove(int sx, int sy, int dx, int dy, char piece)
{
if (abs(dx - sx) != abs(dy - sy)) // change in row == change in column for bishop (abs function make - to +)
{
return false;
}
int stepX = (dx > sx) ? 1 : -1; //down Right x+=1, down left x+=1, Upward (Right or left) x-=1
int stepY = (dy > sy) ? 1 : -1; //down Right y+=1, down left y-=1, Upward Right y+=1, Upward left y-=1
int x = sx + stepX;
int y = sy + stepY;
while (x != dx && y != dy) // Checking for the move (not blocked, is-space )
{
if (boardLogic[x][y] != ' ')
{
return false;
}
x += stepX;
y += stepY;
}
if (boardLogic[dx][dy] == ' ' || (isupper(piece) != isupper(boardLogic[dx][dy]))) // if !same piece or not space then return true for making move
{
return true;
}
return false;
}
bool isvalidKinghtmove(int sx, int sy, int dx, int dy, char piece)
{
int x = abs(dx - sx), y = abs(dy - sy);
if (!((x == 2 && y == 1) || (x == 1 && y == 2))) //knight can move L shape within the Board
{ // so row =2 and column =1 or vise versa
return false;
}
if (boardLogic[dx][dy] == ' ' || (isupper(piece) != isupper(boardLogic[dx][dy])))
{
return true;
}
return false;
}
bool isValidQueenMove(int sx, int sy, int dx, int dy, char piece)
{
//Queen can move Digonally or in a straight line
if (abs(dx - sx) == abs(dy - sy)) // so I have a function of Rook and Bishop
{ // for Rook atleast same row or column
return isValidBishopMove(sx, sy, dx, dy, piece); // for bishop change in row == change in column
} // if destination is not as same as rook or bishop then not valid move
else if (sx == dx || sy == dy)
{
return isvalidRookmove(sx, sy, dx, dy, piece);
}
else
{
return false;
}
}
bool isvalidKingmove(int sx, int sy, int dx, int dy, char piece)
{
// Can't capture own piece
if (boardLogic[dx][dy] != ' ' && isupper(piece) == isupper(boardLogic[dx][dy]))
return false;
// Normal king move (one square)
if (abs(dx - sx) <= 1 && abs(dy - sy) <= 1)
{
// IMPORTANT: Temporarily remove king from board
// Otherwise the king blocks attacks from behind itself
boardLogic[sx][sy] = ' ';
// Check if destination is attacked by opponent
bool attacked = isSquareAttacked(dx, dy, !whiteTurn);
// Restore king
boardLogic[sx][sy] = piece;
return !attacked; // Valid only if NOT attacked
}
// =======================
// CASTLING RULES
// =======================
if (sx == dx && abs(dy - sy) == 2)
{
bool white = isupper(piece);
if (white)
{
if (whiteKingMoved) return false;
// Kingside castling
if (sy == 4 && dy == 6 &&
!whiteRookRightMoved &&
boardLogic[7][5] == ' ' &&
boardLogic[7][6] == ' ' &&
!isSquareAttacked(7, 4, false) &&
!isSquareAttacked(7, 5, false) &&
!isSquareAttacked(7, 6, false))
return true;
// Queenside castling
if (sy == 4 && dy == 2 &&
!whiteRookLeftMoved &&
boardLogic[7][1] == ' ' &&
boardLogic[7][2] == ' ' &&
boardLogic[7][3] == ' ' &&
!isSquareAttacked(7, 4, false) &&
!isSquareAttacked(7, 3, false) &&
!isSquareAttacked(7, 2, false))
return true;
}
else // Black castling
{
if (blackKingMoved) return false;
// Kingside
if (sy == 4 && dy == 6 &&
!blackRookRightMoved &&
boardLogic[0][5] == ' ' &&
boardLogic[0][6] == ' ' &&
!isSquareAttacked(0, 4, true) &&
!isSquareAttacked(0, 5, true) &&
!isSquareAttacked(0, 6, true))
return true;
// Queenside
if (sy == 4 && dy == 2 &&
!blackRookLeftMoved &&
boardLogic[0][1] == ' ' &&
boardLogic[0][2] == ' ' &&
boardLogic[0][3] == ' ' &&
!isSquareAttacked(0, 4, true) &&
!isSquareAttacked(0, 3, true) &&
!isSquareAttacked(0, 2, true))
return true;
}
}
return false;
}
void findKing(char king, int& kx, int& ky) //This Function Search for King Position on the Board
{
for (int r = 0; r < 8; r++)
{
for (int c = 0; c < 8; c++)
{
if (boardLogic[r][c] == king)
{
kx = r;
ky = c;
return;
}
}
}
}
bool kingexpose(int sx, int sy, int dx, int dy)
{
char backupSrc = boardLogic[sx][sy];
char backupDst = boardLogic[dx][dy];
boardLogic[dx][dy] = backupSrc;
boardLogic[sx][sy] = ' ';
char kingChar = whiteTurn ? 'K' : 'k';
int kr = -1, kc = -1;
for (int r = 0; r < 8; r++)
for (int c = 0; c < 8; c++)
if (boardLogic[r][c] == kingChar)
{
kr = r;
kc = c;
}
bool inCheck = isSquareAttacked(kr, kc, !whiteTurn);
boardLogic[sx][sy] = backupSrc;
boardLogic[dx][dy] = backupDst;
return inCheck;
}
bool isSquareAttacked(int dx, int dy, bool byWhite)
{
bool old = whiteTurn;
whiteTurn = byWhite;
for (int r = 0; r < 8; r++)
{
for (int c = 0; c < 8; c++)
{
char p = boardLogic[r][c];
if (p == ' ')
continue;
if (byWhite && isupper(p) == false)
continue;
if (!byWhite && isupper(p) == true)
continue;
if (isValidMove(r, c, dx, dy))
{
whiteTurn = old;
return true;
}
}
}
whiteTurn = old;
return false;
}
bool isInCheck(bool whiteChecked)
{
int kingX = -1, kingY = -1;
if (whiteChecked) // WhiteChecked Provides the detail which King is actually Attacked
findKing('K', kingX, kingY); //Find the Location of White King if it is checked
else
findKing('k', kingX, kingY); //Find the Location of Black King if it is checked
if (kingX == -1)
return false; // safety
return isSquareAttacked(kingX, kingY, !whiteChecked); // Check the King Square is Under Attack or Not
}
bool hasAnyLegalMove(bool turn)
{
bool old = whiteTurn;
whiteTurn = turn;
for (int sx = 0; sx < 8; sx++)
{
for (int sy = 0; sy < 8; sy++)
{
char p = boardLogic[sx][sy];
if (p == ' ') continue;
if (turn && islower(p))
continue;
if (!turn && isupper(p))
continue;
for (int dx = 0; dx < 8; dx++)
{
for (int dy = 0; dy < 8; dy++)
{
if (isValidMove(sx, sy, dx, dy))
{
char backup = boardLogic[dx][dy]; //Temporary move to Destination for Check still in check or Not
char self = boardLogic[sx][sy];
boardLogic[dx][dy] = self;
boardLogic[sx][sy] = ' ';
bool stillCheck = isInCheck(turn);
// undo
boardLogic[sx][sy] = self;
boardLogic[dx][dy] = backup;
if (!stillCheck)
{
whiteTurn = old;
return true;
}
}
}
}
}
}
whiteTurn = old;
return false;
}
bool isCheckmate(bool whiteChecked)
{
if (isInCheck(whiteChecked) && !hasAnyLegalMove(whiteChecked))
return true;
return false;
}
bool isStalemate(bool whiteChecked)
{
// Stalemate>> NOT in check, but dont have any legal moves.
if (!isInCheck(whiteChecked) && !hasAnyLegalMove(whiteChecked))
return true;
return false;
}
bool kingExists(bool white)
{
char kc;
if (white)
{
kc = 'K';
}
else
{
kc = 'k';
}
for (int r = 0; r < 8; ++r)
{
for (int c = 0; c < 8; ++c)
{
if (boardLogic[r][c] == kc)
{
return true;
}
}
}
return false;
}
void makeMove(int sx, int sy, int dx, int dy)
{
char piece = boardLogic[sx][sy];
// =========================
// Track king & rook movement
// =========================
if (piece == 'K') whiteKingMoved = true;
if (piece == 'k') blackKingMoved = true;
if (piece == 'R') {
if (sx == 7 && sy == 0) whiteRookLeftMoved = true;
if (sx == 7 && sy == 7) whiteRookRightMoved = true;
}
if (piece == 'r') {
if (sx == 0 && sy == 0) blackRookLeftMoved = true;
if (sx == 0 && sy == 7) blackRookRightMoved = true;
}
// =========================
// EN PASSANT CAPTURE
// =========================
if (tolower(piece) == 'p' && dx == enPassantRow && dy == enPassantCol)
{
if (isupper(piece)) { // White pawn captures black
if (boardLogic[dx + 1][dy] != ' ') {
blackCaptured[blackCapCount++] = boardLogic[dx + 1][dy];
boardLogic[dx + 1][dy] = ' ';
castlingSound.play();
}
}
else { // Black pawn captures white
if (boardLogic[dx - 1][dy] != ' ') {
whiteCaptured[whiteCapCount++] = boardLogic[dx - 1][dy];
boardLogic[dx - 1][dy] = ' ';
castlingSound.play();
}
}
}
// =========================
// NORMAL CAPTURE
// =========================
if (boardLogic[dx][dy] != ' ') {
if (isupper(boardLogic[dx][dy])) whiteCaptured[whiteCapCount++] = boardLogic[dx][dy];
else blackCaptured[blackCapCount++] = boardLogic[dx][dy];
captureSound.play();
}
// =========================
// Move piece
// =========================
boardLogic[dx][dy] = piece;
boardLogic[sx][sy] = ' ';
// =========================
// DOUBLE PAWN MOVE (Enable En Passant)
// =========================
enPassantRow = -1;
enPassantCol = -1;
if (piece == 'P' && sx == 6 && dx == 4) { enPassantRow = 5; enPassantCol = sy; }
else if (piece == 'p' && sx == 1 && dx == 3) { enPassantRow = 2; enPassantCol = sy; }
// =========================
// CASTLING EXECUTION
// =========================
if (piece == 'K') {
if (sy == 4 && dy == 6) { // King side
boardLogic[7][5] = 'R';
boardLogic[7][7] = ' ';
castlingSound.play();
}
if (sy == 4 && dy == 2) { // Queen side
boardLogic[7][3] = 'R';
boardLogic[7][0] = ' ';
castlingSound.play();
}
}
if (piece == 'k') {
if (sy == 4 && dy == 6) { // King side
boardLogic[0][5] = 'r';
boardLogic[0][7] = ' ';
castlingSound.play();
}
if (sy == 4 && dy == 2) { // Queen side
boardLogic[0][3] = 'r';
boardLogic[0][0] = ' ';
castlingSound.play();
}
}
// =========================
// Done
// =========================
updateboard(); // Refresh display after move
}
// ===========================
// SFML BOARD HANDLING
// ===========================
int boardArr[8][8];
int convert(char Piece) //+for Upper(white Piece) -for Lower(black Piece)
{
//when we are going to perform move it is easy to campare integers rather than characters so....
switch (Piece)
{
//1 for white Pawn & so on
case 'P': return 1;
case 'R': return 2;
case 'N': return 3;
case 'B': return 4;
case 'Q': return 5;
case 'K': return 6;
//-1 for Black Pawn & so on
case 'p': return -1;
case 'r': return -2;
case 'n': return -3;
case 'b': return -4;
case 'q': return -5;
case 'k': return -6;
}
return 0; //for spaces it return 0
}
char backConvert(int id)
{
//when board update after move it assign the charater to the pieces (texture requires character not digit as our image name is Character)
switch (id)
{
case 1: return 'P';
case 2: return 'R';
case 3: return 'N';
case 4: return 'B';
case 5: return 'Q';
case 6: return 'K';
case -1: return 'p';
case -2: return 'r';
case -3: return 'n';
case -4: return 'b';
case -5: return 'q';
case -6: return 'k';
}
return ' '; //for 0 it returns spaces
}
void updateboard()// It actually convert the board into Digital-One
{
for (int r = 0; r < 8; r++)
{
for (int c = 0; c < 8; c++)
{
boardArr[r][c] = convert(boardLogic[r][c]);
}
}
}
// ==========
// DRAWING
// ==========
float tileW, tileH, offX, offY;
void drawBoard(RenderWindow& win, RectangleShape& box, int dragR, int dragC, int hoverR, int hoverC, Color lightTile, Color darkTile)
{
// Stop menu music if it's still playing
if (backgroundSound.getStatus() == sf::Music::Playing)
backgroundSound.stop();
Color validMoveColor = Color(230, 230, 250, 190); // Lavender Mist
Color invalidMoveColor = Color(255, 120, 140, 180); // Warm Rose
for (int r = 0; r < 8; r++)
{
for (int c = 0; c < 8; c++)
{
box.setSize(Vector2f(tileW, tileH));
// Highlight the square under mouse while dragging
if (r == hoverR && c == hoverC && dragR != -1 && dragC != -1)
{
if (isValidMove(dragR, dragC, r, c))
box.setFillColor(validMoveColor);
else
box.setFillColor(invalidMoveColor);
}
else if ((r + c) % 2 == 0)
{
box.setFillColor(lightTile);
}
else
{
box.setFillColor(darkTile);
}
box.setPosition(c * tileW + offX, r * tileH + offY);
win.draw(box);
}
}
}
void drawPieces(RenderWindow& win,Texture W[], Texture B[],int skipR, int skipC)
{
Sprite s;
s.setScale(0.75f, 0.75f);
for (int r = 0; r < 8; r++)
{
for (int c = 0; c < 8; c++)
{
// Skip drawing the dragged piece
if (r == skipR && c == skipC)
continue;
int id = boardArr[r][c];
if (id == 0)
continue;
if (id > 0)
s.setTexture(W[id - 1]);
else
s.setTexture(B[-id - 1]);
s.setPosition(c * tileW + offX,
r * tileH + offY);
win.draw(s);
}
}
}
void drawCaptured(RenderWindow& win, Texture W[], Texture B[])
{
Sprite s;
s.setScale(0.5f, 0.5f);
float xWhite = offX + 8 * tileW + 10; // Right of board
float xBlack = offX - tileW; // Left of board
float yStart = offY;
// Draw light background for captured pieces
RectangleShape bgWhite(Vector2f(tileW, tileH * 8));
bgWhite.setFillColor(Color(200, 200, 200)); // Light grey
bgWhite.setPosition(xWhite, yStart);
win.draw(bgWhite);
RectangleShape bgBlack(Vector2f(tileW, tileH * 8));
bgBlack.setFillColor(Color(200, 200, 200)); // Light grey
bgBlack.setPosition(xBlack, yStart);
win.draw(bgBlack);
// White captured pieces (shown on right)
for (int i = 0; i < whiteCapCount; i++)
{
char c = whiteCaptured[i];
int idx = convert(c) - 1;
if (idx >= 0 && idx < 6)
{
s.setTexture(W[idx]);
s.setPosition(xWhite, yStart + i * (tileH / 2));
win.draw(s);
}
}
// Black captured pieces (shown on left)
for (int i = 0; i < blackCapCount; i++)
{
char c = blackCaptured[i];
int idx = -convert(c) - 1;
if (idx >= 0 && idx < 6)
{
s.setTexture(B[idx]);
s.setPosition(xBlack, yStart + i * (tileH / 2));
win.draw(s);
}
}
}
char showPromotionMenu(RenderWindow& window, bool white, Texture W[], Texture B[])
{
RectangleShape menuBG(Vector2f(tileW * 4, tileH));
menuBG.setFillColor(Color(200, 200, 200));
menuBG.setPosition((window.getSize().x - tileW * 4) / 2, (window.getSize().y - tileH) / 2);
Sprite sprites[4];
int startX = menuBG.getPosition().x;
for (int i = 0; i < 4; i++)
{
sprites[i].setScale(0.75f, 0.75f);
sprites[i].setPosition(startX + i * tileW, menuBG.getPosition().y);
if (white)
{
if (i == 0) sprites[i].setTexture(W[1]); // Rook
if (i == 1) sprites[i].setTexture(W[2]); // Knight
if (i == 2) sprites[i].setTexture(W[3]); // Bishop
if (i == 3) sprites[i].setTexture(W[4]); // Queen
}
else
{
if (i == 0) sprites[i].setTexture(B[1]);
if (i == 1) sprites[i].setTexture(B[2]);
if (i == 2) sprites[i].setTexture(B[3]);
if (i == 3) sprites[i].setTexture(B[4]);
}
}
while (true)
{
Event ev;
while (window.pollEvent(ev))
{
if (ev.type == Event::Closed)
{
window.close();
}
if (ev.type == Event::MouseButtonPressed && ev.mouseButton.button == Mouse::Left)
{
int mx = ev.mouseButton.x;
int idx = (mx - startX) / tileW;
if (idx >= 0 && idx < 4)
{
if (white) return (idx == 0 ? 'R' : idx == 1 ? 'N' : idx == 2 ? 'B' : 'Q');
else return (idx == 0 ? 'r' : idx == 1 ? 'n' : idx == 2 ? 'b' : 'q');
}
}
}
window.clear();
RectangleShape box(Vector2f(tileW, tileH));
drawBoard(window, box, -1, -1, -1, -1, lightColor, darkColor);
drawPieces(window, W, B, -1, -1);
window.draw(menuBG);
for (int i = 0; i < 4; i++) window.draw(sprites[i]);
window.display();
}
}