-
Notifications
You must be signed in to change notification settings - Fork 0
/
chess.py
681 lines (567 loc) · 26 KB
/
chess.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
import pygame
from pygame.locals import *
import random
from piece import Piece
from utils import Utils
import time
class Chess(object):
def __init__(self, screen, pieces_src, square_coords, square_length):
# display surface
self.screen = screen
# create an object of class to show chess pieces on the board
self.chess_pieces = Piece(pieces_src, cols=6, rows=2)
# store coordinates of the chess board squares
self.board_locations = square_coords
# length of the side of a chess board square
self.square_length = square_length
# dictionary to keeping track of player turn
self.turn = {"black": 0,
"white": 0}
# list containing possible moves for the selected piece
self.moves = []
#
self.utils = Utils()
# mapping of piece names to index of list containing piece coordinates on spritesheet
self.pieces = {
"white_pawn": 5,
"white_knight": 3,
"white_bishop": 2,
"white_rook": 4,
"white_king": 0,
"white_queen": 1,
"black_pawn": 11,
"black_knight": 9,
"black_bishop": 8,
"black_rook": 10,
"black_king": 6,
"black_queen": 7
}
# list containing captured pieces
self.captured = []
#
self.winner = ""
self.reset()
def reset(self):
# clear moves lists
self.moves = []
# randomize player turn
x = random.randint(0, 1)
if(x == 1):
self.turn["black"] = 1
elif(x == 0):
self.turn["white"] = 1
# two dimensonal dictionary containing details about each board location
# storage format is [piece_name, currently_selected, x_y_coordinate]
self.piece_location = {}
x = 0
for i in range(97, 105):
a = 8
y = 0
self.piece_location[chr(i)] = {}
while a>0:
# [piece name, currently selected, board coordinates]
self.piece_location[chr(i)][a] = ["", False, [x,y]]
a = a - 1
y = y + 1
x = x + 1
# reset the board
for i in range(97, 105):
x = 8
while x>0:
if(x==8):
if(chr(i)=='a' or chr(i)=='h'):
self.piece_location[chr(i)][x][0] = "black_rook"
elif(chr(i)=='b' or chr(i)=='g'):
self.piece_location[chr(i)][x][0] = "black_knight"
elif(chr(i)=='c' or chr(i)=='f'):
self.piece_location[chr(i)][x][0] = "black_bishop"
elif(chr(i)=='d'):
self.piece_location[chr(i)][x][0] = "black_queen"
elif(chr(i)=='e'):
self.piece_location[chr(i)][x][0] = "black_king"
elif(x==7):
self.piece_location[chr(i)][x][0] = "black_pawn"
elif(x==2):
self.piece_location[chr(i)][x][0] = "white_pawn"
elif(x==1):
if(chr(i)=='a' or chr(i)=='h'):
self.piece_location[chr(i)][x][0] = "white_rook"
elif(chr(i)=='b' or chr(i)=='g'):
self.piece_location[chr(i)][x][0] = "white_knight"
elif(chr(i)=='c' or chr(i)=='f'):
self.piece_location[chr(i)][x][0] = "white_bishop"
elif(chr(i)=='d'):
self.piece_location[chr(i)][x][0] = "white_queen"
elif(chr(i)=='e'):
self.piece_location[chr(i)][x][0] = "white_king"
x = x - 1
#
def play_turn(self):
# white color
white_color = (255, 255, 255)
# create fonts for texts
small_font = pygame.font.SysFont("comicsansms", 20)
# create text to be shown on the game menu
if self.turn["black"]:
turn_text = small_font.render("Turn: Black", True, white_color)
elif self.turn["white"]:
turn_text = small_font.render("Turn: White", True, white_color)
# show welcome text
self.screen.blit(turn_text,
((self.screen.get_width() - turn_text.get_width()) // 2,
10))
# let player with black piece play
if(self.turn["black"]):
self.move_piece("black")
# let player with white piece play
elif(self.turn["white"]):
self.move_piece("white")
# method to draw pieces on the chess board
def draw_pieces(self):
transparent_green = (0,194,39,170)
transparent_blue = (28,21,212,170)
# create a transparent surface
surface = pygame.Surface((self.square_length, self.square_length), pygame.SRCALPHA)
surface.fill(transparent_green)
surface1 = pygame.Surface((self.square_length, self.square_length), pygame.SRCALPHA)
surface1.fill(transparent_blue)
# loop to change background color of selected piece
for val in self.piece_location.values():
for value in val.values() :
# name of the piece in the current location
piece_name = value[0]
# x, y coordinates of the current piece
piece_coord_x, piece_coord_y = value[2]
# change background color of piece if it is selected
if value[1] and len(value[0]) > 5:
# if the piece selected is a black piece
if value[0][:5] == "black":
self.screen.blit(surface, self.board_locations[piece_coord_x][piece_coord_y])
if len(self.moves) > 0:
for move in self.moves:
x_coord = move[0]
y_coord = move[1]
if x_coord >= 0 and y_coord >= 0 and x_coord < 8 and y_coord < 8:
self.screen.blit(surface, self.board_locations[x_coord][y_coord])
# if the piece selected is a white piece
elif value[0][:5] == "white":
self.screen.blit(surface1, self.board_locations[piece_coord_x][piece_coord_y])
if len(self.moves) > 0:
for move in self.moves:
x_coord = move[0]
y_coord = move[1]
if x_coord >= 0 and y_coord >= 0 and x_coord < 8 and y_coord < 8:
self.screen.blit(surface1, self.board_locations[x_coord][y_coord])
# draw all chess pieces
for val in self.piece_location.values():
for value in val.values() :
# name of the piece in the current location
piece_name = value[0]
# x, y coordinates of the current piece
piece_coord_x, piece_coord_y = value[2]
# check if there is a piece at the square
if(len(value[0]) > 1):
# draw piece on the board
self.chess_pieces.draw(self.screen, piece_name,
self.board_locations[piece_coord_x][piece_coord_y])
# method to find the possible moves of the selected piece
def possible_moves(self, piece_name, piece_coord):
# list to store possible moves of the selected piece
positions = []
# find the possible locations to put a piece
if len(piece_name) > 0:
# get x, y coordinate
x_coord, y_coord = piece_coord
# calculate moves for bishop
if piece_name[6:] == "bishop":
positions = self.diagonal_moves(positions, piece_name, piece_coord)
# calculate moves for pawn
elif piece_name[6:] == "pawn":
# convert list index to dictionary key
columnChar = chr(97 + x_coord)
rowNo = 8 - y_coord
# calculate moves for white pawn
if piece_name == "black_pawn":
if y_coord + 1 < 8:
# get row in front of black pawn
rowNo = rowNo - 1
front_piece = self.piece_location[columnChar][rowNo][0]
# pawns cannot move when blocked by another another pawn
if(front_piece[6:] != "pawn"):
positions.append([x_coord, y_coord+1])
# black pawns can move two positions ahead for first move
if y_coord < 2:
positions.append([x_coord, y_coord+2])
# EM PASSANT
# diagonal to the left
if x_coord - 1 >= 0 and y_coord + 1 < 8:
x = x_coord - 1
y = y_coord + 1
# convert list index to dictionary key
columnChar = chr(97 + x)
rowNo = 8 - y
to_capture = self.piece_location[columnChar][rowNo]
if(to_capture[0][:5] == "white"):
positions.append([x, y])
# diagonal to the right
if x_coord + 1 < 8 and y_coord + 1 < 8:
x = x_coord + 1
y = y_coord + 1
# convert list index to dictionary key
columnChar = chr(97 + x)
rowNo = 8 - y
to_capture = self.piece_location[columnChar][rowNo]
if(to_capture[0][:5] == "white"):
positions.append([x, y])
# calculate moves for white pawn
elif piece_name == "white_pawn":
if y_coord - 1 >= 0:
# get row in front of black pawn
rowNo = rowNo + 1
front_piece = self.piece_location[columnChar][rowNo][0]
# pawns cannot move when blocked by another another pawn
if(front_piece[6:] != "pawn"):
positions.append([x_coord, y_coord-1])
# black pawns can move two positions ahead for first move
if y_coord > 5:
positions.append([x_coord, y_coord-2])
# EM PASSANT
# diagonal to the left
if x_coord - 1 >= 0 and y_coord - 1 >= 0:
x = x_coord - 1
y = y_coord - 1
# convert list index to dictionary key
columnChar = chr(97 + x)
rowNo = 8 - y
to_capture = self.piece_location[columnChar][rowNo]
if(to_capture[0][:5] == "black"):
positions.append([x, y])
# diagonal to the right
if x_coord + 1 < 8 and y_coord - 1 >= 0:
x = x_coord + 1
y = y_coord - 1
# convert list index to dictionary key
columnChar = chr(97 + x)
rowNo = 8 - y
to_capture = self.piece_location[columnChar][rowNo]
if(to_capture[0][:5] == "black"):
positions.append([x, y])
# calculate moves for rook
elif piece_name[6:] == "rook":
# find linear moves
positions = self.linear_moves(positions, piece_name, piece_coord)
# calculate moves for knight
elif piece_name[6:] == "knight":
# left positions
if(x_coord - 2) >= 0:
if(y_coord - 1) >= 0:
positions.append([x_coord-2, y_coord-1])
if(y_coord + 1) < 8:
positions.append([x_coord-2, y_coord+1])
# top positions
if(y_coord - 2) >= 0:
if(x_coord - 1) >= 0:
positions.append([x_coord-1, y_coord-2])
if(x_coord + 1) < 8:
positions.append([x_coord+1, y_coord-2])
# right positions
if(x_coord + 2) < 8:
if(y_coord - 1) >= 0:
positions.append([x_coord+2, y_coord-1])
if(y_coord + 1) < 8:
positions.append([x_coord+2, y_coord+1])
# bottom positions
if(y_coord + 2) < 8:
if(x_coord - 1) >= 0:
positions.append([x_coord-1, y_coord+2])
if(x_coord + 1) < 8:
positions.append([x_coord+1, y_coord+2])
# calculate movs for king
elif piece_name[6:] == "king":
if(y_coord - 1) >= 0:
# top spot
positions.append([x_coord, y_coord-1])
if(y_coord + 1) < 8:
# bottom spot
positions.append([x_coord, y_coord+1])
if(x_coord - 1) >= 0:
# left spot
positions.append([x_coord-1, y_coord])
# top left spot
if(y_coord - 1) >= 0:
positions.append([x_coord-1, y_coord-1])
# bottom left spot
if(y_coord + 1) < 8:
positions.append([x_coord-1, y_coord+1])
if(x_coord + 1) < 8:
# right spot
positions.append([x_coord+1, y_coord])
# top right spot
if(y_coord - 1) >= 0:
positions.append([x_coord+1, y_coord-1])
# bottom right spot
if(y_coord + 1) < 8:
positions.append([x_coord+1, y_coord+1])
# calculate movs for queen
elif piece_name[6:] == "queen":
# find diagonal positions
positions = self.diagonal_moves(positions, piece_name, piece_coord)
# find linear moves
positions = self.linear_moves(positions, piece_name, piece_coord)
# list of positions to be removed
to_remove = []
# remove positions that overlap other pieces of the current player
for pos in positions:
x, y = pos
# convert list index to dictionary key
columnChar = chr(97 + x)
rowNo = 8 - y
# find the pieces to remove
des_piece_name = self.piece_location[columnChar][rowNo][0]
if(des_piece_name[:5] == piece_name[:5]):
to_remove.append(pos)
# remove position from positions list
for i in to_remove:
positions.remove(i)
# return list containing possible moves for the selected piece
return positions
def move_piece(self, turn):
# get the coordinates of the square selected on the board
square = self.get_selected_square()
# if a square was selected
if square:
# get name of piece on the selected square
piece_name = square[0]
# color of piece on the selected square
piece_color = piece_name[:5]
# board column character
columnChar = square[1]
# board row number
rowNo = square[2]
# get x, y coordinates
x, y = self.piece_location[columnChar][rowNo][2]
# if there's a piece on the selected square
if(len(piece_name) > 0) and (piece_color == turn):
# find possible moves for thr piece
self.moves = self.possible_moves(piece_name, [x,y])
# checkmate mechanism
p = self.piece_location[columnChar][rowNo]
for i in self.moves:
if i == [x, y]:
if(p[0][:5] == turn) or len(p[0]) == 0:
self.validate_move([x,y])
else:
self.capture_piece(turn, [columnChar, rowNo], [x,y])
# only the player with the turn gets to play
if(piece_color == turn):
# change selection flag from all other pieces
for k in self.piece_location.keys():
for key in self.piece_location[k].keys():
self.piece_location[k][key][1] = False
# change selection flag of the selected piece
self.piece_location[columnChar][rowNo][1] = True
def get_selected_square(self):
# get left event
left_click = self.utils.left_click_event()
# if there's a mouse event
if left_click:
# get mouse event
mouse_event = self.utils.get_mouse_event()
for i in range(len(self.board_locations)):
for j in range(len(self.board_locations)):
rect = pygame.Rect(self.board_locations[i][j][0], self.board_locations[i][j][1],
self.square_length, self.square_length)
collision = rect.collidepoint(mouse_event[0], mouse_event[1])
if collision:
selected = [rect.x, rect.y]
# find x, y coordinates the selected square
for k in range(len(self.board_locations)):
#
try:
l = None
l = self.board_locations[k].index(selected)
if l != None:
#reset color of all selected pieces
for val in self.piece_location.values():
for value in val.values() :
# [piece name, currently selected, board coordinates]
if not value[1]:
value[1] = False
# get column character and row number of the chess piece
columnChar = chr(97 + k)
rowNo = 8 - l
# get the name of the
piece_name = self.piece_location[columnChar][rowNo][0]
return [piece_name, columnChar, rowNo]
except:
pass
else:
return None
def capture_piece(self, turn, chess_board_coord, piece_coord):
# get x, y coordinate of the destination piece
x, y = piece_coord
# get chess board coordinate
columnChar, rowNo = chess_board_coord
p = self.piece_location[columnChar][rowNo]
if p[0] == "white_king":
self.winner = "Black"
print("Black wins")
elif p[0] == "black_king":
self.winner = "White"
print("White wins")
# add the captured piece to list
self.captured.append(p)
# move source piece to its destination
self.validate_move(piece_coord)
def validate_move(self, destination):
desColChar = chr(97 + destination[0])
desRowNo = 8 - destination[1]
for k in self.piece_location.keys():
for key in self.piece_location[k].keys():
board_piece = self.piece_location[k][key]
if board_piece[1]:
# unselect the source piece
self.piece_location[k][key][1] = False
# get the name of the source piece
piece_name = self.piece_location[k][key][0]
# move the source piece to the destination piece
self.piece_location[desColChar][desRowNo][0] = piece_name
src_name = self.piece_location[k][key][0]
# remove source piece from its current position
self.piece_location[k][key][0] = ""
# change turn
if(self.turn["black"]):
self.turn["black"] = 0
self.turn["white"] = 1
elif("white"):
self.turn["black"] = 1
self.turn["white"] = 0
src_location = k + str(key)
des_location = desColChar + str(desRowNo)
print("{} moved from {} to {}".format(src_name, src_location, des_location))
# helper function to find diagonal moves
def diagonal_moves(self, positions, piece_name, piece_coord):
# reset x and y coordinate values
x, y = piece_coord
# find top left diagonal spots
while(True):
x = x - 1
y = y - 1
if(x < 0 or y < 0):
break
else:
positions.append([x,y])
# convert list index to dictionary key
columnChar = chr(97 + x)
rowNo = 8 - y
p = self.piece_location[columnChar][rowNo]
# stop finding possible moves if blocked by a piece
if len(p[0]) > 0 and piece_name[:5] != p[:5]:
break
# reset x and y coordinate values
x, y = piece_coord
# find bottom right diagonal spots
while(True):
x = x + 1
y = y + 1
if(x > 7 or y > 7):
break
else:
positions.append([x,y])
# convert list index to dictionary key
columnChar = chr(97 + x)
rowNo = 8 - y
p = self.piece_location[columnChar][rowNo]
# stop finding possible moves if blocked by a piece
if len(p[0]) > 0 and piece_name[:5] != p[:5]:
break
# reset x and y coordinate values
x, y = piece_coord
# find bottom left diagonal spots
while(True):
x = x - 1
y = y + 1
if (x < 0 or y > 7):
break
else:
positions.append([x,y])
# convert list index to dictionary key
columnChar = chr(97 + x)
rowNo = 8 - y
p = self.piece_location[columnChar][rowNo]
# stop finding possible moves if blocked by a piece
if len(p[0]) > 0 and piece_name[:5] != p[:5]:
break
# reset x and y coordinate values
x, y = piece_coord
# find top right diagonal spots
while(True):
x = x + 1
y = y - 1
if(x > 7 or y < 0):
break
else:
positions.append([x,y])
# convert list index to dictionary key
columnChar = chr(97 + x)
rowNo = 8 - y
p = self.piece_location[columnChar][rowNo]
# stop finding possible moves if blocked by a piece
if len(p[0]) > 0 and piece_name[:5] != p[:5]:
break
return positions
# helper function to find horizontal and vertical moves
def linear_moves(self, positions, piece_name, piece_coord):
# reset x, y coordniate value
x, y = piece_coord
# horizontal moves to the left
while(x > 0):
x = x - 1
positions.append([x,y])
# convert list index to dictionary key
columnChar = chr(97 + x)
rowNo = 8 - y
p = self.piece_location[columnChar][rowNo]
# stop finding possible moves if blocked by a piece
if len(p[0]) > 0 and piece_name[:5] != p[:5]:
break
# reset x, y coordniate value
x, y = piece_coord
# horizontal moves to the right
while(x < 7):
x = x + 1
positions.append([x,y])
# convert list index to dictionary key
columnChar = chr(97 + x)
rowNo = 8 - y
p = self.piece_location[columnChar][rowNo]
# stop finding possible moves if blocked by a piece
if len(p[0]) > 0 and piece_name[:5] != p[:5]:
break
# reset x, y coordniate value
x, y = piece_coord
# vertical moves upwards
while(y > 0):
y = y - 1
positions.append([x,y])
# convert list index to dictionary key
columnChar = chr(97 + x)
rowNo = 8 - y
p = self.piece_location[columnChar][rowNo]
# stop finding possible moves if blocked by a piece
if len(p[0]) > 0 and piece_name[:5] != p[:5]:
break
# reset x, y coordniate value
x, y = piece_coord
# vertical moves downwards
while(y < 7):
y = y + 1
positions.append([x,y])
# convert list index to dictionary key
columnChar = chr(97 + x)
rowNo = 8 - y
p = self.piece_location[columnChar][rowNo]
# stop finding possible moves if blocked by a piece
if len(p[0]) > 0 and piece_name[:5] != p[:5]:
break
return positions