-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathEngine.py
More file actions
1174 lines (950 loc) · 39 KB
/
Copy pathEngine.py
File metadata and controls
1174 lines (950 loc) · 39 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
######################################################################################################
############################################### ENGINE ###############################################
######################################################################################################
#
# in binary every square on the board is accessed by 2 to the power of whatever square it is
#
# Things to note from this
#
# To move upwards you subtract 8 and to move downwards add 8
#
# Diagonal movement
# ---------------------
# top right = i - 7
# top left = i - 9
# bottom right = i + 9
# bottom left = i + 7
#
######################################################################################################
######################################################################################################
######################################################################################################
import math
import random
import UI_Handler as UI
import Settings.PROJECT_SETTINGS as settings
global signalGameUIEvents
global currentBoardFullData
#------------------------------------------------------------------------------------------------------------------------
# bitboards
global bitWordBoard
global whitePieces
global blackPieces
global whitePawns
global whiteHorses
global whiteBishops
global whiteRooks
global whiteQueens
global whiteKing
global blackPawns
global blackHorses
global blackBishops
global blackRooks
global blackQueens
global blackKing
#------------------------------------------------------------------------------------------------------------------------
# colours "WHITE" and "BLACK"
global playerColour
global enemyColour
#------------------------------------------------------------------------------------------------------------------------
# used for tracking castling
global wKingMoved
global wRooksMoved
global bKingMoved
global bRooksMoved
global wqueenSide
global wkingSide
global bqueenSide
global bkingSide
#------------------------------------------------------------------------------------------------------------------------
# offsets needed for all horizonatal and diagonal moves shown visually in the diagram at the top of the code
# use first 4 indexes for straight line moves like the rook and the last 4 for diagonal moves or all indexes for the queen
directionOffsets = [-8,8,1,-1,-9,9,-7,7]
# 2d array that stores squares to edge for every square on the board and is pre computed to allow quicker lookup times
global squaresToEdge
global lastMove
global Checkmate
global Stalemate
lastMove = [0,0]
pieceLookup = {
"BLACKROOK": "♖",
"BLACKHORSE": "♘",
"BLACKBISHOP": "♗",
"BLACKQUEEN": "♕",
"BLACKKING": "♔",
"BLACKPAWN": "♙",
"WHITEROOK": "♜",
"WHITEHORSE": "♞",
"WHITEBISHOP": "♝",
"WHITEQUEEN": "♛",
"WHITEKING": "♚",
"WHITEPAWN": "♟",
"NONENONE": " ",
"MOVEOVERLAY": "X"
}
pieceValue = {
"PAWN": 1,
"HORSE": 3,
"BISHOP": 3,
"ROOK": 5,
"QUEEN": 9,
"KING": 0
}
def assignColours(plrColour):
global playerColour
global enemyColour
if plrColour == "WHITE":
playerColour = "WHITE"
enemyColour = "BLACK"
else:
playerColour = "BLACK"
enemyColour = "WHITE"
return enemyColour
def switchColours(colour):
if colour == "WHITE":
return "BLACK"
else:
return "WHITE"
def getColour(square):
if square == None:
return None
# input is an int
if square & whitePieces != 0:
return "WHITE"
elif square & blackPieces != 0:
return "BLACK"
else:
return "NONE"
def whiteAssignment(i,value):
global whitePawns
global whiteHorses
global whiteBishops
global whiteRooks
global whiteQueens
global whiteKing
if i == 0:
whitePawns = value
elif i == 1:
whiteBishops = value
elif i == 2:
whiteHorses = value
elif i == 3:
whiteRooks = value
elif i == 4:
whiteQueens = value
elif i == 5:
whiteKing = value
def blackAssignment(i,value):
global blackPawns
global blackHorses
global blackBishops
global blackRooks
global blackQueens
global blackKing
if i == 0:
blackPawns = value
elif i == 1:
blackBishops = value
elif i == 2:
blackHorses = value
elif i == 3:
blackRooks = value
elif i == 4:
blackQueens = value
elif i == 5:
blackKing = value
def makeMove(square,chosenLegalMove,colour,isFake=False,extraInfo=None):
isCapture = updateBoard(square,chosenLegalMove,colour,isFake,extraInfo) # w and b are arrays of piece bitboards [Pawns,Bishops,Horses,Rooks,Queens,King]
if not isFake:
global currentBoardFullData
castlingData = [wkingSide,wqueenSide,wKingMoved,wRooksMoved,bkingSide,bqueenSide,bKingMoved,bRooksMoved]
whitePiecesData = [whitePawns, whiteBishops, whiteHorses, whiteRooks, whiteQueens, whiteKing]
blackPiecesData = [blackPawns, blackBishops, blackHorses, blackRooks, blackQueens, blackKing]
currentBoardFullData = [whitePiecesData,blackPiecesData,castlingData]
kingIsChecked = getCheckMoves(switchColours(colour))
if not settings.isConsoleApplication():
signalGameUIEvents.addMoveToTracker(getPieceTypeFromSquare(chosenLegalMove),getColour(chosenLegalMove),isCapture,kingIsChecked,lastMove[0],lastMove[1])
def updateBoard(square,chosenLegalMove,colour,isFake,extraInfo):
global bitWordBoard
global whitePieces
global blackPieces
global lastMove
global whitePawns
global blackPawns
isCapture = False
w = [whitePawns, whiteBishops, whiteHorses, whiteRooks, whiteQueens, whiteKing]
b = [blackPawns, blackBishops, blackHorses, blackRooks, blackQueens, blackKing]
nonBinSquare = int(math.log(square,2))
nonBinMove = int(math.log(chosenLegalMove,2))
if isEnPassant(nonBinSquare,square,nonBinMove):
pieceUIToUpdate = enPassant(nonBinMove,nonBinSquare,colour)
if not settings.isConsoleApplication() and not isFake:
signalGameUIEvents.emitEnPassantEvent(pieceUIToUpdate)
if isCastling(nonBinSquare,square, nonBinMove):
rookMoves,sideOfCastle = castle(chosenLegalMove,colour)
if not settings.isConsoleApplication() and not isFake:
signalGameUIEvents.emitCastleEvent(rookMoves,sideOfCastle)
if colour == "WHITE":
for i in range(6):
if square & w[i] != 0:
# this is the set its in
w[i] = w[i] ^ square
w[i] = w[i] | chosenLegalMove
whiteAssignment(i,w[i])
if chosenLegalMove & b[i] != 0:
isCapture = True
b[i] = b[i] ^ chosenLegalMove
blackAssignment(i,b[i])
else:
for i in range(6):
if square & b[i] != 0:
# this is the set its in
b[i] = b[i] ^ square
b[i] = b[i] | chosenLegalMove
blackAssignment(i,b[i])
if chosenLegalMove & w[i] != 0:
isCapture = True
w[i] = w[i] ^ chosenLegalMove
whiteAssignment(i,w[i])
if isPromoting(chosenLegalMove,nonBinMove):
piece = None
if playerColour == colour:
if not isFake:
if not settings.isConsoleApplication():
piece = "QUEEN"
else:
piece = UI.askForPromotePiece()
promote(chosenLegalMove,colour,piece)
if not settings.isConsoleApplication() and not isFake:
signalGameUIEvents.emitPromotionEvent(nonBinMove,colour,piece)
else:
promote(chosenLegalMove,colour,extraInfo)
lastMove = [nonBinSquare,nonBinMove]
whitePieces = whitePawns | whiteBishops | whiteHorses | whiteRooks | whiteQueens | whiteKing
blackPieces = blackPawns | blackBishops | blackHorses | blackRooks | blackQueens | blackKing
bitWordBoard = whitePieces | blackPieces
canCastle(colour)
return isCapture
def precomputeSquaresToEdge():
global squaresToEdge
squaresToEdge = [None] * 64
for file in range(8):
for rank in range(8):
north = rank
south = 7 - rank
west = file
east = 7 - file
northEast = min(north,east)
southEast = min(south,east)
southWest = min(south,west)
northWest = min(north,west)
currentSquare = (rank * 8) + file
squaresToEdge[currentSquare] = [north,south,east,west,northWest,southEast,northEast,southWest]
def getPieceTypeFromSquare(square):
if (square & (whitePawns | blackPawns)) != 0:
return "PAWN"
elif (square & (whiteRooks | blackRooks)) != 0:
return "ROOK"
elif (square & (whiteBishops | blackBishops)) != 0:
return "BISHOP"
elif (square & (whiteHorses | blackHorses)) != 0:
return "HORSE"
elif (square & (whiteQueens | blackQueens)) != 0:
return "QUEEN"
elif (square & (whiteKing | blackKing)) != 0:
return "KING"
else:
return "NONE"
def generateAllMoves(turn,isResponses,movesToSearch=[]):
legalMoves = []
moves = []
if movesToSearch != []:
turnIndex = 0
for i in movesToSearch:
turnIndex = turnIndex + 1
if turnIndex % 2 == 1:
makeMove(int(math.pow(2,i[0])),int(math.pow(2,i[1])),enemyColour,True)
else:
makeMove(int(math.pow(2,i[0])),int(math.pow(2,i[1])),playerColour,True)
for file in range(8):
for rank in range(8):
currentSquareIndex = (rank * 8) + file
squareBinary = int(math.pow(2,currentSquareIndex))
if getColour(squareBinary) == turn:
pieceType = getPieceTypeFromSquare(squareBinary)
if pieceType == "ROOK" or pieceType == "BISHOP" or pieceType == "QUEEN":
moves = moves + generateSlidingPieceMoves(currentSquareIndex, pieceType,turn)
elif pieceType == "PAWN":
moves = moves + generatePawnMoves(currentSquareIndex, turn)
elif pieceType == "HORSE":
moves = moves + generateHorseMoves(currentSquareIndex,turn)
elif pieceType == "KING":
moves = moves + generateKingMoves(currentSquareIndex,turn)
if not isResponses:
for move in moves:
makeMove(int(math.pow(2,move[0])),int(math.pow(2,move[1])),turn,True,None)
if not inCheck(turn,generateAllMoves(switchColours(turn),True,movesToSearch)): # if opponent doesnt put you in check
startValid = move[0] <= 63 and move[0] >= 0
endValid = move[1] <= 63 and move[1] >= 0
if startValid and endValid:
legalMoves = legalMoves + [move]
resetData()
if movesToSearch != []:
turnIndex = 0
for i in movesToSearch:
turnIndex = turnIndex + 1
if turnIndex % 2 == 1:
makeMove(int(math.pow(2,i[0])),int(math.pow(2,i[1])),enemyColour,True)
else:
makeMove(int(math.pow(2,i[0])),int(math.pow(2,i[1])),playerColour,True)
if len(legalMoves) == 0:
if inCheck(turn,generateAllMoves(switchColours(turn),True,movesToSearch)):
if movesToSearch == []:
global Checkmate
Checkmate = True
else:
if movesToSearch == []:
global Stalemate
Stalemate = True
if settings.isConsoleApplication():
UI.clear()
UI.stalemateUI()
UI.sleep(10)
return legalMoves
return moves
def addCheckMove(move):
global checkMoves
checkMoves = checkMoves + [move]
def generatePawnMoves(startSquare,colour):
moves = []
directionEnd = 1
direction = -1
binarySquare = int(math.pow(2,startSquare))
playerOnStartingRank = startSquare >= 48 and startSquare <= 55 and (playerColour == colour)
enemyOnStartingRank = startSquare >= 8 and startSquare <= 15 and (enemyColour == colour)
onLeftEdge = startSquare in [0,8,16,24,32,40,48,56]
onRightEdge = startSquare in [7,15,23,31,39,47,55,63]
enemyLeft = getColour(binarySquare >> 9) == enemyColour
enemyRight = getColour(binarySquare >> 7) == enemyColour
playerLeft = getColour(binarySquare << 7) == playerColour
playerRight = getColour(binarySquare << 9) == playerColour
canTakePieceLeft = (enemyLeft and colour == playerColour) or (playerLeft and colour == enemyColour)
canTakePieceRight = (enemyRight and colour == playerColour) or (playerRight and colour == enemyColour)
if (playerOnStartingRank) or (enemyOnStartingRank):
directionEnd = 2
if playerColour == colour:
direction = 0
elif enemyColour == colour:
direction = 1
if canTakePieceLeft and not onLeftEdge:
if playerColour == colour:
moves = moves + [[startSquare, startSquare - 9]]
else:
moves = moves + [[startSquare, startSquare + 7]]
if canTakePieceRight and not onRightEdge:
if playerColour == colour:
moves = moves + [[startSquare, startSquare - 7]]
else:
moves = moves + [[startSquare, startSquare + 9]]
if direction != -1:
for squares in range(directionEnd):
targetSquare = startSquare + (directionOffsets[direction] * (squares + 1))
if getColour(int(math.pow(2,targetSquare))) == playerColour:
break
if getColour(int(math.pow(2,targetSquare))) == enemyColour:
break
moves = moves + [[startSquare,targetSquare]]
if (startSquare >= 32 and startSquare <= 39 and enemyColour == colour) or (startSquare >= 24 and startSquare <= 31 and playerColour == colour):
if lastMove != None:
if abs(lastMove[1] - startSquare) == 1:
if (lastMove[0] >= 8 and lastMove[0] <= 15) and (lastMove[1] == lastMove[0] + 16) and playerColour == colour and getPieceTypeFromSquare(int(math.pow(2,lastMove[1]))) == "PAWN":
moves = moves + [[startSquare, lastMove[1] - 8]]
if (lastMove[0] >= 48 and lastMove[0] <= 55) and (lastMove[1] == lastMove[0] - 16) and enemyColour == colour and getPieceTypeFromSquare(int(math.pow(2,lastMove[1]))) == "PAWN":
moves = moves + [[startSquare, lastMove[1] + 8]]
else:
print("ERROR")
return moves
def generateHorseMoves(startSquare,colour):
moves = []
for i in range(4):
squareBetween = startSquare + (directionOffsets[i] * 2)
targetSquareLeft = None
targetSquareRight = None
if i == 0 or i == 1:
if squaresToEdge[startSquare][3] >= 1:
targetSquareLeft = squareBetween - 1
if squaresToEdge[startSquare][2] >= 1:
targetSquareRight = squareBetween + 1
else:
if squaresToEdge[startSquare][i] >= 2:
targetSquareLeft = squareBetween + directionOffsets[0]
targetSquareRight = squareBetween + directionOffsets[1]
if targetSquareLeft != None:
if (getColour(int(math.pow(2,targetSquareLeft))) != colour) and targetSquareLeft >= 0:
moves = moves + [[startSquare,targetSquareLeft]]
if targetSquareRight != None:
if (getColour(int(math.pow(2,targetSquareRight))) != colour) and targetSquareRight >= 0:
moves = moves + [[startSquare,targetSquareRight]]
return moves
def generateKingMoves(startSquare,colour):
moves = []
for i in range(8):
if squaresToEdge[startSquare][i] >= 1:
targetSquare = startSquare + directionOffsets[i]
if getColour(int(math.pow(2,targetSquare))) != colour:
moves = moves + [[startSquare, targetSquare]]
kingSide,queenSide = canCastle(colour)
if playerColour == "WHITE":
if kingSide:
if getPieceTypeFromSquare(int(math.pow(2,startSquare + 1))) == "NONE" and getPieceTypeFromSquare(int(math.pow(2,startSquare + 2))) == "NONE":
moves = moves + [[startSquare, startSquare + 2]]
if queenSide:
if getPieceTypeFromSquare(int(math.pow(2,startSquare - 1))) == "NONE" and getPieceTypeFromSquare(int(math.pow(2,startSquare - 2))) == "NONE" and getPieceTypeFromSquare(int(math.pow(2,startSquare - 3))) == "NONE":
moves = moves + [[startSquare, startSquare - 2]]
else:
if kingSide:
if getPieceTypeFromSquare(int(math.pow(2,startSquare - 1))) == "NONE" and getPieceTypeFromSquare(int(math.pow(2,startSquare - 2))) == "NONE":
moves = moves + [[startSquare, startSquare - 2]]
if queenSide:
if getPieceTypeFromSquare(int(math.pow(2,startSquare + 1))) == "NONE" and getPieceTypeFromSquare(int(math.pow(2,startSquare + 2))) == "NONE" and getPieceTypeFromSquare(int(math.pow(2,startSquare + 3))) == "NONE":
moves = moves + [[startSquare, startSquare + 2]]
return moves
def generateSlidingPieceMoves(startSquare, piece,colour):
# pieces such as the queen,bishop and rook
global squaresToEdge
moves = []
directionStart = 0
directionEnd = 8
if piece == "ROOK":
directionStart = 0
directionEnd = 4
elif piece == "BISHOP":
directionStart = 4
directionEnd = 8
for direction in range(directionStart, directionEnd):
for squares in range(squaresToEdge[startSquare][direction]):
targetSquare = startSquare + (directionOffsets[direction] * (squares + 1)) # from start square to edge of board
if getColour(int(math.pow(2,targetSquare))) == colour:
break
moves = moves + [[startSquare,targetSquare]]
if getColour(int(math.pow(2,targetSquare))) != colour and getColour(int(math.pow(2,targetSquare))) != "NONE":
break
return moves
def filterMovesBySquare(square, colour):
squaresMoves = []
pseudoLegalMoves = generateAllMoves(colour,False)
for move in pseudoLegalMoves:
if move[0] == square:
squaresMoves = squaresMoves + [move]
return squaresMoves
def isEnPassant(square,binary,chosenLegalMove):
if (chosenLegalMove - square) % 8 != 0 and getPieceTypeFromSquare(binary) == "PAWN" and getPieceTypeFromSquare(int(math.pow(2,chosenLegalMove))) == "NONE":
return True
return False
def enPassant(nonBinMove,nonBinSquare,colour):
global whitePawns
global blackPawns
direction = 0
if nonBinMove - nonBinSquare > 0:
direction = -1
else:
direction = 1
if colour == "WHITE":
blackPawns = blackPawns ^ int(math.pow(2, nonBinMove + (direction * 8)))
else:
whitePawns = whitePawns ^ int(math.pow(2, nonBinMove + (direction * 8)))
return nonBinMove + (direction * 8)
def isCastling(square,binary, chosenLegalMove):
if playerColour == "WHITE":
legalMoves = [6,2,58,62]
if (square == 4 or square == 60) and (chosenLegalMove in legalMoves) and getPieceTypeFromSquare(binary) == "KING":
return True
else:
legalMoves = [5,1,57,61]
if (square == 3 or square == 59) and (chosenLegalMove in legalMoves) and getPieceTypeFromSquare(binary) == "KING":
return True
return False
def castle(chosenLegalMove,colour):
placementForRook = int(math.log(chosenLegalMove,2))
if playerColour == "WHITE":
if placementForRook == 6:
updateBoard(int(math.pow(2,7)),int(math.pow(2,5)),colour,False,None)
return [7,5],"KINGSIDE"
elif placementForRook == 62:
updateBoard(int(math.pow(2,63)),int(math.pow(2,61)),colour,False,None)
return [63,61],"KINGSIDE"
elif placementForRook == 2:
updateBoard(1,3,colour,False,None)
return [1,3],"QUEENSIDE"
elif placementForRook == 58:
updateBoard(int(math.pow(2,56)),int(math.pow(2,59)),colour,False,None)
return [56,59],"QUEENSIDE"
else:
if placementForRook == 5:
updateBoard(int(math.pow(2,7)),int(math.pow(2,4)),colour,False,None)
return [7,4],"QUEENSIDE"
elif placementForRook == 61:
updateBoard(int(math.pow(2,63)),int(math.pow(2,60)),colour,False,None)
return [63,60],"QUEENSIDE"
elif placementForRook == 1:
updateBoard(1,2,colour,False,None)
return [1,2],"KINGSIDE"
elif placementForRook == 57:
updateBoard(int(math.pow(2,56)),int(math.pow(2,58)),colour,False,None)
return [56,58],"KINGSIDE"
def isPromoting(binary,chosenLegalMove):
if ((chosenLegalMove >= 0 and chosenLegalMove <= 7) or (chosenLegalMove >= 56 and chosenLegalMove <= 63)) and getPieceTypeFromSquare(binary) == "PAWN":
return True
return False
def promote(chosenLegalMove,colour,piece):
global whiteHorses
global whiteBishops
global whiteRooks
global whiteQueens
global whitePawns
global blackPawns
global blackHorses
global blackBishops
global blackRooks
global blackQueens
if colour == "WHITE":
whitePawns = whitePawns ^ chosenLegalMove
if piece == "BISHOP":
whiteBishops = whiteBishops | chosenLegalMove
elif piece == "HORSE":
whiteHorses = whiteHorses | chosenLegalMove
elif piece == "ROOK":
whiteRooks = whiteRooks | chosenLegalMove
elif piece == "QUEEN":
whiteQueens = whiteQueens | chosenLegalMove
else:
blackPawns = blackPawns ^ chosenLegalMove
if piece == "BISHOP":
blackBishops = blackBishops | chosenLegalMove
elif piece == "HORSE":
blackHorses = blackHorses | chosenLegalMove
elif piece == "ROOK":
blackRooks = blackRooks | chosenLegalMove
elif piece == "QUEEN":
blackQueens = blackQueens | chosenLegalMove
def canCastle(colour):
global wKingMoved
global wRooksMoved
global bKingMoved
global bRooksMoved
global whiteRooks
global whiteKing
global blackRooks
global blackKing
global wqueenSide
global wkingSide
global bqueenSide
global bkingSide
if colour == "WHITE":
if whiteRooks != 0:
if wKingMoved & whiteKing == 0:
wKingMoved = 0
wkingSide = False
wqueenSide = False
if wRooksMoved & whiteRooks != whiteRooks:
if wRooksMoved > whiteRooks:
wkingSide = False
if wRooksMoved < whiteRooks:
wqueenSide = False
return wkingSide,wqueenSide
else:
if blackRooks != 0:
if bKingMoved & blackKing == 0:
bKingMoved = 0
bkingSide = False
bqueenSide = False
if bRooksMoved & blackRooks != blackRooks:
if bRooksMoved < blackRooks:
bkingSide = False
if bRooksMoved > blackRooks:
bqueenSide = False
return bkingSide,bqueenSide
def inCheck(colour,moves):
global blackKing
global whiteKing
if colour == "WHITE":
if whiteKing == 0:
return True
kingPos = int(math.log(whiteKing,2))
for i in moves:
if i[1] == kingPos:
return True
else:
if blackKing == 0:
return True
kingPos = int(math.log(blackKing,2))
for i in moves:
if i[1] == kingPos:
return True
return False
def getCheckMoves(colour):
squareToStart = None
if colour == "WHITE":
global whiteKing
squareToStart = int(math.log(whiteKing,2))
else:
global blackKing
squareToStart = int(math.log(blackKing,2))
bishopMoves = generateSlidingPieceMoves(squareToStart,"BISHOP",colour)
castleMoves = generateSlidingPieceMoves(squareToStart,"ROOK",colour)
horseMoves = generateHorseMoves(squareToStart,colour)
piece = getPieceTypeFromSquare(int(math.pow(2,lastMove[1])))
for horseMove in horseMoves:
if horseMove[1] == lastMove[1]:
if piece == "HORSE":
return True
for castleMove in castleMoves:
if castleMove[1] == lastMove[1]:
if piece == "ROOK" or piece == "QUEEN":
return True
for bishopMove in bishopMoves:
if bishopMove[1] == lastMove[1]:
if piece == "BISHOP" or piece == "QUEEN":
return True
return False
def evaluate():
evaluationScore = 0
for file in range(8):
for rank in range(8):
currentSquareIndex = (rank * 8) + file
squareBinary = int(math.pow(2,currentSquareIndex))
pieceType = getPieceTypeFromSquare(squareBinary)
colour = getColour(squareBinary)
if not pieceType in ["KING","NONE"]:
if colour == "WHITE":
evaluationScore = evaluationScore + pieceValue[pieceType]
else:
evaluationScore = evaluationScore - pieceValue[pieceType]
return evaluationScore
def getBestEvalMove(colour,currentBestMove,newEvaluation,move):
eval = evaluate()
if currentBestMove != None:
if colour == "WHITE":
if eval > newEvaluation:
currentBestMove = move
newEvaluation = eval
else:
if eval < newEvaluation:
currentBestMove = move
newEvaluation = eval
else:
currentBestMove = move
return currentBestMove,newEvaluation
def search(moves,colour,searchMoves=[]):
resetData(searchMoves)
currentEvaluation = evaluate()
newEvaluation = currentEvaluation
extraInfo = None # may contain promotion piece
bestMove = None
if len(moves) != 0:
for i in moves:
resetData(searchMoves)
'''if depth != 0:
currentColour = switchColours(colour)
depthMove = i
depthCopy = depth
depthCopy = depthCopy - 1
searchMovesCopy = searchMoves
searchMovesCopy = searchMovesCopy + [depthMove]
depthMoves = generateAllMoves(currentColour,False,searchMovesCopy)
depthMove,depthExtraInfo,eval = search(depthMoves,currentColour,depthCopy,startingDepth,searchMovesCopy)
maxDepthMoves = maxDepthMoves + [depthMove,extraInfo,eval]'''
if isPromoting(int(math.pow(2,i[0])),i[1]):
for piece in ["BISHOP","ROOK","HORSE","QUEEN"]:
resetData(searchMoves)
makeMove(int(math.pow(2,i[0])),int(math.pow(2,i[1])),colour,True,piece)
bestMove, newEvaluation = getBestEvalMove(colour,bestMove,newEvaluation,i)
if bestMove == i:
extraInfo = piece
else:
makeMove(int(math.pow(2,i[0])),int(math.pow(2,i[1])),colour,True)
bestMove,newEvaluation = getBestEvalMove(colour,bestMove,newEvaluation,i)
resetData()
if newEvaluation == currentEvaluation:
index = random.randint(0, len(moves) - 1)
chosenMove = moves[index]
return chosenMove,extraInfo,newEvaluation
else:
return bestMove,extraInfo,newEvaluation
else:
return None,None,None
def searchv2(depth,colour,searchMoves = []):
resetData(searchMoves)
if depth == 0:
return evaluate(),searchMoves[0]
moves = generateAllMoves(colour,False,searchMoves)
if len(moves) == 0:
pass
bestEval = None
if colour == "WHITE":
bestEval = -1000000000
else:
bestEval = 1000000000
bestMove = None
for move in moves:
resetData(searchMoves)
if isPromoting(int(math.pow(2,move[0])),move[1]):
makeMove(int(math.pow(2,move[0])),int(math.pow(2,move[1])),colour,True,"QUEEN")
else:
makeMove(int(math.pow(2,move[0])),int(math.pow(2,move[1])),colour,True)
eval,nextBestMove = searchv2(depth - 1,switchColours(colour),searchMoves + [move])
eval = -eval
bestEval = getBestEvalMove(colour,nextBestMove,bestEval,move)[1]
if bestEval == eval:
bestMove = nextBestMove
return bestEval,bestMove
# ------------- plan for final search function that supports depth ----------------------
#
# does search call for each branch and
# returns best move for enemy
# (the start then adds all these moves returned from branches
# into list and selects one with lowest eval response from black)
# ^ ^ ^ ^
# | | | |
# Checks every move person searching has
# ^ ^ ^ ^
# | | | |
# Start of search
#
# all above can then be called as many times for different depths
# the above section is of depth 1
#
# ---------------------------------------------------------------------------------------
def searchv3(colour,searchMoves = [],depth = 1):
#chosenMove,extraInfo,newEvaluation
resetData(searchMoves)
startEval = evaluate()
moves = generateAllMoves(colour,False,searchMoves)
opponentColour = switchColours(colour)
allEndDepthMoves = []
for move in moves:
resetData(searchMoves)
opponentMoves = generateAllMoves(opponentColour,False,searchMoves)
bestOpponentMove, extraInfo, bestOpponentEval = search(opponentMoves,opponentColour,searchMoves + [move])
if depth - 1 != 0:
bestOpponentEval,newMove,extraInfo = searchv3(colour,searchMoves + [move,bestOpponentMove],depth - 1)
allEndDepthMoves = allEndDepthMoves + [[bestOpponentEval,move,extraInfo]]
else:
allEndDepthMoves = allEndDepthMoves + [[bestOpponentEval,move,extraInfo]]
bestMove = None
if len(allEndDepthMoves) > 0:
bestMove = allEndDepthMoves[0]
for i in range(len(allEndDepthMoves)):
if colour == "WHITE":
if allEndDepthMoves[i][0] > bestMove[0]:
bestMove = allEndDepthMoves[i]
else:
if allEndDepthMoves[i][0] < bestMove[0]:
bestMove = allEndDepthMoves[i]
if bestMove != None:
return bestMove[0],bestMove[1],bestMove[2]
else:
return None,None,None
##################################################################################################################################################################################
##################################################################################################################################################################################
################################################################ Used to create bitboards from 2d array ##########################################################################
##################################################################################################################################################################################
##################################################################################################################################################################################
def colourType(piece):
whitePieces = ['♜','♞','♝','♛','♚','♟']
blackPieces = ['♖','♘','♗','♕','♔','♙']
if piece in whitePieces:
return "WHITE"
if piece in blackPieces:
return "BLACK"
def getPieceType(pieceSelected):
# returns a string that contains the type of piece it is
# examples are things such as 'rook', 'pawn', 'queens'
colour = colourType(pieceSelected)
if pieceSelected in ['♟','♙']:
return "PAWN",colour
elif pieceSelected in ['♞','♘']:
return "HORSE",colour
elif pieceSelected in ['♝','♗']:
return "BISHOP",colour
elif pieceSelected in ['♜','♖']:
return "ROOK",colour
elif pieceSelected in ['♛','♕']:
return "QUEEN",colour
elif pieceSelected in ['♚','♔']:
return "KING",colour
else:
return "NONE",None
def convertToBitBoard(board,castlingData,enPassant):
global bitWordBoard
global whitePieces
global blackPieces
global whitePawns
global whiteHorses
global whiteBishops
global whiteRooks
global whiteQueens
global whiteKing
global blackPawns
global blackHorses
global blackBishops
global blackRooks
global blackQueens
global blackKing
global Checkmate
Checkmate = False
global Stalemate
Stalemate = False
blackPieces = 0
whitePieces = 0
whitePawns = 0
whiteHorses = 0
whiteBishops = 0
whiteRooks = 0
whiteQueens = 0
whiteKing = 0
blackPawns = 0
blackHorses = 0