-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvisualize.py
1362 lines (1165 loc) · 62 KB
/
visualize.py
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
from os import environ
environ['PYGAME_HIDE_SUPPORT_PROMPT'] = '1'
import pygame
import subprocess
import argparse
import copy
#TODO: add king "capturing" its own rook-looking syntax for castling
#TODO: don't highlight the square of the last moved piece's to_location if it is in the valid squares of a selected piece
# Define colors
WHITE = (240, 217, 181)
BLACK = (181, 136, 99)
def insufficient_material(board):
"""
Determines if the game is drawn due to insufficient material.
:param board: A 2D list representing the chessboard, where each character represents a piece.
Empty squares are represented by '.' or similar non-piece characters.
:return: True if the game should be drawn due to insufficient material, False otherwise.
"""
pieces = [piece for row in board for piece in row if piece.isalpha()] # Flatten board and filter pieces
# Ensure kings exist
if 'K' not in pieces or 'k' not in pieces:
return False
# Remove kings from the list for further checks
pieces = [piece for piece in pieces if piece.lower() != 'k']
if not pieces:
# King vs King
return True
if len(pieces) == 1:
# King and one minor piece vs King
return pieces[0].lower() in ('b', 'n')
if len(pieces) == 2:
# King and bishop vs King and bishop of the same color
bishops = [piece for piece in pieces if piece.lower() == 'b']
if len(bishops) == 2:
# Determine bishop square colors (black or white squares based on their position)
bishop_positions = [(i, j) for i, row in enumerate(board) for j, piece in enumerate(row) if piece.lower() == 'b']
bishop_colors = [(i + j) % 2 for i, j in bishop_positions]
return bishop_colors[0] == bishop_colors[1] # Same color bishops
return False
def get_piece_image(piece):
# Load piece image based on piece name (e.g., "Wp" for white pawn)
king_aliases = ["K", "k", "S", "s", "U", "u", "W", "w"]
pawn_aliases = ["P", "p", "E", "e"]
if piece in king_aliases:
piece = "k" if piece.islower() else "K"
if piece in pawn_aliases:
piece = "p" if piece.islower() else "P"
if piece.islower():
piece_key = "B"
else:
piece_key = "W"
piece_key += piece[0].lower()
image_path = "graphics/" + f"{piece_key}.png"
return pygame.image.load(image_path)
def create_piece_from_char(char, position):
if char == 'P':
return Pawn("white", position)
elif char == 'p':
return Pawn("black", position)
elif char == 'E':
pawn = Pawn("white", position)
pawn.en_passant_eligible = True
return pawn
elif char == 'e':
pawn = Pawn("black", position)
pawn.en_passant_eligible = True
return pawn
elif char == 'K': #K denotes a white king with no castling rights.
king = King("white", position)
king.has_queenside_castling_rights = False
king.has_kingside_castling_rights = False
return king
elif char == 'k': #k denotes a black king with no castling rights.
king = King("black", position)
king.has_queenside_castling_rights = False
king.has_kingside_castling_rights = False
return king
elif char == 'S': #S denotes a white king with only kingside castling rights.
king = King("white", position)
king.has_queenside_castling_rights = False
king.has_kingside_castling_rights = True
return king
elif char == 's': #s denotes a black king with only kingside castling rights.
king = King("black", position)
king.has_queenside_castling_rights = False
king.has_kingside_castling_rights = True
return king
elif char == 'U': #U denotes a white king with only queenside castling rights.
king = King("white", position)
king.has_queenside_castling_rights = True
king.has_kingside_castling_rights = False
return king
elif char == 'u': #u denotes a black king with only queenside castling rights.
king = King("black", position)
king.has_queenside_castling_rights = True
king.has_kingside_castling_rights = False
return king
elif char == 'W': #W denotes a white king with full castling rights.
king = King("white", position)
king.has_queenside_castling_rights = True
king.has_kingside_castling_rights = True
return king
elif char == 'w': #w denotes a black king with full castling rights.
king = King("black", position)
king.has_queenside_castling_rights = True
king.has_kingside_castling_rights = True
return king
elif char == 'R':
return Rook("white", position)
elif char == 'r':
return Rook("black", position)
elif char == 'N':
return Knight("white", position)
elif char == 'n':
return Knight("black", position)
elif char == 'B':
return Bishop("white", position)
elif char == 'b':
return Bishop("black", position)
elif char == 'Q':
return Queen("white", position)
elif char == 'q':
return Queen("black", position)
else:
return None # Return None for empty squares (e.g., '.')
def move_piece(board, from_position, to_position):
row_from, col_from = from_position
row_to, col_to = to_position
king_aliases = ['S', 'W', 'U', 's', 'w', 'u']
#Revoke en passant eligibility on other pieces
for row in range(8):
for col in range(8):
if board[row][col] == 'E':
board[row][col] = 'P'
elif board[row][col] == 'e':
board[row][col] = 'p'
# Check if there's a piece at the from_position
piece = board[row_from][col_from]
if piece:
# First order of business is detecting if we're moving a pawn or not for some pawn-specific logic.
if piece == 'P' or piece == 'p':
# Determine if this pawn is eligible to be captured en passant
en_passant_eligible = False
if piece == 'P' and row_from-row_to == 2: # White pawn
en_passant_eligible = (
(col_from > 0 and board[4][col_to - 1] == 'p') or # Check left for black pawn
(col_from < 7 and board[4][col_to + 1] == 'p') # Check right for black pawn
)
elif piece == 'p' and row_from-row_to == -2: # Black pawn
en_passant_eligible = (
(col_from > 0 and board[3][col_to - 1] == 'P') or # Check left for white pawn
(col_from < 7 and board[3][col_to + 1] == 'P') # Check right for white pawn
)
# If the pawn moved forward two squares AND there's an enemy pawn able to capture it en passant
if en_passant_eligible:
# Make it eligible to be en passanted
piece = 'E' if piece == 'P' else 'e'
# If we're capturing en passant. Determine by checking if moving to a different column onto an empty square
if col_to != col_from and board[row_to][col_to] == '.':
if piece.isupper():
board[row_to + 1][col_to] = '.'
elif piece.islower():
board[row_to - 1][col_to] = '.'
#Second, we need to revoke castling rights if it is a rook
elif piece == 'R':
# If we're moving the a1 rook from its starting square
# and there's a king with both sides castling rights on the starting square, revoke
# this king's queenside castling rights.
if (row_from, col_from) == (7, 0) and board[7][4] == 'W': #Both sides castling rights
board[7][4] = 'S' #Convert to kingside only castling rights
elif (row_from, col_from) == (7, 0) and board[7][4] == 'U': #Queenside only castling rights
board[7][4] = 'K' #Convert to no castling rights
elif(row_from, col_from) == (7, 7) and board[7][4] == 'W': #Both sides castling rights
board[7][4] = 'U' #Queenside only castling rights
elif(row_from, col_from) == (7, 7) and board[7][4] == 'S': #Kingside only castling rights
board[7][4] = 'K' #convert to no castling rights
elif piece == 'r':
# If we're moving the a8 rook from its starting square
# and there's a king with both sides castling rights on the starting square, revoke
# this king's queenside castling rights.
if (row_from, col_from) == (0, 0) and board[0][4] == 'w': #Both sides castling rights
board[0][4] = 's' #Convert to kingside only castling rights
elif (row_from, col_from) == (0, 0) and board[0][4] == 'u': #Queenside only castling rights
board[0][4] = 'k' #Convert to no castling rights
elif(row_from, col_from) == (0, 7) and board[0][4] == 'w': #Both sides castling rights
board[0][4] = 'u' #Queenside only castling rights
elif(row_from, col_from) == (0, 7) and board[0][4] == 's': #Kingside only castling rights
board[0][4] = 'k' #convert to no castling rights
elif piece in king_aliases: #We're moving a king.
piece = 'K' if piece.isupper() else 'k' #Revoke all castling rights.
if(abs(col_from - col_to) == 2): #We are castling
if(col_to == 2): #Queenside
if piece.isupper(): #White
board[7][0] = '.'
board[7][3] = 'R'
else: #Black
board[0][0] = '.'
board[0][3] = 'r'
else: #Kingside
if piece.isupper(): #White
board[7][7] = '.'
board[7][5] = 'R'
else: #Black
board[0][7] = '.'
board[0][5] = 'r'
# Update the board state
board[row_from][col_from] = "."
board[row_to][col_to] = piece
else:
raise ValueError("Tried to move a piece that doesn't exist.")
#Returns the coordinates of the kings
def find_kings(board):
white_king_aliases = ["K", "W", "U", "S"]
black_king_aliases = ["k", "w", "u", "s"]
kings = []
for row in range(8):
for col in range(8):
if board[row][col] in white_king_aliases:
kings.append((row, col))
for row in range(8):
for col in range(8):
if board[row][col] in black_king_aliases:
kings.append((row, col))
return kings
#Look to see if the king is in check.
def look_for_check(board):
# Find the king's positions
king_positions = find_kings(board)
white_in_check = False
black_in_check = False
for row in range(8):
for col in range(8):
piece = board[row][col]
for king_position in king_positions:
king_row = king_position[0]
king_col = king_position[1]
isWhite = board[king_row][king_col].isupper()
if piece.islower() and isWhite: #If a black piece on white's turn:
enemy_piece = create_piece_from_char(piece, (row, col))
if king_position in enemy_piece.in_vision_positions(board):
white_in_check = True
elif piece.isupper() and not isWhite: #If a white piece on black's turn
enemy_piece = create_piece_from_char(piece, (row, col))
if king_position in enemy_piece.in_vision_positions(board):
black_in_check = True
if(white_in_check and black_in_check):
return "both_in_check"
elif white_in_check:
return "white_in_check"
elif black_in_check:
return "black_in_check"
return "none_in_check"
def simulate_move(board, from_pos, to_position):
new_board = copy.deepcopy(board)
move_piece(new_board, from_pos, to_position)
return new_board
#Returns the position of a pawn on the back rank, if there is one. If there is not, it returns (-1, -1)
def pawn_on_back_rank(board) -> tuple:
for col in range(8):
if board[0][col] == 'P':
return (0, col)
elif board[7][col] == 'p':
return (7, col)
return (-1, -1)
def promote(board):
for col in range(8):
if board[0][col] == 'P':
board[0][col] = 'Q'
elif board[7][col] == 'p':
board[0][col] = 'q'
def print_board(board):
for row in board:
print(" ".join(row))
def set_board_from_string(input_board):
board_as_list = [[input_board[i * 8 + j] for j in range(8)] for i in range(8)]
return board_as_list
def coordinate_to_algebraic(coordinate):
"""
Convert coordinates (0, 0) to algebraic chess notation, e.g., (0, 0) becomes 'a8'.
"""
if 0 <= coordinate[0] <= 7 and 0 <= coordinate[1] <= 7:
column = chr(ord('a') + coordinate[1])
row = str(8 - coordinate[0])
return f"{column}{row}"
else:
raise ValueError("Invalid coordinate")
def algebraic_to_coordinate(algebraic):
row = 0
col = 0
# Validate the basic algebraic notation (e.g., g7, a8)
if len(algebraic) < 2 or not ('a' <= algebraic[0] <= 'h') or not ('1' <= algebraic[1] <= '8'):
raise ValueError("Invalid algebraic notation")
# Convert rank ('1'-'8') to row index (0-7)
row = 7 - (int(algebraic[1]) - 1)
# Convert file ('a'-'h') to column index (0-7)
col = ord(algebraic[0]) - ord('a')
# Return early for standard moves
if len(algebraic) == 2:
return (row, col)
# Handle promotions with a third character (e.g., g7q, e8n)
if len(algebraic) == 3 and algebraic[2].lower() in 'qrnb':
piece_code = 0
if algebraic[2].lower() == 'n':
piece_code = 1
elif algebraic[2].lower() == 'r':
piece_code = 2
elif algebraic[2].lower() == 'b':
piece_code = 3
# Calculate new row and column for the promoted piece
if row == 0:
coordinate = 64 + col * 4 + piece_code
elif row == 7:
coordinate = 96 + col * 4 + piece_code
else:
raise ValueError("Promotion can only occur on the last rank")
row = coordinate // 8
col = coordinate % 8
return (row, col)
# If the input length is not valid, raise an error
print(len(algebraic))
print(f"\"{algebraic}\"")
raise ValueError("Invalid algebraic notation")
def split_algebraic(algebraic):
# Strip any trailing newline or whitespace characters
algebraic = algebraic.strip()
if len(algebraic) == 4 or len(algebraic) == 5:
first_part = algebraic[:2] # Extract the first two characters
second_part = algebraic[2:4] # Extract the next two characters
else:
raise ValueError("Invalid algebraic notation")
first_coordinate = algebraic_to_coordinate(first_part)
second_coordinate = algebraic_to_coordinate(second_part)
return (first_coordinate, second_coordinate)
def board_to_fen(board):
fen = ''
for row in board:
empty_count = 0
for cell in row:
if cell == '.':
empty_count += 1
else:
cell = 'K' if cell in ['W', 'S', 'U'] else cell
cell = 'k' if cell in ['w', 's', 'u'] else cell
cell = 'P' if cell == 'E' else cell
cell = 'p' if cell == 'e' else cell
if empty_count > 0:
fen += str(empty_count)
empty_count = 0
fen += cell
if empty_count > 0:
fen += str(empty_count)
fen += '/'
fen = fen[:-1] # Remove the trailing slash
return fen
def generate_fen(board, active_color='w', castling='KQkq', en_passant='-', halfmove=0, fullmove=1):
fen_board = board_to_fen(board)
return f"{fen_board} {active_color} {castling} {en_passant} {halfmove} {fullmove}"
def generate_castling_rights(board):
castling = ''
# Flatten the 2D list to make searching easier
flattened_board = [cell for row in board for cell in row]
# Look for white castling rights
if 'W' in flattened_board:
castling += 'KQ'
elif 'S' in flattened_board:
castling += 'K'
elif 'U' in flattened_board:
castling += 'Q'
# Look for black castling rights
if 'w' in flattened_board:
castling += 'kq'
elif 's' in flattened_board:
castling += 'k'
elif 'u' in flattened_board:
castling += 'q'
# If no castling rights are found
if not castling:
return '-'
return castling
def get_algebraic_notation(row, col):
files = 'abcdefgh' # a-h for the file (column)
ranks = '87654321' # 8-1 for the rank (row)
return files[col] + ranks[row]
def find_en_passant_square(board):
for row in range(len(board)):
for col in range(len(board[row])):
if board[row][col] == 'E': # White en passant pawn
return get_algebraic_notation(row + 1, col) # En passant square is below the white pawn
elif board[row][col] == 'e': # Black en passant pawn
return get_algebraic_notation(row - 1, col) # En passant square is above the black pawn
return '-' # No en passant square
def consult_engine(fen) -> str:
# Run the compiled C++ program and capture the output
run_process = subprocess.run(["./engine"] + fen.split(), capture_output=True, text=True)
if run_process.returncode == 0:
return run_process.stdout
class Screen:
def __init__(self, screen_width, screen_height):
self.screen_width = screen_width
self.screen_height = screen_height
self.square_size = screen_width // 8 # Size of each square
self.board = "" #TODO: fix later
self.board_as_list = [] #TODO: Make this work off of string boards instead of list boards.
self.halfmove = 0 # Number of half-moves since last capture or pawn move
self.fullmove = 1 # Incremented after Black's move
self.fen_positions = {} # Dictionary to track FEN positions and their occurrences
pygame.init()
# Create a Pygame window
self.screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Chessboard")
self.buffer = pygame.Surface((screen_width, screen_height))
self.buffer.fill((0, 0, 0)) # Fill the buffer with a black background
# Main game loop flag
self.running = True
# Create a variable to track the currently selected piece
self.selected_piece = None
self.selected_piece_position = None #Position of the piece that's being dragged
self.selected_piece_original_position = None # Store the original position of the selected piece
self.shouldDrag = False
self.selected_piece_valid_moves = []
self.last_moved_piece_current_position = None
self.last_moved_piece_original_position = None
self.is_white_turn = True
self.black_is_in_check = False
self.white_is_in_check = False
self.selected_promotion_piece = (-1, -1)
self.board_state = "ongoing" #Can be stalemate or checkmate
def handle_moves(self, player_side, square_to_move_to):
# Handle player's move (if it's the player's turn)
if self.selected_piece_original_position and square_to_move_to != (-1, -1) and self.is_white_turn == (player_side == 'white'):
capture, pawn_move = self.check_halfmove(self.selected_piece_original_position, square_to_move_to)
back_rank = 0 if player_side == 'white' else 7
# Play the move, check for promotion
move = coordinate_to_algebraic(self.selected_piece_original_position) + coordinate_to_algebraic(square_to_move_to)
self.board_state = self.process_player_move(square_to_move_to, pawn_move)
promotion_piece = ''
if pawn_move and square_to_move_to[0] == back_rank:
promotion_piece = self.board_as_list[square_to_move_to[0]][square_to_move_to[1]].lower()
move += promotion_piece
if promotion_piece == '.':
return ""
self.clear_buffer()
self.draw_board(self.buffer)
self.highlight_squares(self.buffer)
self.draw_pieces(self.buffer)
self.update_display()
if capture:
capture_sound = pygame.mixer.Sound('./sounds/Capture.ogg')
capture_sound.play()
else:
move_sound = pygame.mixer.Sound('./sounds/Move.ogg')
move_sound.play()
return move
# Handle engine's move (if it's engine's turn)
if self.board_state == "ongoing" and self.is_white_turn != (player_side == 'white'):
fen = self.generate_fen_string(self.halfmove, self.fullmove)
print(fen)
response = consult_engine(fen)
if response:
from_coord, to_coord = split_algebraic(response)
frow = from_coord[0]
fcol = from_coord[1]
trow = to_coord[0]
tcol = to_coord[1]
# Load sounds
capture = True if self.board_as_list[trow][tcol] != "." else False
move_sound = pygame.mixer.Sound('./sounds/Move.ogg') # Replace with your move sound file path
capture_sound = pygame.mixer.Sound('./sounds/Capture.ogg') # Replace with your capture sound file path
# Play sound when a move is made
if capture:
capture_sound.play()
else:
move_sound.play()
promotion_piece = ''
if len(response) == 5:
promotion_piece = response[4]
self.board_as_list[frow][fcol] = promotion_piece
self.board_state = self.play_move(from_coord, to_coord)
return response
return ""
def run(self, player_side):
square_to_move_to = (-1, -1)
moves = []
while self.running:
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE and self.board_state != "ongoing":
self.running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
square_to_move_to = self.handle_mouse_button_down(event)
elif event.type == pygame.MOUSEMOTION:
self.handle_mouse_motion(event)
elif event.type == pygame.MOUSEBUTTONUP:
if event.button == 1:
square_to_move_to = self.handle_mouse_button_up(event)
# Clear and redraw the board and pieces
self.clear_buffer()
self.draw_board(self.buffer)
self.highlight_squares(self.buffer)
self.draw_pieces(self.buffer)
self.blit_selected_piece()
# Handle player and engine moves
move = self.handle_moves(player_side, square_to_move_to)
if move != "":
moves += [move]
self.update_display()
# Check game state
# if self.board_state != "ongoing":
# self.running = False
command = ["python", "uci_to_pgn.py"] + moves # List: command + arguments
# Run the subprocess
# print(command)
run_process = subprocess.run(command, capture_output=True, text=True)
# Print stderr (standard error) to check for any error messages
if run_process.stderr:
print("Error:", run_process.stderr)
# if run_process.returncode == 0:
print(run_process.stdout)
def check_halfmove(self, from_square, to_square):
"""Handle user's move, check if it's a capture or pawn move."""
row, col = to_square
frow, fcol = from_square
capture = self.board_as_list[row][col] != '.'
pawn_move = self.board_as_list[frow][fcol].lower() == 'p'
return capture, pawn_move
def process_player_move(self, square_to_move_to, pawn_move):
"""Process the player's move, handling promotions if necessary."""
frow, fcol = self.selected_piece_original_position
trow = square_to_move_to[0]
# Check for pawn promotion
if pawn_move and (trow == 0 or trow == 7):
promotion_piece = self.show_promotion_interface(square_to_move_to)
# If no promotion piece has been selected yet, return current board state
if promotion_piece == '':
return self.board_state # Return the unchanged board state
# Update the piece if promotion was selected
self.board_as_list[frow][fcol] = promotion_piece
# Proceed with the move
return self.play_move(self.selected_piece_original_position, square_to_move_to)
def generate_fen_string(self, halfmove, fullmove):
"""Generate FEN string after player's move."""
color = 'w' if self.is_white_turn else 'b'
castling_string = generate_castling_rights(self.board_as_list)
en_passant_square = find_en_passant_square(self.board_as_list)
return generate_fen(self.board_as_list, active_color=color, castling=castling_string, en_passant=en_passant_square, halfmove=halfmove, fullmove=fullmove)
def handle_mouse_button_down(self, event):
mouse_x, mouse_y = pygame.mouse.get_pos()
clicked_row = mouse_y // self.square_size
clicked_col = mouse_x // self.square_size
clicked_square = (clicked_row, clicked_col)
piece = self.board_as_list[clicked_row][clicked_col]
if(self.selected_piece != None): #Piece is selected
if clicked_square in self.selected_piece_valid_moves:
return clicked_square
else:
self.deselect_piece()
else:
# print("no piece selected, looking to pick up piece")
if piece != ".":
if(self.is_white_turn and piece.islower()):
# print("invalid piece selection. picked black piece on white's turn. do nothing")
return (-1, -1)
elif(not self.is_white_turn and piece.isupper()):
# print("invalid piece selection. picked white piece on black's turn. do nothing")
return (-1, -1)
# print("this piece isn't an empty square, it is of the right color, and we don't already have a piece selected. select piece. and drag it.")
self.select_piece(piece, clicked_square)
self.shouldDrag = True
return (-1, -1)
def handle_mouse_motion(self, event):
if self.selected_piece:
mouse_x, mouse_y = pygame.mouse.get_pos()
self.selected_piece_position = (mouse_y // self.square_size, mouse_x // self.square_size)
def handle_mouse_button_up(self, event):
if self.selected_piece:
# Place the piece back to its original position
mouse_x, mouse_y = pygame.mouse.get_pos()
clicked_row = mouse_y // self.square_size
clicked_col = mouse_x // self.square_size
clicked_square = (clicked_row, clicked_col)
if clicked_square != self.selected_piece_original_position:
if clicked_square not in self.selected_piece_valid_moves:
self.deselect_piece()
self.shouldDrag = False
else:
# self.board_state = self.play_move(self.selected_piece_original_position, clicked_square)
return clicked_square
else:
self.shouldDrag = False
return (-1, -1)
def show_promotion_interface(self, pawn_position):
# Define colors
orange_outer = (207, 95, 35)
orange_inner = (188, 148, 124)
# Create a semi-transparent overlay
overlay = pygame.Surface((self.screen_width, self.screen_height), pygame.SRCALPHA)
overlay.fill((0, 0, 0, 128)) # Fills the overlay with semi-transparent black
# Draw the overlay on the screen
self.buffer.blit(overlay, (0, 0))
promotion_squares = []
if pawn_position[0] == 0: #white promotion at top of board
# Assuming pawn_position is the position of the promoting pawn (e.g., (6, 3) for a white pawn on the 7th rank)
promotion_squares = [pawn_position, #Should print a queen icon here
(pawn_position[0] + 1, pawn_position[1]), # Should print a knight icon here
(pawn_position[0] + 2, pawn_position[1]), # Should print a rook icon here
(pawn_position[0] + 3, pawn_position[1])] # Should print a bishop icon here
if pawn_position[0] == 7: #black promotion at bottom of board
promotion_squares = [pawn_position, #Should print a queen icon here
(pawn_position[0] - 1, pawn_position[1]), # Should print a knight icon here
(pawn_position[0] - 2, pawn_position[1]), # Should print a rook icon here
(pawn_position[0] - 3, pawn_position[1])] # Should print a bishop icon here
# Assuming pawn_position is the position of the promoting pawn (e.g., (6, 3) for a white pawn on the 7th rank)
promotion_pieces = ['Q', 'N', 'R', 'B'] if pawn_position[0] == 0 else ['q', 'n', 'r', 'b']
# Create a gradient surface for the outer rectangle
gradient_outer_surface = pygame.Surface((self.square_size, self.square_size), 255)
for y in range(self.square_size):
alpha = int(255 * (1 - abs(y - self.square_size // 2) / (self.square_size // 2)))
pygame.draw.rect(gradient_outer_surface, (orange_outer[0], orange_outer[1], orange_outer[2], alpha),
(0, y, self.square_size, 1))
# Blit the gradient surface for the outer rectangle onto the buffer
x, y = pawn_position[1] * self.square_size, pawn_position[0] * self.square_size
# self.buffer.blit(gradient_outer_surface, (x, y))
# Create a solid surface for the inner circle
inner_circle_surface = pygame.Surface((self.square_size, self.square_size), pygame.SRCALPHA)
pygame.draw.circle(inner_circle_surface, orange_inner, (self.square_size // 2, self.square_size // 2),
self.square_size // 2)
# Draw circles and piece images on promotion squares
for i, square in enumerate(promotion_squares):
x, y = square[1] * self.square_size, square[0] * self.square_size
center = (x + self.square_size // 2, y + self.square_size // 2)
pygame.draw.circle(self.buffer, (173, 173, 173), center, self.square_size // 2)
# Get the piece image based on the promotion piece character
piece_image = get_piece_image(promotion_pieces[i])
# Calculate the position to blit the piece image
piece_rect = piece_image.get_rect()
piece_rect.center = center
x, y = square[1] * self.square_size, square[0] * self.square_size
rect = pygame.Rect(x, y, self.square_size, self.square_size)
# Check if mouse is hovering over the square
mouse_x, mouse_y = pygame.mouse.get_pos()
if rect.collidepoint(mouse_x, mouse_y): # Replace mouse_x and mouse_y with actual mouse coordinates
# Blit the gradient surface
self.buffer.blit(gradient_outer_surface, (x, y))
self.buffer.blit(inner_circle_surface, (x, y))
# Blit the piece image onto the buffer
self.buffer.blit(piece_image, piece_rect)
for event in pygame.event.get():
mouse_x, mouse_y = pygame.mouse.get_pos()
hovered_square_coord = (mouse_y // self.square_size, mouse_x // self.square_size)
if event.type == pygame.MOUSEBUTTONDOWN:
self.selected_promotion_piece = hovered_square_coord if hovered_square_coord in promotion_squares else (-1, -1)
elif event.type == pygame.MOUSEBUTTONUP: #I think the issue I'm having is here. It's that there needs to be a cooldown.
if self.selected_promotion_piece != (-1, -1):
self.shouldShowPromotionInterface = False
promotion_map = {
0: 'Q', 1: 'N', 2: 'R', 3: 'B',
7: 'q', 6: 'n', 5: 'r', 4: 'b'
}
return promotion_map.get(self.selected_promotion_piece[0], None)
self.shouldShowPromotionInterface = True
#TODO: fix the screen jitteryness when queening
# self.update_display()
return '' #Code for continue showing the interface
def play_move(self, from_pos, to_pos):
frow = from_pos[0]
fcol = from_pos[1]
if(self.board_as_list[frow][fcol].islower()): #Black just moved a piece
self.fullmove += 1
capture, pawn_move = self.check_halfmove(from_pos, to_pos)
if capture or pawn_move:
self.halfmove = 0
else:
self.halfmove += 1
move_piece(self.board_as_list, from_pos, to_pos)
#Make a new fen for this new position, with -1 being the halfmove counter and full move counter
#because this fen is only used to go into the table of seen positions
color = 'w' if self.is_white_turn else 'b'
castling_string = generate_castling_rights(self.board_as_list)
en_passant_square = find_en_passant_square(self.board_as_list)
fen = generate_fen(self.board_as_list, color, castling_string, en_passant_square, -1, -1)
# Update the map with the FEN position
if fen in self.fen_positions:
self.fen_positions[fen] += 1
else:
self.fen_positions[fen] = 1
# Check for threefold repetition
if self.fen_positions[fen] >= 3:
print("Draw due to three-fold repetition")
print("Hit escape to get the PGN and close the window.")
return "Draw."
#Write down the squares we moved from and to before we clear it so we can highlight them.
self.last_moved_piece_original_position = from_pos
self.last_moved_piece_current_position = to_pos
self.deselect_piece()
self.is_white_turn = not self.is_white_turn
self.white_is_in_check = True if("white_in_check" == look_for_check(self.board_as_list)) else False
self.black_is_in_check = True if("black_in_check" == look_for_check(self.board_as_list)) else False
no_legal_moves = self.no_legal_moves(self.board_as_list)
if(self.halfmove >= 100):
print("Draw due to 50 move rule, 100 half moves have been played without capturing a piece or moving a pawn.")
print("Hit escape to get the PGN and close the window.")
return "Draw."
if(insufficient_material(self.board_as_list)):
print("Draw due to insufficient material. Hit escape to get the PGN and close the window.")
return "Draw."
if self.is_white_turn and self.white_is_in_check and no_legal_moves:
print("Checkmate. Black wins. Hit escape to get the PGN and close the window.")
return "Checkmate."
elif not self.is_white_turn and self.black_is_in_check and no_legal_moves:
print("Checkmate. White wins. Hit escape to get the PGN and close the window.")
return "Checkmate."
if self.is_white_turn and not self.white_is_in_check and no_legal_moves:
print("Stalemate. Hit escape to get the PGN and close the window.")
return "Stalemate."
elif not self.is_white_turn and not self.black_is_in_check and no_legal_moves:
print("Stalemate. Hit escape to get the PGN and close the window.")
return "Stalemate."
return "ongoing"
def no_legal_moves(self, board):
for row in range(8):
for col in range(8):
if self.is_white_turn and board[row][col].isupper():
piece = board[row][col]
piece_as_class = create_piece_from_char(piece, (row, col))
if piece_as_class.valid_moves(board): # Check if there are any valid moves
return False
elif not self.is_white_turn and board[row][col].islower():
piece = board[row][col]
piece_as_class = create_piece_from_char(piece, (row, col))
if piece_as_class.valid_moves(board): # Check if there are any valid moves
# for move in piece_as_class.valid_moves(board):
# print(f"{coordinate_to_algebraic(piece_as_class.position)}{coordinate_to_algebraic(move)}")
return False
return True
def select_piece(self, piece, position):
# print("shouldn't this function only be called once")
self.selected_piece = piece
self.selected_piece_original_position = position
piece_class = create_piece_from_char(piece, position)
self.selected_piece_valid_moves = piece_class.valid_moves(self.board_as_list)
def deselect_piece(self):
self.selected_piece = None
self.selected_piece_position = None #Position of the piece that's being dragged
self.selected_piece_original_position = None # Store the original position of the selected piece
self.selected_piece_valid_moves = []
def clear_buffer(self):
# Clear the buffer (not the screen)
self.buffer.fill((0, 0, 0))
def blit_selected_piece(self):
if self.selected_piece and self.shouldDrag:
mouse_x, mouse_y = pygame.mouse.get_pos()
selected_piece_image = get_piece_image(self.selected_piece)
self.buffer.blit(selected_piece_image, (mouse_x - 30, mouse_y - 30))
def update_display(self):
# Blit the buffer to the screen
self.screen.blit(self.buffer, (0, 0))
pygame.display.update()
# Draw the chessboard
def draw_board(self, surface=None):
if surface is None:
surface = self.screen # Default to drawing on the screen
# Labels for rows and columns
row_labels = "87654321"
column_labels = "abcdefgh"
for row in range(8):
for col in range(8):
square_color = WHITE if (row + col) % 2 == 0 else BLACK
pygame.draw.rect(surface, square_color, (col * self.square_size, row * self.square_size, self.square_size, self.square_size))
# Determine the color for the labels based on the square's color
label_color = BLACK if square_color == WHITE else WHITE # Black text for white squares, white text for black squares
font = pygame.font.Font(None, 14)
# Draw row numbers in the top right corner of each square
row_label = row_labels[row]
text = font.render(row_label, True, label_color)
text_rect = text.get_rect()
text_rect.topright = ((8 - 0.05) * self.square_size, (row + 0.05) * self.square_size)
surface.blit(text, text_rect)
# Draw column letters in the bottom left corner of each square along the bottom
col_label = column_labels[col]
text = font.render(col_label, True, label_color)
text_rect = text.get_rect()
text_rect.bottomleft = ((col + 0.05) * self.square_size, (8 - 0.05) * self.square_size)
surface.blit(text, text_rect)
def highlight_squares(self, surface=None):
if surface is None:
surface = self.screen # Default to drawing on the screen
# Highlight the selected square (if any)
squares_to_highlight = []
if self.selected_piece != '.' and self.selected_piece != None:
row = self.selected_piece_original_position[0]
col = self.selected_piece_original_position[1]
squares_to_highlight = self.selected_piece_valid_moves
highlight_color_light = (130, 150, 105) # Light square highlight color
highlight_color_dark = (100, 111, 64) # Dark square highlight color
# Define red gradient color for check highlight
# Check if any king is in check
check_status = look_for_check(self.board_as_list)
king_positions = find_kings(self.board_as_list) # [(white_king_row, white_king_col), (black_king_row, black_king_col)]
check_gradient_color = (255, 0, 0, 128) # Semi-transparent red
last_move_highlight_color_dark = (170, 162, 58)
last_move_highlight_color_light = (205, 210, 106)
for row in range(8):
for col in range(8):
square_color = WHITE if (row + col) % 2 == 0 else BLACK
highlight_color = highlight_color_light if square_color == WHITE else highlight_color_dark
last_move_highlight_color = last_move_highlight_color_light if square_color == WHITE else last_move_highlight_color_dark
if self.last_moved_piece_original_position == (row, col) or self.last_moved_piece_current_position == (row, col):
pygame.draw.rect(surface, last_move_highlight_color, (col * self.square_size, row * self.square_size, self.square_size, self.square_size))
#Highlight the entire square that the selected piece sits on.
if self.selected_piece_original_position == (row, col):
pygame.draw.rect(surface, highlight_color, (col * self.square_size, row * self.square_size, self.square_size, self.square_size))
#Highlight the squares that the piece can move to.
if (row, col) in squares_to_highlight:
center_x = (col + 0.5) * self.square_size
center_y = (row + 0.5) * self.square_size
# Draw a small circle or marker at the center
if(self.board_as_list[row][col] == '.'):
pygame.draw.circle(surface, highlight_color, (int(center_x), int(center_y)), 7, 7)
# Draw triangles around the corner of square that the piece can capture to.
else:
square_rect = pygame.Rect(col * self.square_size, row * self.square_size, self.square_size, self.square_size)
top_left = (square_rect.left, square_rect.top)
top_right = (square_rect.right-1, square_rect.top)
bottom_left = (square_rect.left, square_rect.bottom-1)
bottom_right = (square_rect.right-1, square_rect.bottom-1)
# Define triangle points
triangle_size = 12
triangle_points_top_left = [top_left, (top_left[0], top_left[1] + triangle_size), (top_left[0] + triangle_size, top_left[1])]
triangle_points_top_right = [top_right, (top_right[0], top_right[1] + triangle_size), (top_right[0] - triangle_size, top_right[1])]
triangle_points_bottom_right = [bottom_right, (bottom_right[0], bottom_right[1] - triangle_size), (bottom_right[0] - triangle_size, bottom_right[1])]
triangle_points_bottom_left = [bottom_left, (bottom_left[0], bottom_left[1] - triangle_size), (bottom_left[0] + triangle_size, bottom_left[1])]
# Draw triangles at the corners
pygame.draw.polygon(surface, highlight_color, triangle_points_top_left)
pygame.draw.polygon(surface, highlight_color, triangle_points_top_right)
pygame.draw.polygon(surface, highlight_color, triangle_points_bottom_left)
pygame.draw.polygon(surface, highlight_color, triangle_points_bottom_right)
#Highlight the full square of valid moves that the cursor is also hovering.
mouse_x, mouse_y = pygame.mouse.get_pos()
cursor_board_pos_y = mouse_y // self.square_size
cursor_board_pos_x = mouse_x // self.square_size
if (cursor_board_pos_y, cursor_board_pos_x) == (row, col) and (row, col) in squares_to_highlight:
pygame.draw.rect(surface, highlight_color, (col * self.square_size, row * self.square_size, self.square_size, self.square_size))
# Add red gradient circle behind the king in check
if "white_in_check" in check_status:
white_king_row, white_king_col = king_positions[0]
center_x = (white_king_col + 0.5) * self.square_size
center_y = (white_king_row + 0.5) * self.square_size
pygame.draw.circle(surface, check_gradient_color, (int(center_x), int(center_y)), self.square_size // 2, 0)
if "black_in_check" in check_status:
black_king_row, black_king_col = king_positions[1]
center_x = (black_king_col + 0.5) * self.square_size
center_y = (black_king_row + 0.5) * self.square_size
pygame.draw.circle(surface, check_gradient_color, (int(center_x), int(center_y)), self.square_size // 2, 0)
def draw_pieces(self, surface=None):
if surface is None:
surface = self.screen # Default to drawing on the screen
# Draw the pieces based on self.board_as_list
for row in range(8):
for col in range(8):