-
Notifications
You must be signed in to change notification settings - Fork 0
/
chess.py
638 lines (572 loc) · 23.7 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
import pygame
from pygame import image, display, MOUSEMOTION, MOUSEBUTTONDOWN, MOUSEBUTTONUP, QUIT
import logic
def setPeice(dict, pice, pos, imgl, rects, typeL):
dumRect = dict[pice].get_rect()
dumRect.topleft = pos[0], pos[1]
rects.append(dumRect)
imgl.append(dict[pice])
typeL.append(pice)
return imgl, rects, typeL
def spstr(stri):
return [i for i in stri]
def disRank(dic, rank, rankc, imgl1, rects1, typeL):
imgl = []
rects = []
indx = 0
passamt = 0
while indx <= 7:
if passamt != 0:
passamt -= 1
else:
try:
passamt = int(rank[0]) - 1
rank.pop(0)
except:
pic = rank[0]
rank.pop(0)
imgl, rects, typeL = setPeice(dic, pic, rankc[indx], imgl1, rects1, typeL)
indx += 1
return imgl, rects, typeL
def setBoard(dic, cord, imgl1, rects1, typeL1, position="rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"):
imgl = []
rects = []
sl = position.split("/")
casel = sl[-1].split(" ")
sl.pop(-1)
for i in casel:
sl.append(i)
rankCirdlis = []
for i in cord:
rankCirdlis.append(i)
rank8c, rank7c, rank6c, rank5c, rank4c, rank3c, rank2c, rank1c = rankCirdlis
rank8, rank7, rank6, rank5, rank4, rank3, rank2, rank1, whomove, castel, encrassont, halfm, mov = sl
rank8 = spstr(rank8)
rank7 = spstr(rank7)
rank6 = spstr(rank6)
rank5 = spstr(rank5)
rank4 = spstr(rank4)
rank3 = spstr(rank3)
rank2 = spstr(rank2)
rank1 = spstr(rank1)
imgl, rects, typeL = disRank(dic, rank8, rank8c, imgl1, rects1, typeL1)
imgl, rects, typeL = disRank(dic, rank7, rank7c, imgl1, rects1, typeL1)
imgl, rects, typeL = disRank(dic, rank6, rank6c, imgl1, rects1, typeL1)
imgl, rects, typeL = disRank(dic, rank5, rank5c, imgl1, rects1, typeL1)
imgl, rects, typeL = disRank(dic, rank4, rank4c, imgl1, rects1, typeL1)
imgl, rects, typeL = disRank(dic, rank3, rank3c, imgl1, rects1, typeL1)
imgl, rects, typeL = disRank(dic, rank2, rank2c, imgl1, rects1, typeL1)
imgl, rects, typeL = disRank(dic, rank1, rank1c, imgl1, rects1, typeL1)
return imgl, rects, typeL, whomove, castel, encrassont, int(halfm), int(mov)
def legalMoveF(move, picType, grid, legalmy, legalmx, castlelis, ensq, typeL):
blck = []
whit = []
discard = []
for help, idk in enumerate(rects):
if typeL[help].isupper():
whit.append(idk.topleft)
elif typeL[help].islower():
blck.append(idk.topleft)
listOfPiecesC = [whit, blck]
if move == "w":
if picType == "B":
legalMoves = logic.bishopMove(move, listOfPiecesC, grid, legalmy, legalmx)
elif picType == "R":
legalMoves = logic.rookMove(move, listOfPiecesC, grid, legalmy, legalmx)
elif picType == "Q":
legalMoves = logic.queenMove(move, listOfPiecesC, grid, legalmy, legalmx)
elif picType == "K":
legalMoves = logic.kingMove(move, listOfPiecesC, grid, legalmy, legalmx, castlelis)
elif picType == "N":
legalMoves = logic.knightMove(move, listOfPiecesC, grid, legalmy, legalmx)
elif picType == "P":
legalMoves, discard = logic.pawnMove(move, listOfPiecesC, grid, legalmy, legalmx, ensq)
else:
legalMoves = [grid[legalm[0]][legalm[1]]]
elif move == "b":
if picType == "b":
legalMoves = logic.bishopMove(move, listOfPiecesC, grid, legalmy, legalmx)
elif picType == "r":
legalMoves = logic.rookMove(move, listOfPiecesC, grid, legalmy, legalmx)
elif picType == "q":
legalMoves = logic.queenMove(move, listOfPiecesC, grid, legalmy, legalmx)
elif picType == "k":
legalMoves = logic.kingMove(move, listOfPiecesC, grid, legalmy, legalmx, castlelis)
elif picType == "n":
legalMoves = logic.knightMove(move, listOfPiecesC, grid, legalmy, legalmx)
elif picType == "p":
legalMoves, discard = logic.pawnMove(move, listOfPiecesC, grid, legalmy, legalmx, ensq)
else:
legalMoves = [grid[legalm[0]][legalm[1]]]
else:
legalMoves = [grid[legalm[0]][legalm[1]]]
return legalMoves, discard
def promote(piceDicr, rectS, listT, imgList, currentPicT, move):
picPos = rects[currentPicT].topleft
whatPeice = None
picChosen = False
bg = pygame.image.load('promback.png')
rectS.pop(currentPicT)
listT.pop(currentPicT)
imgList.pop(currentPicT)
if move == "w":
Q = piceDicr["Q"]
R = piceDicr["R"]
N = piceDicr["N"]
B = piceDicr["B"]
Qr = Q.get_rect()
Rr = R.get_rect()
Nr = N.get_rect()
Br = B.get_rect()
Qr.topleft = picPos
Rr.topleft = (picPos[0], picPos[1] + 125 * 1)
Nr.topleft = (picPos[0], picPos[1] + 125 * 2)
Br.topleft = (picPos[0], picPos[1] + 125 * 3)
if move == "b":
Q = piceDicr["q"]
R = piceDicr["r"]
N = piceDicr["n"]
B = piceDicr["b"]
Qr = Q.get_rect()
Rr = R.get_rect()
Nr = N.get_rect()
Br = B.get_rect()
Qr.topleft = picPos
Rr.topleft = (picPos[0], picPos[1] - 125 * 1)
Nr.topleft = (picPos[0], picPos[1] - 125 * 2)
Br.topleft = (picPos[0], picPos[1] - 125 * 3)
promImagL = [Q, R, N, B]
promrects = [Qr, Rr, Nr, Br]
while not picChosen:
for event in pygame.event.get():
if event.type == MOUSEBUTTONDOWN:
for which, pic in enumerate(promrects):
if pic.collidepoint(event.pos):
whatPeice = which
if event.type == MOUSEBUTTONUP and not picChosen:
if move == "w":
if whatPeice == 0:
whatPeice = "Q"
picChosen = True
if whatPeice == 1:
whatPeice = "R"
picChosen = True
if whatPeice == 2:
whatPeice = "N"
picChosen = True
if whatPeice == 3:
whatPeice = "B"
picChosen = True
if move == "b":
if whatPeice == 0:
whatPeice = "q"
picChosen = True
if whatPeice == 1:
whatPeice = "r"
picChosen = True
if whatPeice == 2:
whatPeice = "n"
picChosen = True
if whatPeice == 3:
whatPeice = "b"
picChosen = True
if move == "w":
screen.blit(bg, picPos)
for ofset, img in enumerate(promImagL):
screen.blit(img, (picPos[0], picPos[1] + (125 * ofset)))
if move == "b":
screen.blit(bg, (picPos[0], picPos[1] - 375))
for ofset, img in enumerate(promImagL):
screen.blit(img, (picPos[0], picPos[1] + (-125 * ofset)))
pygame.display.update()
if whatPeice == "Q":
imgList, rectS, listT = setPeice(piceDicr, whatPeice, picPos, imgList, rectS, listT)
if whatPeice == "R":
imgList, rectS, listT = setPeice(piceDicr, whatPeice, picPos, imgList, rectS, listT)
if whatPeice == "N":
imgList, rectS, listT = setPeice(piceDicr, whatPeice, picPos, imgList, rectS, listT)
if whatPeice == "B":
imgList, rectS, listT = setPeice(piceDicr, whatPeice, picPos, imgList, rectS, listT)
if whatPeice == "q":
imgList, rectS, listT = setPeice(piceDicr, whatPeice.lower(), picPos, imgList, rectS, listT)
if whatPeice == "r":
imgList, rectS, listT = setPeice(piceDicr, whatPeice.lower(), picPos, imgList, rectS, listT)
if whatPeice == "n":
imgList, rectS, listT = setPeice(piceDicr, whatPeice.lower(), picPos, imgList, rectS, listT)
if whatPeice == "b":
imgList, rectS, listT = setPeice(piceDicr, whatPeice.lower(), picPos, imgList, rectS, listT)
return rectS, listT, imgList
def encode(grid, rectS, typl, move, ensq, casl, half, mov):
result = ""
li = []
poslist = []
for pic in rectS:
poslist.append(pic.topleft)
# encode the current postion into FEN notation
for rank in grid:
rankst = ""
count = 0
pictrigger = False
cc = None
for square in rank:
if square in poslist:
if count == 0:
inc = poslist.index(square)
pict = typl[inc]
rankst = rankst + pict
else:
inc = poslist.index(square)
pict = typl[inc]
rankst = rankst + str(count)
rankst = rankst + pict
count = 0
pictrigger = True
else:
count += 1
if len(rankst) == 0:
rankst = str(count)
if count != 0 and pictrigger:
rankst = rankst + str(count)
li.append(rankst)
picepart = "/".join(li)
# encoding the enpassant sq's
emp = "-"
for y, ran in enumerate(grid):
for x, sqq in enumerate(ran):
if ensq != None and ensq == sqq:
temp = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
emp = f"{temp[y]}{x + 1}"
if len(casl) == 0:
cc = "-"
else:
cc = "".join(casl)
if move == "w":
move = "b"
elif move == "b":
move = "w"
result = f"{picepart} {move} {cc} {emp} {half} {mov}"
print(result)
return result
path = './big images/'
screen = display.set_mode((1000, 1000))
icon = image.load('chess.png')
promBack = image.load('promback.png')
darkcirce = image.load(path + "dark-circle.png")
wp = image.load(path + 'wp.png')
bp = image.load(path + 'bp.png')
wn = image.load(path + 'wn.png')
bn = image.load(path + 'bn.png')
wb = image.load(path + 'wb.png')
bb = image.load(path + 'bb.png')
wr = image.load(path + 'wr.png')
br = image.load(path + 'br.png')
wq = image.load(path + 'wq.png')
bq = image.load(path + 'bq.png')
wk = image.load(path + 'wk.png')
bk = image.load(path + 'bk.png')
picl = [wp, bp, wn, bn, wb, bb, wr, br, wq, bq, wk, bk]
piecelst = {"P": picl[0], "p": picl[1], "N": picl[2], "n": picl[3], "B": picl[4], "b": picl[5],
"R": picl[6], "r": picl[7], "Q": picl[8], "q": picl[9], "K": picl[10], "k": picl[11]}
imgl = []
rects = []
typeL = []
board = image.load(path + 'board.png')
listc = [0, 125, 250, 375, 500, 625, 750, 875]
grid = []
for y in listc:
rndl = []
for x in listc:
rndl.append((x, y))
grid.append(rndl)
postions = ["rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"]
screen.blit(board, (0, 0))
imgl, rects, typeL, move, castle, encrassont, halfm, movnum = setBoard(piecelst, grid, imgl, rects, typeL)
display.set_caption('chess')
display.set_icon(icon)
castlelis = []
display.flip()
def enpassantDecode(encrassont):
ensq = [i for i in encrassont]
temp = ["a", "b", "c", "d", "e", "f", "g", "h"]
if encrassont == "-":
ensq = None
else:
lol = temp.index(encrassont[0])
ensq = grid[int(encrassont[1]) - 1][lol]
return ensq
def castDecode(castle1):
if castle1 == "-":
castle1 = None
else:
for i in castle1:
castlelis.append(i)
rookID = {}
rookIndexW = [yep for yep, r in enumerate(typeL) if r == "R"]
rookIndexB = [yep for yep, r in enumerate(typeL) if r == "r"]
rookIndexW.reverse()
rookIndexB.reverse()
for i, side in enumerate(castlelis):
if side.isupper():
try:
if side == "K":
rookID[side] = rookIndexW[0]
except IndexError:
pass
try:
if side == "Q":
rookID[side] = rookIndexW[1]
except IndexError:
pass
if side.islower():
try:
if side == "k":
rookID[side] = rookIndexB[0]
except IndexError:
pass
try:
if side == "q":
rookID[side] = rookIndexB[1]
except IndexError:
pass
return castlelis, rookID
running = True
movingbox = None
ensq = enpassantDecode(encrassont)
castlelis, rookID = castDecode(castle)
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
if event.type == MOUSEBUTTONDOWN:
if event.button == 1:
for indx, pice in enumerate(rects):
if pice.collidepoint(event.pos):
pbp = pice.topleft
movingbox = indx
picType = typeL[movingbox]
smallestX, smallestY = 1000, 1000
for indx, rnk in enumerate(grid):
for indy, pos in enumerate(rnk):
if abs(pos[0] - pbp[0]) <= smallestX and abs(pos[1] - pbp[1]) <= smallestY:
legalm = [indx, indy]
smallestX = abs(pos[0] - pbp[0])
smallestY = abs(pos[1] - pbp[1])
if movingbox is not None:
legalMoves, discard = legalMoveF(move, picType, grid, legalm[1], legalm[0], castlelis, ensq, typeL)
if event.type == MOUSEBUTTONUP:
if event.button == 1 and movingbox is not None:
origin = grid[legalm[0]][legalm[1]]
boxPos = rects[movingbox].topleft
smallestX2, smallestY2 = 1000, 1000
ind = 0
for indxy, pos in enumerate(legalMoves):
if abs(pos[0] - boxPos[0]) <= smallestX2 and abs(pos[1] - boxPos[1]) <= smallestY2:
ind = indxy
smallestX2 = abs(pos[0] - boxPos[0])
smallestY2 = abs(pos[1] - boxPos[1])
rects[movingbox].topleft = notOrigin = legalMoves[ind]
# capturing pecies
# and removing certian rook/ enpasant things
for index, peice in enumerate(rects):
peicepos = peice.topleft
if peicepos == legalMoves[ind] and index != movingbox:
rects.pop(index)
typeL.pop(index)
imgl.pop(index)
tak = True
break
# remove pawn after en passant white
if peicepos[1] == notOrigin[1] + 125 and peicepos[0] == notOrigin[0] and typeL[index] == "p" and \
typeL[movingbox] == "P" and move == "w":
rects.pop(index)
typeL.pop(index)
imgl.pop(index)
tak = True
break
# remove pawn after en passant black
if peicepos[1] == notOrigin[1] - 125 and peicepos[0] == notOrigin[0] and typeL[index] == "P" and \
typeL[movingbox] == "p" and move == "b":
rects.pop(index)
typeL.pop(index)
imgl.pop(index)
tak = True
break
# Promotion
if notOrigin[1] == 0 and picType == "P":
# the 'if' is to prevent the peices index to be interpreted as a diffrent due to captures
if tak:
rects, typeL, imgl = promote(piecelst, rects, typeL, imgl, movingbox - 1, move)
else:
rects, typeL, imgl = promote(piecelst, rects, typeL, imgl, movingbox, move)
if notOrigin[1] == 875 and picType == "p":
rects, typeL, imgl = promote(piecelst, rects, typeL, imgl, movingbox, move)
veryDescriptiveVariableName = []
# switching moves
if move == "w" and legalMoves[ind] != origin:
cRemoveIndex = []
# en passant target set
if notOrigin[1] + 125 != origin[1]:
ensq = (origin[0], notOrigin[1] + 125)
else:
ensq = None
# moving the casle rook to the opposite side ofthe king
if picType == "K":
caslSid = None
if origin[0] - 250 == notOrigin[0]:
caslSid = "Q"
if origin[0] + 250 == notOrigin[0]:
caslSid = "K"
if caslSid == "Q":
rookcasle = rookID[caslSid]
rookpos = (notOrigin[0] + 125, notOrigin[1])
rects[rookcasle].topleft = rookpos
if caslSid == "K":
rookcasle = rookID[caslSid]
rookpos = (notOrigin[0] - 125, notOrigin[1])
rects[rookcasle].topleft = rookpos
move = "b"
movnum += 1
if movnum % 2 == 1:
halfm += 1
# castle remove check king
if picType == "K":
try:
veryDescriptiveVariableName.append(castlelis.index("K"))
except ValueError:
pass
try:
veryDescriptiveVariableName.append(castlelis.index("Q"))
except ValueError:
pass
elif move == "b" and legalMoves[ind] != origin:
cRemoveIndex = []
# en passant target set
if notOrigin[1] - 125 != origin[1]:
ensq = (origin[0], notOrigin[1] - 125)
else:
ensq = None
if picType == "k":
caslSid = None
if origin[0] - 250 == notOrigin[0]:
caslSid = "q"
if origin[0] + 250 == notOrigin[0]:
caslSid = "k"
if caslSid == "q":
rookcasle = rookID[caslSid]
rookpos = (notOrigin[0] + 125, notOrigin[1])
rects[rookcasle].topleft = rookpos
if caslSid == "k":
rookcasle = rookID[caslSid]
rookpos = (notOrigin[0] - 125, notOrigin[1])
rects[rookcasle].topleft = rookpos
move = "w"
movnum += 1
if movnum % 2 == 1:
halfm += 1
if picType == "k":
try:
veryDescriptiveVariableName.append(castlelis.index("k"))
except ValueError:
pass
try:
veryDescriptiveVariableName.append(castlelis.index("q"))
except ValueError:
pass
# rook move casle removal
rookID.clear()
caslw = []
rookIndexB = []
rookIndexW = []
rookIndexW = [yep for yep, r in enumerate(typeL) if r == "R"]
rookIndexB = [yep for yep, r in enumerate(typeL) if r == "r"]
rookIndexW.reverse()
rookIndexB.reverse()
for item in rookIndexW:
if rects[item].topleft == (875, 875):
caslw.append("K")
if rects[item].topleft == (0, 875):
caslw.append("Q")
for item in rookIndexB:
if rects[item].topleft == (875, 0):
caslw.append("k")
if rects[item].topleft == (0, 0):
caslw.append("q")
for caslnt in castlelis:
if caslnt not in caslw:
veryDescriptiveVariableName.append(castlelis.index(caslnt))
notVeryDescriptiveVariableName = []
for i in veryDescriptiveVariableName:
if i not in notVeryDescriptiveVariableName:
notVeryDescriptiveVariableName.append(i)
for ofset, ind in enumerate(notVeryDescriptiveVariableName):
castlelis.pop(ind - ofset)
for i, side in enumerate(castlelis):
if side.isupper():
try:
if side == "K":
rookID[side] = rookIndexW[0]
except IndexError:
pass
try:
if side == "Q":
rookID[side] = rookIndexW[1]
except IndexError:
pass
if side.islower():
try:
if side == "k":
rookID[side] = rookIndexB[0]
except IndexError:
pass
try:
if side == "q":
rookID[side] = rookIndexB[1]
except IndexError:
pass
# fixes a bug where you can play your own move twice by unding multiple times works now yipee
if legalMoves[ind] != origin:
postions.append(encode(grid, rects, typeL, move, ensq, castlelis, halfm, movnum))
legalMoves = []
movingbox = None
if event.type == MOUSEMOTION and movingbox is not None:
rects[movingbox].move_ip(event.rel)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_u:
screen.blit(board, (0, 0))
trig = False
try:
position = postions[-2]
postions.pop(-1)
trig = True
except IndexError:
try:
position = postions[-1]
postions.pop(-1)
trig = True
except IndexError:
print("CANNOT UNDO LOL!!!")
trig = False
if trig:
imgl = []
rects = []
typeL = []
move = None
castle = None
encrassont = None
halfm = None
movnum = None
castlelis = []
rookID = []
imgl, rects, typeL, move, castle, encrassont, halfm, movnum = setBoard(piecelst, grid, imgl, rects,
typeL, position)
movingbox = None
ensq = enpassantDecode(encrassont)
castlelis, rookID = castDecode(castle)
screen.blit(board, (0, 0))
for ing, rect in enumerate(rects):
screen.blit(imgl[ing], rect)
if movingbox != None:
for i in legalMoves:
screen.blit(darkcirce, (i[0] + 37.5, i[1] + 37.5))
pygame.display.update()
pygame.quit()