-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchess.py
1501 lines (1212 loc) · 51.5 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
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
'''
PIECE AND COLOR BITMASK = 0bCPPP
where:
C - color
P - piece code
CASTLING RIGHTS BITMASK = 0bqkQK
where:
q - CASTLE_QUEENSIDE_BLACK
k - CASTLE_KINGSIDE_BLACK
Q - CASTLE_QUEENSIDE_WHITE
K - CASTLE_KINGSIDE_WHITE
This program uses "Little-Endian Rank-File Mapping":
bit_boards = 0b(h8)(g8)...(b1)(a1)
board = [ a1, b1, ..., g8, h8 ]
move = [ leaving_position, arriving_position ]
'''
from copy import deepcopy
from random import choice
from time import sleep, time
COLOR_MASK = 1 << 3
WHITE = 0 << 3
BLACK = 1 << 3
ENDGAME_PIECE_COUNT = 7
PIECE_MASK = 0b111
EMPTY = 0
PAWN = 1
KNIGHT = 2
BISHOP = 3
ROOK = 4
QUEEN = 5
KING = 6
PIECE_TYPES = [ PAWN, KNIGHT, BISHOP, ROOK, QUEEN, KING]
PIECE_VALUES = { EMPTY:0, PAWN:100, KNIGHT:300, BISHOP:300, ROOK:500, QUEEN:900, KING:42000 }
FILES = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
RANKS = ['1', '2', '3', '4', '5', '6', '7', '8']
CASTLE_KINGSIDE_WHITE = 0b1 << 0
CASTLE_QUEENSIDE_WHITE = 0b1 << 1
CASTLE_KINGSIDE_BLACK = 0b1 << 2
CASTLE_QUEENSIDE_BLACK = 0b1 << 3
FULL_CASTLING_RIGHTS = CASTLE_KINGSIDE_WHITE|CASTLE_QUEENSIDE_WHITE|CASTLE_KINGSIDE_BLACK|CASTLE_QUEENSIDE_BLACK
ALL_SQUARES = 0xFFFFFFFFFFFFFFFF
FILE_A = 0x0101010101010101
FILE_B = 0x0202020202020202
FILE_C = 0x0404040404040404
FILE_D = 0x0808080808080808
FILE_E = 0x1010101010101010
FILE_F = 0x2020202020202020
FILE_G = 0x4040404040404040
FILE_H = 0x8080808080808080
RANK_1 = 0x00000000000000FF
RANK_2 = 0x000000000000FF00
RANK_3 = 0x0000000000FF0000
RANK_4 = 0x00000000FF000000
RANK_5 = 0x000000FF00000000
RANK_6 = 0x0000FF0000000000
RANK_7 = 0x00FF000000000000
RANK_8 = 0xFF00000000000000
DIAG_A1H8 = 0x8040201008040201
ANTI_DIAG_H1A8 = 0x0102040810204080
LIGHT_SQUARES = 0x55AA55AA55AA55AA
DARK_SQUARES = 0xAA55AA55AA55AA55
FILE_MASKS = [FILE_A, FILE_B, FILE_C, FILE_D, FILE_E, FILE_F, FILE_G, FILE_H]
RANK_MASKS = [RANK_1, RANK_2, RANK_3, RANK_4, RANK_5, RANK_6, RANK_7, RANK_8]
INITIAL_BOARD = [ WHITE|ROOK, WHITE|KNIGHT, WHITE|BISHOP, WHITE|QUEEN, WHITE|KING, WHITE|BISHOP, WHITE|KNIGHT, WHITE|ROOK,
WHITE|PAWN, WHITE|PAWN, WHITE|PAWN, WHITE|PAWN, WHITE|PAWN, WHITE|PAWN, WHITE|PAWN, WHITE|PAWN,
EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY,
EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY,
EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY,
EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY,
BLACK|PAWN, BLACK|PAWN, BLACK|PAWN, BLACK|PAWN, BLACK|PAWN, BLACK|PAWN, BLACK|PAWN, BLACK|PAWN,
BLACK|ROOK, BLACK|KNIGHT, BLACK|BISHOP, BLACK|QUEEN, BLACK|KING, BLACK|BISHOP, BLACK|KNIGHT, BLACK|ROOK ]
EMPTY_BOARD = [ EMPTY for _ in range(64) ]
INITIAL_FEN = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'
STROKES_YOLO = '1k6/2b1p3/Qp4N1/4r2P/2B2q2/1R6/2Pn2K1/8 w - - 0 1'
PIECE_CODES = { WHITE|KING: 'K',
WHITE|QUEEN: 'Q',
WHITE|ROOK: 'R',
WHITE|BISHOP:'B',
WHITE|KNIGHT:'N',
WHITE|PAWN: 'P',
BLACK|KING: 'k',
BLACK|QUEEN: 'q',
BLACK|ROOK: 'r',
BLACK|BISHOP:'b',
BLACK|KNIGHT:'n',
BLACK|PAWN: 'p',
EMPTY: '.' }
PIECE_CODES.update({v: k for k, v in PIECE_CODES.items()})
DOUBLED_PAWN_PENALTY = 10
ISOLATED_PAWN_PENALTY = 20
BACKWARDS_PAWN_PENALTY = 8
PASSED_PAWN_BONUS = 20
ROOK_SEMI_OPEN_FILE_BONUS = 10
ROOK_OPEN_FILE_BONUS = 15
ROOK_ON_SEVENTH_BONUS = 20
PAWN_BONUS = [0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, -40, -40, 0, 0, 0,
1, 2, 3, -10, -10, 3, 2, 1,
2, 4, 6, 8, 8, 6, 4, 2,
3, 6, 9, 12, 12, 9, 6, 3,
4, 8, 12, 16, 16, 12, 8, 4,
5, 10, 15, 20, 20, 15, 10, 5,
0, 0, 0, 0, 0, 0, 0, 0]
KNIGHT_BONUS = [-10, -30, -10, -10, -10, -10, -30, -10,
-10, 0, 0, 0, 0, 0, 0, -10,
-10, 0, 5, 5, 5, 5, 0, -10,
-10, 0, 5, 10, 10, 5, 0, -10,
-10, 0, 5, 10, 10, 5, 0, -10,
-10, 0, 5, 5, 5, 5, 0, -10,
-10, 0, 0, 0, 0, 0, 0, -10,
-10, -10, -10, -10, -10, -10, -10, -10]
BISHOP_BONUS = [-10, -10, -20, -10, -10, -20, -10, -10,
-10, 0, 0, 0, 0, 0, 0, -10,
-10, 0, 5, 5, 5, 5, 0, -10,
-10, 0, 5, 10, 10, 5, 0, -10,
-10, 0, 5, 10, 10, 5, 0, -10,
-10, 0, 5, 5, 5, 5, 0, -10,
-10, 0, 0, 0, 0, 0, 0, -10,
-10, -10, -10, -10, -10, -10, -10, -10]
KING_BONUS = [ 0, 20, 40, -20, 0, -20, 40, 20,
-20, -20, -20, -20, -20, -20, -20, -20,
-40, -40, -40, -40, -40, -40, -40, -40,
-40, -40, -40, -40, -40, -40, -40, -40,
-40, -40, -40, -40, -40, -40, -40, -40,
-40, -40, -40, -40, -40, -40, -40, -40,
-40, -40, -40, -40, -40, -40, -40, -40,
-40, -40, -40, -40, -40, -40, -40, -40]
KING_ENDGAME_BONUS = [ 0, 10, 20, 30, 30, 20, 10, 0,
10, 20, 30, 40, 40, 30, 20, 10,
20, 30, 40, 50, 50, 40, 30, 20,
30, 40, 50, 60, 60, 50, 40, 30,
30, 40, 50, 60, 60, 50, 40, 30,
20, 30, 40, 50, 50, 40, 30, 20,
10, 20, 30, 40, 40, 30, 20, 10,
0, 10, 20, 30, 30, 20, 10, 0]
verbose = True
# ========== CHESS GAME ==========
class Game:
def __init__(self, FEN=''):
self.board = INITIAL_BOARD
self.to_move = WHITE
self.ep_square = 0
self.castling_rights = FULL_CASTLING_RIGHTS
self.halfmove_clock = 0
self.fullmove_number = 1
self.position_history = []
if FEN != '':
self.load_FEN(FEN)
self.position_history.append(FEN)
else:
self.position_history.append(INITIAL_FEN)
self.move_history = []
def get_move_list(self):
return ' '.join(self.move_history)
def to_FEN(self):
FEN_str = ''
for i in range(len(RANKS)):
first = len(self.board) - 8*(i+1)
empty_sqrs = 0
for fille in range(len(FILES)):
piece = self.board[first+fille]
if piece&PIECE_MASK == EMPTY:
empty_sqrs += 1
else:
if empty_sqrs > 0:
FEN_str += '{}'.format(empty_sqrs)
FEN_str += '{}'.format(piece2str(piece))
empty_sqrs = 0
if empty_sqrs > 0:
FEN_str += '{}'.format(empty_sqrs)
FEN_str += '/'
FEN_str = FEN_str[:-1] + ' '
if self.to_move == WHITE:
FEN_str += 'w '
if self.to_move == BLACK:
FEN_str += 'b '
if self.castling_rights & CASTLE_KINGSIDE_WHITE:
FEN_str += 'K'
if self.castling_rights & CASTLE_QUEENSIDE_WHITE:
FEN_str += 'Q'
if self.castling_rights & CASTLE_KINGSIDE_BLACK:
FEN_str += 'k'
if self.castling_rights & CASTLE_QUEENSIDE_BLACK:
FEN_str += 'q'
if self.castling_rights == 0:
FEN_str += '-'
FEN_str += ' '
if self.ep_square == 0:
FEN_str += '-'
else:
FEN_str += bb2str(self.ep_square)
FEN_str += ' {}'.format(self.halfmove_clock)
FEN_str += ' {}'.format(self.fullmove_number)
return FEN_str
def load_FEN(self, FEN_str):
FEN_list = FEN_str.split(' ')
board_str = FEN_list[0]
rank_list = board_str.split('/')
rank_list.reverse()
self.board = []
for rank in rank_list:
rank_pieces = []
for p in rank:
if p.isdigit():
for _ in range(int(p)):
rank_pieces.append(EMPTY)
else:
rank_pieces.append(str2piece(p))
self.board.extend(rank_pieces)
to_move_str = FEN_list[1].lower()
if to_move_str == 'w':
self.to_move = WHITE
if to_move_str == 'b':
self.to_move = BLACK
castling_rights_str = FEN_list[2]
self.castling_rights = 0
if castling_rights_str.find('K') >= 0:
self.castling_rights |= CASTLE_KINGSIDE_WHITE
if castling_rights_str.find('Q') >= 0:
self.castling_rights |= CASTLE_QUEENSIDE_WHITE
if castling_rights_str.find('k') >= 0:
self.castling_rights |= CASTLE_KINGSIDE_BLACK
if castling_rights_str.find('q') >= 0:
self.castling_rights |= CASTLE_QUEENSIDE_BLACK
ep_str = FEN_list[3]
if ep_str == '-':
self.ep_square = 0
else:
self.ep_square = str2bb(ep_str)
self.halfmove_clock = int(FEN_list[4])
self.fullmove_number = int(FEN_list[5])
# ================================
def get_piece(board, bitboard):
return board[bb2index(bitboard)]
def bb2index(bitboard):
for i in range(64):
if bitboard & (0b1 << i):
return i
def str2index(position_str):
fille = FILES.index(position_str[0].lower())
rank = RANKS.index(position_str[1])
return 8*rank + fille
def bb2str(bitboard):
for i in range(64):
if bitboard & (0b1 << i):
fille = i%8
rank = int(i/8)
return '{}{}'.format(FILES[fille], RANKS[rank])
def str2bb(position_str):
return 0b1 << str2index(position_str)
def move2str(move):
return bb2str(move[0]) + bb2str(move[1])
def single_gen(bitboard):
for i in range(64):
bit = 0b1 << i
if bitboard & bit:
yield bit
def piece_gen(board, piece_code):
for i in range(64):
if board[i]&PIECE_MASK == piece_code:
yield 0b1 << i
def colored_piece_gen(board, piece_code, color):
for i in range(64):
if board[i] == piece_code|color:
yield 0b1 << i
def opposing_color(color):
if color == WHITE:
return BLACK
if color == BLACK:
return WHITE
def piece2str(piece):
return PIECE_CODES[piece]
def str2piece(string):
return PIECE_CODES[string]
def print_board(board):
print('')
for i in range(len(RANKS)):
rank_str = str(8-i) + ' '
first = len(board) - 8*(i+1)
for fille in range(len(FILES)):
rank_str += '{} '.format(piece2str(board[first+fille]))
print(rank_str)
print(' a b c d e f g h')
def print_rotated_board(board):
r_board = rotate_board(board)
print('')
for i in range(len(RANKS)):
rank_str = str(i+1) + ' '
first = len(r_board) - 8*(i+1)
for fille in range(len(FILES)):
rank_str += '{} '.format(piece2str(r_board[first+fille]))
print(rank_str)
print(' h g f e d c b a')
def print_bitboard(bitboard):
print('')
for rank in range(len(RANKS)):
rank_str = str(8-rank) + ' '
for fille in range(len(FILES)):
if (bitboard >> (fille + (7-rank)*8)) & 0b1:
rank_str += '# '
else:
rank_str += '. '
print(rank_str)
print(' a b c d e f g h')
def lsb(bitboard):
for i in range(64):
bit = (0b1 << i)
if bit & bitboard:
return bit
def msb(bitboard):
for i in range(64):
bit = (0b1 << (63-i))
if bit & bitboard:
return bit
def get_colored_pieces(board, color):
return list2int([ (i != EMPTY and i&COLOR_MASK == color) for i in board ])
def empty_squares(board):
return list2int([ i == EMPTY for i in board ])
def occupied_squares(board):
return nnot(empty_squares(board))
def list2int(lst):
rev_list = lst[:]
rev_list.reverse()
return int('0b' + ''.join(['1' if i else '0' for i in rev_list]), 2)
def nnot(bitboard):
return ~bitboard & ALL_SQUARES
def rotate_board(board):
rotated_board = deepcopy(board)
rotated_board.reverse()
return rotated_board
def flip_board_v(board):
flip = [56, 57, 58, 59, 60, 61, 62, 63,
48, 49, 50, 51, 52, 53, 54, 55,
40, 41, 42, 43, 44, 45, 46, 47,
32, 33, 34, 35, 36, 37, 38, 39,
24, 25, 26, 27, 28, 29, 30, 31,
16, 17, 18, 19, 20, 21, 22, 23,
8, 9, 10, 11, 12, 13, 14, 15,
0, 1, 2, 3, 4, 5, 6, 7]
return deepcopy([board[flip[i]] for i in range(64)])
def east_one(bitboard):
return (bitboard << 1) & nnot(FILE_A)
def west_one(bitboard):
return (bitboard >> 1) & nnot(FILE_H)
def north_one(bitboard):
return (bitboard << 8) & nnot(RANK_1)
def south_one(bitboard):
return (bitboard >> 8) & nnot(RANK_8)
def NE_one(bitboard):
return north_one(east_one(bitboard))
def NW_one(bitboard):
return north_one(west_one(bitboard))
def SE_one(bitboard):
return south_one(east_one(bitboard))
def SW_one(bitboard):
return south_one(west_one(bitboard))
def move_piece(board, move):
new_board = deepcopy(board)
new_board[bb2index(move[1])] = new_board[bb2index(move[0])]
new_board[bb2index(move[0])] = EMPTY
return new_board
def make_move(game, move):
new_game = deepcopy(game)
leaving_position = move[0]
arriving_position = move[1]
# update_clocks
new_game.halfmove_clock += 1
if new_game.to_move == BLACK:
new_game.fullmove_number += 1
# reset clock if capture
if get_piece(new_game.board, arriving_position) != EMPTY:
new_game.halfmove_clock = 0
# for pawns: reset clock, removed captured ep, set new ep, promote
if get_piece(new_game.board, leaving_position)&PIECE_MASK == PAWN:
new_game.halfmove_clock = 0
if arriving_position == game.ep_square:
new_game.board = remove_captured_ep(new_game)
if is_double_push(leaving_position, arriving_position):
new_game.ep_square = new_ep_square(leaving_position)
if arriving_position&(RANK_1|RANK_8):
new_game.board[bb2index(leaving_position)] = new_game.to_move|QUEEN
# reset ep square if not updated
if new_game.ep_square == game.ep_square:
new_game.ep_square = 0
# update castling rights for rook moves
if leaving_position == str2bb('a1'):
new_game.castling_rights = remove_castling_rights(new_game, CASTLE_QUEENSIDE_WHITE)
if leaving_position == str2bb('h1'):
new_game.castling_rights = remove_castling_rights(new_game, CASTLE_KINGSIDE_WHITE)
if leaving_position == str2bb('a8'):
new_game.castling_rights = remove_castling_rights(new_game, CASTLE_QUEENSIDE_BLACK)
if leaving_position == str2bb('h8'):
new_game.castling_rights = remove_castling_rights(new_game, CASTLE_KINGSIDE_BLACK)
# castling
if get_piece(new_game.board, leaving_position) == WHITE|KING:
new_game.castling_rights = remove_castling_rights(new_game, CASTLE_KINGSIDE_WHITE|CASTLE_QUEENSIDE_WHITE)
if leaving_position == str2bb('e1'):
if arriving_position == str2bb('g1'):
new_game.board = move_piece(new_game.board, [str2bb('h1'), str2bb('f1')])
if arriving_position == str2bb('c1'):
new_game.board = move_piece(new_game.board, [str2bb('a1'), str2bb('d1')])
if get_piece(new_game.board, leaving_position) == BLACK|KING:
new_game.castling_rights = remove_castling_rights(new_game, CASTLE_KINGSIDE_BLACK|CASTLE_QUEENSIDE_BLACK)
if leaving_position == str2bb('e8'):
if arriving_position == str2bb('g8'):
new_game.board = move_piece(new_game.board, [str2bb('h8'), str2bb('f8')])
if arriving_position == str2bb('c8'):
new_game.board = move_piece(new_game.board, [str2bb('a8'), str2bb('d8')])
# update positions and next to move
new_game.board = move_piece(new_game.board, (leaving_position, arriving_position))
new_game.to_move = opposing_color(new_game.to_move)
# update history
new_game.move_history.append(move2str(move))
new_game.position_history.append(new_game.to_FEN())
return new_game
def unmake_move(game):
if len(game.position_history) < 2:
return deepcopy(game)
new_game = Game(game.position_history[-2])
new_game.move_history = deepcopy(game.move_history)[:-1]
new_game.position_history = deepcopy(game.position_history)[:-1]
return new_game
def get_rank(rank_num):
rank_num = int(rank_num)
return RANK_MASKS[rank_num]
def get_file(file_str):
file_str = file_str.lower()
file_num = FILES.index(file_str)
return FILE_MASKS[file_num]
def get_filter(filter_str):
if filter_str in FILES:
return get_file(filter_str)
if filter_str in RANKS:
return get_rank(filter_str)
# ========== PAWN ==========
def get_all_pawns(board):
return list2int([ i&PIECE_MASK == PAWN for i in board ])
def get_pawns(board, color):
return list2int([ i == color|PAWN for i in board ])
def pawn_moves(moving_piece, game, color):
return pawn_pushes(moving_piece, game.board, color) | pawn_captures(moving_piece, game, color)
def pawn_captures(moving_piece, game, color):
return pawn_simple_captures(moving_piece, game, color) | pawn_ep_captures(moving_piece, game, color)
def pawn_pushes(moving_piece, board, color):
return pawn_simple_pushes(moving_piece, board, color) | pawn_double_pushes(moving_piece, board, color)
def pawn_simple_captures(attacking_piece, game, color):
return pawn_attacks(attacking_piece, game.board, color) & get_colored_pieces(game.board, opposing_color(color))
def pawn_ep_captures(attacking_piece, game, color):
if color == WHITE:
ep_squares = game.ep_square & RANK_6
if color == BLACK:
ep_squares = game.ep_square & RANK_3
return pawn_attacks(attacking_piece, game.board, color) & ep_squares
def pawn_attacks(attacking_piece, board, color):
return pawn_east_attacks(attacking_piece, board, color) | pawn_west_attacks(attacking_piece, board, color)
def pawn_simple_pushes(moving_piece, board, color):
if color == WHITE:
return north_one(moving_piece) & empty_squares(board)
if color == BLACK:
return south_one(moving_piece) & empty_squares(board)
def pawn_double_pushes(moving_piece, board, color):
if color == WHITE:
return north_one(pawn_simple_pushes(moving_piece, board, color)) & (empty_squares(board) & RANK_4)
if color == BLACK:
return south_one(pawn_simple_pushes(moving_piece, board, color)) & (empty_squares(board) & RANK_5)
def pawn_east_attacks(attacking_piece, board, color):
if color == WHITE:
return NE_one(attacking_piece & get_colored_pieces(board, color))
if color == BLACK:
return SE_one(attacking_piece & get_colored_pieces(board, color))
def pawn_west_attacks(attacking_piece, board, color):
if color == WHITE:
return NW_one(attacking_piece & get_colored_pieces(board, color))
if color == BLACK:
return SW_one(attacking_piece & get_colored_pieces(board, color))
def pawn_double_attacks(attacking_piece, board, color):
return pawn_east_attacks(attacking_piece, board, color) & pawn_west_attacks(attacking_piece, board, color)
def is_double_push(leaving_square, target_square):
return (leaving_square&RANK_2 and target_square&RANK_4) or \
(leaving_square&RANK_7 and target_square&RANK_5)
def new_ep_square(leaving_square):
if leaving_square&RANK_2:
return north_one(leaving_square)
if leaving_square&RANK_7:
return south_one(leaving_square)
def remove_captured_ep(game):
new_board = deepcopy(game.board)
if game.ep_square & RANK_3:
new_board[bb2index(north_one(game.ep_square))] = EMPTY
if game.ep_square & RANK_6:
new_board[bb2index(south_one(game.ep_square))] = EMPTY
return new_board
# ========== KNIGHT ==========
def get_knights(board, color):
return list2int([ i == color|KNIGHT for i in board ])
def knight_moves(moving_piece, board, color):
return knight_attacks(moving_piece) & nnot(get_colored_pieces(board, color))
def knight_attacks(moving_piece):
return knight_NNE(moving_piece) | \
knight_ENE(moving_piece) | \
knight_NNW(moving_piece) | \
knight_WNW(moving_piece) | \
knight_SSE(moving_piece) | \
knight_ESE(moving_piece) | \
knight_SSW(moving_piece) | \
knight_WSW(moving_piece)
def knight_WNW(moving_piece):
return moving_piece << 6 & nnot(FILE_G | FILE_H)
def knight_ENE(moving_piece):
return moving_piece << 10 & nnot(FILE_A | FILE_B)
def knight_NNW(moving_piece):
return moving_piece << 15 & nnot(FILE_H)
def knight_NNE(moving_piece):
return moving_piece << 17 & nnot(FILE_A)
def knight_ESE(moving_piece):
return moving_piece >> 6 & nnot(FILE_A | FILE_B)
def knight_WSW(moving_piece):
return moving_piece >> 10 & nnot(FILE_G | FILE_H)
def knight_SSE(moving_piece):
return moving_piece >> 15 & nnot(FILE_A)
def knight_SSW(moving_piece):
return moving_piece >> 17 & nnot(FILE_H)
def knight_fill(moving_piece, n):
fill = moving_piece
for _ in range(n):
fill |= knight_attacks(fill)
return fill
def knight_distance(pos1, pos2):
init_bitboard = str2bb(pos1)
end_bitboard = str2bb(pos2)
fill = init_bitboard
dist = 0
while fill & end_bitboard == 0:
dist += 1
fill = knight_fill(init_bitboard, dist)
return dist
# ========== KING ==========
def get_king(board, color):
return list2int([ i == color|KING for i in board ])
def king_moves(moving_piece, board, color):
return king_attacks(moving_piece) & nnot(get_colored_pieces(board, color))
def king_attacks(moving_piece):
king_atks = moving_piece | east_one(moving_piece) | west_one(moving_piece)
king_atks |= north_one(king_atks) | south_one(king_atks)
return king_atks & nnot(moving_piece)
def can_castle_kingside(game, color):
if color == WHITE:
return (game.castling_rights & CASTLE_KINGSIDE_WHITE) and \
game.board[str2index('f1')] == EMPTY and \
game.board[str2index('g1')] == EMPTY and \
(not is_attacked(str2bb('e1'), game.board, opposing_color(color))) and \
(not is_attacked(str2bb('f1'), game.board, opposing_color(color))) and \
(not is_attacked(str2bb('g1'), game.board, opposing_color(color)))
if color == BLACK:
return (game.castling_rights & CASTLE_KINGSIDE_BLACK) and \
game.board[str2index('f8')] == EMPTY and \
game.board[str2index('g8')] == EMPTY and \
(not is_attacked(str2bb('e8'), game.board, opposing_color(color))) and \
(not is_attacked(str2bb('f8'), game.board, opposing_color(color))) and \
(not is_attacked(str2bb('g8'), game.board, opposing_color(color)))
def can_castle_queenside(game, color):
if color == WHITE:
return (game.castling_rights & CASTLE_QUEENSIDE_WHITE) and \
game.board[str2index('b1')] == EMPTY and \
game.board[str2index('c1')] == EMPTY and \
game.board[str2index('d1')] == EMPTY and \
(not is_attacked(str2bb('c1'), game.board, opposing_color(color))) and \
(not is_attacked(str2bb('d1'), game.board, opposing_color(color))) and \
(not is_attacked(str2bb('e1'), game.board, opposing_color(color)))
if color == BLACK:
return (game.castling_rights & CASTLE_QUEENSIDE_BLACK) and \
game.board[str2index('b8')] == EMPTY and \
game.board[str2index('c8')] == EMPTY and \
game.board[str2index('d8')] == EMPTY and \
(not is_attacked(str2bb('c8'), game.board, opposing_color(color))) and \
(not is_attacked(str2bb('d8'), game.board, opposing_color(color))) and \
(not is_attacked(str2bb('e8'), game.board, opposing_color(color)))
def castle_kingside_move(game):
if game.to_move == WHITE:
return (str2bb('e1'), str2bb('g1'))
if game.to_move == BLACK:
return (str2bb('e8'), str2bb('g8'))
def castle_queenside_move(game):
if game.to_move == WHITE:
return (str2bb('e1'), str2bb('c1'))
if game.to_move == BLACK:
return (str2bb('e8'), str2bb('c8'))
def remove_castling_rights(game, removed_rights):
return game.castling_rights & ~removed_rights
# ========== BISHOP ==========
def get_bishops(board, color):
return list2int([ i == color|BISHOP for i in board ])
def bishop_rays(moving_piece):
return diagonal_rays(moving_piece) | anti_diagonal_rays(moving_piece)
def diagonal_rays(moving_piece):
return NE_ray(moving_piece) | SW_ray(moving_piece)
def anti_diagonal_rays(moving_piece):
return NW_ray(moving_piece) | SE_ray(moving_piece)
def NE_ray(moving_piece):
ray_atks = NE_one(moving_piece)
for _ in range(6):
ray_atks |= NE_one(ray_atks)
return ray_atks & ALL_SQUARES
def SE_ray(moving_piece):
ray_atks = SE_one(moving_piece)
for _ in range(6):
ray_atks |= SE_one(ray_atks)
return ray_atks & ALL_SQUARES
def NW_ray(moving_piece):
ray_atks = NW_one(moving_piece)
for _ in range(6):
ray_atks |= NW_one(ray_atks)
return ray_atks & ALL_SQUARES
def SW_ray(moving_piece):
ray_atks = SW_one(moving_piece)
for _ in range(6):
ray_atks |= SW_one(ray_atks)
return ray_atks & ALL_SQUARES
def NE_attacks(single_piece, board, color):
blocker = lsb(NE_ray(single_piece) & occupied_squares(board))
if blocker:
return NE_ray(single_piece) ^ NE_ray(blocker)
else:
return NE_ray(single_piece)
def NW_attacks(single_piece, board, color):
blocker = lsb(NW_ray(single_piece) & occupied_squares(board))
if blocker:
return NW_ray(single_piece) ^ NW_ray(blocker)
else:
return NW_ray(single_piece)
def SE_attacks(single_piece, board, color):
blocker = msb(SE_ray(single_piece) & occupied_squares(board))
if blocker:
return SE_ray(single_piece) ^ SE_ray(blocker)
else:
return SE_ray(single_piece)
def SW_attacks(single_piece, board, color):
blocker = msb(SW_ray(single_piece) & occupied_squares(board))
if blocker:
return SW_ray(single_piece) ^ SW_ray(blocker)
else:
return SW_ray(single_piece)
def diagonal_attacks(single_piece, board, color):
return NE_attacks(single_piece, board, color) | SW_attacks(single_piece, board, color)
def anti_diagonal_attacks(single_piece, board, color):
return NW_attacks(single_piece, board, color) | SE_attacks(single_piece, board, color)
def bishop_attacks(moving_piece, board, color):
atks = 0
for piece in single_gen(moving_piece):
atks |= diagonal_attacks(piece, board, color) | anti_diagonal_attacks(piece, board, color)
return atks
def bishop_moves(moving_piece, board, color):
return bishop_attacks(moving_piece, board, color) & nnot(get_colored_pieces(board, color))
# ========== ROOK ==========
def get_rooks(board, color):
return list2int([ i == color|ROOK for i in board ])
def rook_rays(moving_piece):
return rank_rays(moving_piece) | file_rays(moving_piece)
def rank_rays(moving_piece):
return east_ray(moving_piece) | west_ray(moving_piece)
def file_rays(moving_piece):
return north_ray(moving_piece) | south_ray(moving_piece)
def east_ray(moving_piece):
ray_atks = east_one(moving_piece)
for _ in range(6):
ray_atks |= east_one(ray_atks)
return ray_atks & ALL_SQUARES
def west_ray(moving_piece):
ray_atks = west_one(moving_piece)
for _ in range(6):
ray_atks |= west_one(ray_atks)
return ray_atks & ALL_SQUARES
def north_ray(moving_piece):
ray_atks = north_one(moving_piece)
for _ in range(6):
ray_atks |= north_one(ray_atks)
return ray_atks & ALL_SQUARES
def south_ray(moving_piece):
ray_atks = south_one(moving_piece)
for _ in range(6):
ray_atks |= south_one(ray_atks)
return ray_atks & ALL_SQUARES
def east_attacks(single_piece, board, color):
blocker = lsb(east_ray(single_piece) & occupied_squares(board))
if blocker:
return east_ray(single_piece) ^ east_ray(blocker)
else:
return east_ray(single_piece)
def west_attacks(single_piece, board, color):
blocker = msb(west_ray(single_piece) & occupied_squares(board))
if blocker:
return west_ray(single_piece) ^ west_ray(blocker)
else:
return west_ray(single_piece)
def rank_attacks(single_piece, board, color):
return east_attacks(single_piece, board, color) | west_attacks(single_piece, board, color)
def north_attacks(single_piece, board, color):
blocker = lsb(north_ray(single_piece) & occupied_squares(board))
if blocker:
return north_ray(single_piece) ^ north_ray(blocker)
else:
return north_ray(single_piece)
def south_attacks(single_piece, board, color):
blocker = msb(south_ray(single_piece) & occupied_squares(board))
if blocker:
return south_ray(single_piece) ^ south_ray(blocker)
else:
return south_ray(single_piece)
def file_attacks(single_piece, board, color):
return north_attacks(single_piece, board, color) | south_attacks(single_piece, board, color)
def rook_attacks(moving_piece, board, color):
atks = 0
for single_piece in single_gen(moving_piece):
atks |= rank_attacks(single_piece, board, color) | file_attacks(single_piece, board, color)
return atks
def rook_moves(moving_piece, board, color):
return rook_attacks(moving_piece, board, color) & nnot(get_colored_pieces(board, color))
# ========== QUEEN ==========
def get_queen(board, color):
return list2int([ i == color|QUEEN for i in board ])
def queen_rays(moving_piece):
return rook_rays(moving_piece) | bishop_rays(moving_piece)
def queen_attacks(moving_piece, board, color):
return bishop_attacks(moving_piece, board, color) | rook_attacks(moving_piece, board, color)
def queen_moves(moving_piece, board, color):
return bishop_moves(moving_piece, board, color) | rook_moves(moving_piece, board, color)
def is_attacked(target, board, attacking_color):
return count_attacks(target, board, attacking_color) > 0
def is_check(board, color):
return is_attacked(get_king(board, color), board, opposing_color(color))
def get_attacks(moving_piece, board, color):
piece = board[bb2index(moving_piece)]
if piece&PIECE_MASK == PAWN:
return pawn_attacks(moving_piece, board, color)
elif piece&PIECE_MASK == KNIGHT:
return knight_attacks(moving_piece)
elif piece&PIECE_MASK == BISHOP:
return bishop_attacks(moving_piece, board, color)
elif piece&PIECE_MASK == ROOK:
return rook_attacks(moving_piece, board, color)
elif piece&PIECE_MASK == QUEEN:
return queen_attacks(moving_piece, board, color)
elif piece&PIECE_MASK == KING:
return king_attacks(moving_piece)
def get_moves(moving_piece, game, color):
piece = game.board[bb2index(moving_piece)]
if piece&PIECE_MASK == PAWN:
return pawn_moves(moving_piece, game, color)
elif piece&PIECE_MASK == KNIGHT:
return knight_moves(moving_piece, game.board, color)
elif piece&PIECE_MASK == BISHOP:
return bishop_moves(moving_piece, game.board, color)
elif piece&PIECE_MASK == ROOK:
return rook_moves(moving_piece, game.board, color)
elif piece&PIECE_MASK == QUEEN:
return queen_moves(moving_piece, game.board, color)
elif piece&PIECE_MASK == KING:
return king_moves(moving_piece, game.board, color)
def count_attacks(target, board, attacking_color):
attack_count = 0
for index in range(64):
piece = board[index]
if piece != EMPTY and piece&COLOR_MASK == attacking_color:
pos = 0b1 << index
if get_attacks(pos, board, attacking_color) & target:
attack_count += 1
return attack_count
def material_sum(board, color):
material = 0
for piece in board:
if piece&COLOR_MASK == color:
material += PIECE_VALUES[piece&PIECE_MASK]
return material
def material_balance(board):
return material_sum(board, WHITE) - material_sum(board, BLACK)
def mobility_balance(game):
return count_legal_moves(game, WHITE) - count_legal_moves(game, BLACK)
def evaluate_game(game):
if game_ended(game):
return evaluate_end_node(game)
else:
return material_balance(game.board) + positional_balance(game)# + 10*mobility_balance(game)
def evaluate_end_node(game):
if is_checkmate(game, game.to_move):
return win_score(game.to_move)
elif is_stalemate(game) or \
has_insufficient_material(game) or \
is_under_75_move_rule(game):
return 0
def positional_balance(game):
return positional_bonus(game, WHITE) - positional_bonus(game, BLACK)
def positional_bonus(game, color):
bonus = 0
if color == WHITE:
board = game.board
elif color == BLACK:
board = flip_board_v(game.board)
for index in range(64):
piece = board[index]
if piece != EMPTY and piece&COLOR_MASK == color:
piece_type = piece&PIECE_MASK
if piece_type == PAWN: