-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchess.py
1436 lines (1159 loc) · 48.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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import dataclasses
import gzip
import pathlib
import pickle
import typing
from typing import (Dict, Generic, Iterable, Iterator, List, Optional, Tuple,
TypeVar)
Color = bool
COLORS = [RED, BLACK] = [True, False]
COLOR_NAMES = ["black", "red"]
PieceType = int
PIECE_TYPES = [PAWN, CANNON, ROOK, KNIGHT, BISHOP, ADVISOR, KING] = range(1, 8)
PIECE_SYMBOLS = [None, "p", "c", "r", "n", "b", "a", "k"]
PIECES_NAMES = {
# "R": "车", "r": "俥",
# "N": "马", "n": "傌",
# "B": "相", "b": "象",
# "A": "仕", "a": "士",
# "K": "帅", "k": "将",
# "P": "兵", "p": "卒",
# "C": "炮", "c": "砲",
"R": "车", "r": "车",
"N": "马", "n": "马",
"B": "相", "b": "象",
"A": "仕", "a": "士",
"K": "帅", "k": "将",
"P": "兵", "p": "卒",
"C": "炮", "c": "炮",
}
ACTION_NAMES = {".": "平", "+": "进", "-": "退"}
POSITION_NAMES = {".": "中", "+": "前", "-": "后",
"a": "一", "b": "二", "c": "三", "d": "四", "e": "五"}
def piece_symbol(piece_type: PieceType) -> str:
return typing.cast(str, PIECE_SYMBOLS[piece_type])
FILE_NAMES = [None, None, None, "a", "b", "c", "d",
"e", "f", "g", "h", "i", None, None, None, None]
CHINESE_NUMBERS = [None, "一", "二", "三", "四", "五", "六", "七", "八", "九"]
RANK_NAMES = [None, None, None, "0", "1", "2", "3",
"4", "5", "6", "7", "8", "9", None, None, None]
STARTING_FEN = "rnbakabnr/9/1c5c1/p1p1p1p1p/9/9/P1P1P1P1P/1C5C1/9/RNBAKABNR w - - 0 1"
STARTING_BOARD_FEN = "rnbakabnr/9/1c5c1/p1p1p1p1p/9/9/P1P1P1P1P/1C5C1/9/RNBAKABNR"
Square = int
SQUARES = [
__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __,
__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __,
__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __,
__, __, __, A0, B0, C0, D0, E0, F0, G0, H0, I0, __, __, __, __,
__, __, __, A1, B1, C1, D1, E1, F1, G1, H1, I1, __, __, __, __,
__, __, __, A2, B2, C2, D2, E2, F2, G2, H2, I2, __, __, __, __,
__, __, __, A3, B3, C3, D3, E3, F3, G3, H3, I3, __, __, __, __,
__, __, __, A4, B4, C4, D4, E4, F4, G4, H4, I4, __, __, __, __,
__, __, __, A5, B5, C5, D5, E5, F5, G5, H5, I5, __, __, __, __,
__, __, __, A6, B6, C6, D6, E6, F6, G6, H6, I6, __, __, __, __,
__, __, __, A7, B7, C7, D7, E7, F7, G7, H7, I7, __, __, __, __,
__, __, __, A8, B8, C8, D8, E8, F8, G8, H8, I8, __, __, __, __,
__, __, __, A9, B9, C9, D9, E9, F9, G9, H9, I9, __, __, __, __,
__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __,
__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __,
__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __,
] = range(256)
SQUARE_NAMES = [
f + r if f and r else None for r in RANK_NAMES for f in FILE_NAMES]
def square_file(square: Square) -> int:
return square & 0xf
def square_file_wxf(square: Square, color: Color) -> int:
if color == BLACK:
return square_file(square) - 2
else:
return 10 - (square_file(square) - 2)
def square_rank(square: Square) -> int:
return square >> 4
def square_in_board(square: Square) -> bool:
return bool(BB_SQUARES[square] & BB_IN_BOARD)
def square_distance(a: Square, b: Square) -> int:
return max(abs(square_file(a) - square_file(b)), abs(square_rank(a) - square_rank(b)))
def square_mirror(square: Square) -> Square:
return square ^ 0xf0
SQUARES_180 = [square_mirror(sq) for sq in SQUARES]
Bitboard = int
BB_EMPTY = 0
BB_ALL = 0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff
BB_IN_BOARD = 0x0000_0000_0000_0ff8_0ff8_0ff8_0ff8_0ff8_0ff8_0ff8_0ff8_0ff8_0ff8_0000_0000_0000
BB_RED_SIDE = 0x0000_0000_0000_0000_0000_0000_0000_0000_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff
BB_BLACK_SIDE = 0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_0000_0000_0000_0000_0000_0000_0000_0000
def print_bitboard(bb: Bitboard) -> None:
builder = []
for square in SQUARES_180:
mask = BB_SQUARES[square]
if not (mask & BB_IN_BOARD):
continue
builder.append("1" if bb & mask else ".")
if mask & BB_FILE_I:
builder.append("\n")
elif square != I0:
builder.append(" ")
print("".join(builder))
BB_SQUARES = [
_, _, _, _____, _____, _____, _____, _____, _____, _____, _____, _____, _, _, _, _,
_, _, _, _____, _____, _____, _____, _____, _____, _____, _____, _____, _, _, _, _,
_, _, _, _____, _____, _____, _____, _____, _____, _____, _____, _____, _, _, _, _,
_, _, _, BB_A0, BB_B0, BB_C0, BB_D0, BB_E0, BB_F0, BB_G0, BB_H0, BB_I0, _, _, _, _,
_, _, _, BB_A1, BB_B1, BB_C1, BB_D1, BB_E1, BB_F1, BB_G1, BB_H1, BB_I1, _, _, _, _,
_, _, _, BB_A2, BB_B2, BB_C2, BB_D2, BB_E2, BB_F2, BB_G2, BB_H2, BB_I2, _, _, _, _,
_, _, _, BB_A3, BB_B3, BB_C3, BB_D3, BB_E3, BB_F3, BB_G3, BB_H3, BB_I3, _, _, _, _,
_, _, _, BB_A4, BB_B4, BB_C4, BB_D4, BB_E4, BB_F4, BB_G4, BB_H4, BB_I4, _, _, _, _,
_, _, _, BB_A5, BB_B5, BB_C5, BB_D5, BB_E5, BB_F5, BB_G5, BB_H5, BB_I5, _, _, _, _,
_, _, _, BB_A6, BB_B6, BB_C6, BB_D6, BB_E6, BB_F6, BB_G6, BB_H6, BB_I6, _, _, _, _,
_, _, _, BB_A7, BB_B7, BB_C7, BB_D7, BB_E7, BB_F7, BB_G7, BB_H7, BB_I7, _, _, _, _,
_, _, _, BB_A8, BB_B8, BB_C8, BB_D8, BB_E8, BB_F8, BB_G8, BB_H8, BB_I8, _, _, _, _,
_, _, _, BB_A9, BB_B9, BB_C9, BB_D9, BB_E9, BB_F9, BB_G9, BB_H9, BB_I9, _, _, _, _,
_, _, _, _____, _____, _____, _____, _____, _____, _____, _____, _____, _, _, _, _,
_, _, _, _____, _____, _____, _____, _____, _____, _____, _____, _____, _, _, _, _,
_, _, _, _____, _____, _____, _____, _____, _____, _____, _____, _____, _, _, _, _,
] = [1 << sq for sq in SQUARES]
BB_CORNERS = BB_A0 | BB_I0 | BB_A9 | BB_I9
BB_RED_PAWNS = BB_A3 | BB_C3 | BB_E3 | BB_G3 | BB_I3
BB_BLACK_PAWNS = BB_A6 | BB_C6 | BB_E6 | BB_G6 | BB_I6
BB_IN_PALACE = (BB_D0 | BB_E0 | BB_F0 | BB_D1 | BB_E1 | BB_F1 | BB_D2 | BB_E2 | BB_F2 |
BB_D7 | BB_E7 | BB_F7 | BB_D8 | BB_E8 | BB_F8 | BB_D9 | BB_E9 | BB_F9)
SQUARES_IN_BOARD = [sq for sq in SQUARES if BB_SQUARES[sq] & BB_IN_BOARD]
BB_FILES = [
_, _, _,
BB_FILE_A,
BB_FILE_B,
BB_FILE_C,
BB_FILE_D,
BB_FILE_E,
BB_FILE_F,
BB_FILE_G,
BB_FILE_H,
BB_FILE_I,
_, _, _, _,
] = [0x0001_0001_0001_0001_0001_0001_0001_0001_0001_0001_0001_0001_0001_0001_0001_0001 << i for i in range(16)]
BB_RANKS = [
_, _, _,
BB_RANK_0,
BB_RANK_1,
BB_RANK_2,
BB_RANK_3,
BB_RANK_4,
BB_RANK_5,
BB_RANK_6,
BB_RANK_7,
BB_RANK_8,
BB_RANK_9,
_, _, _,
] = [0xffff << (16 * i) for i in range(16)]
BB_SQUARES_BISHOP = BB_C0 | BB_G0 | BB_A2 | BB_E2 | BB_I2 | BB_C4 | BB_G4 | BB_C5 | BB_G5 | BB_A7 | BB_E7 | BB_I7 | BB_C9 | BB_G9
BB_SQUARES_ADVISOR = BB_D0 | BB_F0 | BB_E1 | BB_D2 | BB_F2 | BB_D7 | BB_F7 | BB_E8 | BB_D9 | BB_F9
def msb(bb: Bitboard) -> int:
return bb.bit_length() - 1
def scan_reversed(bb: Bitboard) -> Iterator[Square]:
while bb:
r = bb.bit_length() - 1
yield r
bb ^= BB_SQUARES[r]
def count_ones(bb: Bitboard):
s = 0
t = {'0': 0, '1': 1, '2': 1, '3': 2, '4': 1, '5': 2, '6': 2, '7': 3}
for c in oct(bb)[2:]:
s += t[c]
return s
def between(a: Square, b: Square) -> Bitboard:
file_a, file_b = square_file(a), square_file(b)
rank_a, rank_b = square_rank(a), square_rank(b)
if file_a == file_b:
bb = BB_FILES[file_a] & ((BB_ALL << a) ^ (BB_ALL << b))
elif rank_a == rank_b:
bb = BB_RANKS[rank_a] & ((BB_ALL << a) ^ (BB_ALL << b))
else:
bb = BB_EMPTY
return bb & (bb - 1)
def line(a: Square, b: Square) -> Bitboard:
file_a, file_b = square_file(a), square_file(b)
rank_a, rank_b = square_rank(a), square_rank(b)
if file_a == file_b:
return BB_FILES[file_a]
elif rank_a == rank_b:
return BB_RANKS[rank_a]
else:
return BB_EMPTY
def _sliding_attacks(square: Square, occupied: Bitboard, deltas: Iterable[int]) -> Bitboard:
attacks = BB_EMPTY
for delta in deltas:
sq = square
while True:
sq += delta
if not (0 <= sq < 256) or square_distance(sq, sq - delta) > 2:
break
attacks |= BB_SQUARES[sq]
if occupied & BB_SQUARES[sq]:
break
return attacks
def _jump_attacks(square: Square, occupied: Bitboard, deltas: Iterable[int]) -> Bitboard:
attacks = BB_EMPTY
for delta in deltas:
hops = 0
sq = square
while True:
sq += delta
if not (0 <= sq < 256) or square_distance(sq, sq - delta) > 2:
break
if occupied & BB_SQUARES[sq]:
if hops == 1:
attacks |= BB_SQUARES[sq]
break
else:
hops += 1
return attacks
def _edges(square: Square) -> Bitboard:
return (((BB_RANK_0 | BB_RANK_9) & ~BB_RANKS[square_rank(square)]) |
((BB_FILE_A | BB_FILE_I) & ~BB_FILES[square_file(square)]))
def _carry_rippler(mask: Bitboard) -> Iterator[Bitboard]:
# Carry-Rippler trick to iterate subsets of mask.
subset = BB_EMPTY
while True:
yield subset
subset = (subset - mask) & mask
if not subset:
break
def _attack_table(deltas: List[int], jump=False) -> Tuple[List[Bitboard], List[Dict[Bitboard, Bitboard]]]:
mask_table = []
attack_table = []
for square in SQUARES:
attacks = {}
mask = _sliding_attacks(square, BB_EMPTY, deltas) & BB_IN_BOARD
if not jump:
mask &= ~_edges(square)
for subset in _carry_rippler(mask):
attacks[subset] = _jump_attacks(
square, subset, deltas) if jump else _sliding_attacks(square, subset, deltas)
attack_table.append(attacks)
mask_table.append(mask)
return mask_table, attack_table
def _step_attacks(square: Square, deltas: Iterable[int]) -> Bitboard:
return _sliding_attacks(square, BB_ALL, deltas)
def _pawn_attacks(reverse=False) -> List[List[Bitboard]]:
attacks = [[], []]
direction = -1 if reverse else 1
for sq in SQUARES:
# 红兵
if sq > I4:
# 过河兵
attacks[RED].append(_step_attacks(sq, [-1, 16 * direction, 1]))
else:
attacks[RED].append(_step_attacks(sq, [16 * direction]))
for sq in SQUARES:
# 黑卒
if sq < A5:
# 过河兵
attacks[BLACK].append(_step_attacks(sq, [-1, -16 * direction, 1]))
else:
attacks[BLACK].append(_step_attacks(sq, [-16 * direction]))
return attacks
def _knight_attacks(reverse=False) -> Tuple[List[Bitboard], List[Dict[Bitboard, Bitboard]]]:
mask_table = []
attack_table = []
knight_deltas = [33, 31, -14, 18, -33, -31, -18,
14] if not reverse else [14, 31, 33, 18, -14, -31, -18, -33]
directions = [16, 1, -16, -1] if not reverse else [15, 17, -15, -17]
for square in SQUARES:
if not square_in_board(square):
attack_table.append({BB_EMPTY: BB_EMPTY})
mask_table.append(BB_EMPTY)
continue
attacks = {}
mask = BB_EMPTY
for d in directions:
mask |= BB_SQUARES[square + d]
for i in range(0xf):
# 马脚位置
subset = BB_EMPTY
deltas = []
for j in range(4):
if i >> j & 1:
# 别马脚
subset |= BB_SQUARES[square + directions[j]]
else:
deltas.append(knight_deltas[2 * j])
deltas.append(knight_deltas[2 * j + 1])
attacks[subset] = _step_attacks(square, deltas)
attack_table.append(attacks)
mask_table.append(mask)
return mask_table, attack_table
def _bishop_attacks() -> List[Bitboard]:
mask_table = []
attack_table = []
directions = [15, 17, -15, -17]
for square in SQUARES:
square_side = BB_RED_SIDE if BB_SQUARES[square] & BB_RED_SIDE else BB_BLACK_SIDE
if not (BB_SQUARES[square] & BB_SQUARES_BISHOP):
attack_table.append({BB_EMPTY: BB_EMPTY})
mask_table.append(BB_EMPTY)
continue
attacks = {}
mask = BB_EMPTY
for d in directions:
mask |= BB_SQUARES[square + d]
for i in range(0xf):
# 象眼位置
subset = BB_EMPTY
deltas = []
for j in range(4):
if i >> j & 1:
# 塞象眼
subset |= BB_SQUARES[square + directions[j]]
else:
deltas.append(2 * directions[j])
attacks[subset] = _step_attacks(square, deltas) & square_side
attack_table.append(attacks)
mask_table.append(mask)
return mask_table, attack_table
def _king_attacks() -> List[Bitboard]:
attacks = []
for square in SQUARES:
if not (BB_SQUARES[square] & BB_IN_PALACE):
attacks.append(BB_EMPTY)
continue
attacks.append(_step_attacks(square, [-16, 16, 1, -1]) & BB_IN_PALACE)
return attacks
def _advisor_attacks() -> List[Bitboard]:
attacks = []
for square in SQUARES:
if not (BB_SQUARES[square] & BB_SQUARES_ADVISOR):
attacks.append(BB_EMPTY)
continue
attacks.append(_step_attacks(
square, [15, 17, -15, -17]) & BB_IN_PALACE)
return attacks
def _knight_blocker(king: Square, knight: Square) -> Bitboard:
masks = [BB_KNIGHT_REVERSED_MASKS[king] & ~BB_SQUARES[king + 15],
BB_KNIGHT_REVERSED_MASKS[king] & ~BB_SQUARES[king + 17],
BB_KNIGHT_REVERSED_MASKS[king] & ~BB_SQUARES[king - 15],
BB_KNIGHT_REVERSED_MASKS[king] & ~BB_SQUARES[king - 17],
]
for mask in masks:
if BB_KNIGHT_REVERSED_ATTACKS[king][mask] & BB_SQUARES[knight]:
return BB_KNIGHT_REVERSED_MASKS[king] & ~mask
return BB_EMPTY
def _load_moves_table():
moves_table_path = pathlib.Path("moves_table")
if moves_table_path.is_file():
with gzip.open(moves_table_path, "rb") as f:
try:
return pickle.load(f)
except:
raise Exception("pre-calculated moves table load fails!")
raise Exception("pre-calculated moves table does not exsist!")
def _dump_moves_table(table):
moves_table_path = pathlib.Path("moves_table")
with gzip.open(moves_table_path, "wb") as f:
pickle.dump(table, f)
try:
(
BB_KNIGHT_MASKS, BB_KNIGHT_ATTACKS,
BB_KNIGHT_REVERSED_MASKS, BB_KNIGHT_REVERSED_ATTACKS,
BB_BISHOP_MASKS, BB_BISHOP_ATTACKS,
BB_CANNON_RANK_MASKS, BB_CANNON_RANK_ATTACKS,
BB_CANNON_FILE_MASKS, BB_CANNON_FILE_ATTACKS,
BB_RANK_MASKS, BB_RANK_ATTACKS,
BB_FILE_MASKS, BB_FILE_ATTACKS,
BB_PAWN_ATTACKS,
BB_PAWN_REVERSED_ATTACKS,
BB_KING_ATTACKS,
BB_ADVISOR_ATTACKS,
) = _load_moves_table()
except:
BB_KNIGHT_MASKS, BB_KNIGHT_ATTACKS = _knight_attacks()
BB_KNIGHT_REVERSED_MASKS, BB_KNIGHT_REVERSED_ATTACKS = _knight_attacks(
reverse=True)
BB_BISHOP_MASKS, BB_BISHOP_ATTACKS = _bishop_attacks()
BB_CANNON_RANK_MASKS, BB_CANNON_RANK_ATTACKS = _attack_table(
[-1, 1], jump=True)
BB_CANNON_FILE_MASKS, BB_CANNON_FILE_ATTACKS = _attack_table(
[-16, 16], jump=True)
BB_RANK_MASKS, BB_RANK_ATTACKS = _attack_table([-1, 1])
BB_FILE_MASKS, BB_FILE_ATTACKS = _attack_table([-16, 16])
BB_PAWN_ATTACKS = _pawn_attacks()
BB_PAWN_REVERSED_ATTACKS = _pawn_attacks(reverse=True)
BB_KING_ATTACKS = _king_attacks()
BB_ADVISOR_ATTACKS = _advisor_attacks()
_dump_moves_table((
BB_KNIGHT_MASKS, BB_KNIGHT_ATTACKS,
BB_KNIGHT_REVERSED_MASKS, BB_KNIGHT_REVERSED_ATTACKS,
BB_BISHOP_MASKS, BB_BISHOP_ATTACKS,
BB_CANNON_RANK_MASKS, BB_CANNON_RANK_ATTACKS,
BB_CANNON_FILE_MASKS, BB_CANNON_FILE_ATTACKS,
BB_RANK_MASKS, BB_RANK_ATTACKS,
BB_FILE_MASKS, BB_FILE_ATTACKS,
BB_PAWN_ATTACKS,
BB_PAWN_REVERSED_ATTACKS,
BB_KING_ATTACKS,
BB_ADVISOR_ATTACKS,
))
@dataclasses.dataclass
class Piece:
piece_type: PieceType
color: Color
def symbol(self) -> str:
symbol = piece_symbol(self.piece_type)
return symbol.upper() if self.color else symbol
def chinese(self) -> str:
symbol = piece_symbol(self.piece_type)
name = PIECES_NAMES[symbol.upper() if self.color else symbol]
return name
def __hash__(self) -> int:
return self.piece_type + (-1 if self.color else 6)
def __repr__(self) -> str:
return f"Piece.from_symbol({self.symbol()!r})"
def __str__(self) -> str:
return self.symbol()
@classmethod
def from_symbol(cls, symbol: str) -> Piece:
return cls(PIECE_SYMBOLS.index(symbol.lower()), symbol.isupper())
@dataclasses.dataclass(unsafe_hash=True)
class Move:
from_square: Square
to_square: Square
def iccs(self) -> str:
if self:
return SQUARE_NAMES[self.from_square] + SQUARE_NAMES[self.to_square]
else:
return "0000"
def __bool__(self) -> bool:
return bool(self.from_square or self.to_square)
def __repr__(self) -> str:
return f"Move.from_uci({self.iccs()!r})"
def __str__(self) -> str:
return self.iccs()
@classmethod
def from_iccs(cls, iccs: str) -> Move:
if iccs == "0000":
return cls.null()
elif len(iccs) == 4:
from_square = SQUARE_NAMES.index(iccs[:2])
to_square = SQUARE_NAMES.index(iccs[2:])
return cls(from_square, to_square)
else:
raise ValueError(
f"expected iccs string to be of length 4: {iccs!r}")
@classmethod
def null(cls) -> Move:
return cls(0, 0)
BoardT = TypeVar("BoardT", bound="Board")
class _BoardState(Generic[BoardT]):
def __init__(self, board: BoardT) -> None:
self.pawns = board.pawns
self.knights = board.knights
self.bishops = board.bishops
self.rooks = board.rooks
self.cannons = board.cannons
self.advisors = board.advisors
self.kings = board.kings
self.occupied_r = board.occupied_co[RED]
self.occupied_b = board.occupied_co[BLACK]
self.occupied = board.occupied
self.turn = board.turn
self.fullmove_number = board.fullmove_number
def restore(self, board: BoardT) -> None:
board.pawns = self.pawns
board.knights = self.knights
board.bishops = self.bishops
board.rooks = self.rooks
board.cannons = self.cannons
board.advisors = self.advisors
board.kings = self.kings
board.occupied_co[RED] = self.occupied_r
board.occupied_co[BLACK] = self.occupied_b
board.occupied = self.occupied
board.turn = self.turn
board.fullmove_number = self.fullmove_number
class BaseBoard:
def __init__(self, board_fen: Optional[str] = STARTING_BOARD_FEN) -> None:
self.occupied_co = [BB_EMPTY, BB_EMPTY]
if board_fen is None:
self._clear_board()
elif board_fen == STARTING_BOARD_FEN:
self._reset_board()
else:
self._set_board_fen(board_fen)
def _reset_board(self) -> None:
self.pawns = BB_RED_PAWNS | BB_BLACK_PAWNS # 卒/兵
self.knights = BB_B0 | BB_H0 | BB_B9 | BB_H9 # 马
self.bishops = BB_C0 | BB_G0 | BB_C9 | BB_G9 # 象/相
self.rooks = BB_A0 | BB_I0 | BB_A9 | BB_I9 # 车
self.cannons = BB_B2 | BB_H2 | BB_B7 | BB_H7 # 炮
self.advisors = BB_D0 | BB_F0 | BB_D9 | BB_F9 # 士/仕
self.kings = BB_E0 | BB_E9 # 将/帅
self.occupied_co[RED] = BB_RANK_0 | BB_B2 | BB_H2 | BB_RED_PAWNS
self.occupied_co[BLACK] = BB_RANK_9 | BB_B7 | BB_H7 | BB_BLACK_PAWNS
self.occupied = self.occupied_co[RED] | self.occupied_co[BLACK]
def reset_board(self) -> None:
self._reset_board()
def _clear_board(self) -> None:
self.pawns = BB_EMPTY
self.knights = BB_EMPTY
self.bishops = BB_EMPTY
self.rooks = BB_EMPTY
self.cannons = BB_EMPTY
self.advisors = BB_EMPTY
self.kings = BB_EMPTY
self.occupied_co[RED] = BB_EMPTY
self.occupied_co[BLACK] = BB_EMPTY
self.occupied = BB_EMPTY
def clear_board(self) -> None:
self._clear_board()
def _set_board_fen(self, fen: str) -> None:
fen = fen.strip()
if " " in fen:
raise ValueError(
f"expected position part of fen, got multiple parts: {fen!r}")
rows = fen.split("/")
if len(rows) != 10:
raise ValueError(
f"expected 9 rows in position part of fen: {fen!r}")
for row in rows:
field_sum = 0
previous_was_digit = False
for c in row:
if c in ["1", "2", "3", "4", "5", "6", "7", "8", "9"]:
if previous_was_digit:
raise ValueError(
f"two subsequent digits in position part of fen: {fen!r}")
field_sum += int(c)
previous_was_digit = True
elif c.lower() in PIECE_SYMBOLS:
field_sum += 1
previous_was_digit = False
else:
raise ValueError(
f"invalid character in position part of fen: {fen!r}")
if field_sum != 9:
raise ValueError(
f"expected 9 columns per row in position part of fen: {fen!r}")
self._clear_board()
square_index = A0
for c in fen:
if c in ["1", "2", "3", "4", "5", "6", "7", "8", "9"]:
square_index += int(c)
elif c.lower() in PIECE_SYMBOLS:
piece = Piece.from_symbol(c)
self._set_piece_at(
SQUARES_180[square_index], piece.piece_type, piece.color)
square_index += 1
else:
square_index += 7
def set_board_fen(self, fen: str) -> None:
self._set_board_fen(fen)
def board_fen(self) -> str:
builder = []
empty = 0
for square in SQUARES_180:
if not square_in_board(square):
continue
piece = self.piece_at(square)
if not piece:
empty += 1
else:
if empty:
builder.append(str(empty))
empty = 0
builder.append(piece.symbol())
if BB_SQUARES[square] & BB_FILE_I:
if empty:
builder.append(str(empty))
empty = 0
if square != I0: # 如果没有遍历到最后一个棋盘格子
builder.append("/")
return "".join(builder)
def _remove_piece_at(self, square: Square) -> Optional[PieceType]:
piece_type = self.piece_type_at(square)
mask = BB_SQUARES[square]
if piece_type == PAWN:
self.pawns ^= mask
elif piece_type == KNIGHT:
self.knights ^= mask
elif piece_type == BISHOP:
self.bishops ^= mask
elif piece_type == ROOK:
self.rooks ^= mask
elif piece_type == CANNON:
self.cannons ^= mask
elif piece_type == KING:
self.kings ^= mask
elif piece_type == ADVISOR:
self.advisors ^= mask
else:
return None
self.occupied ^= mask
self.occupied_co[RED] &= ~mask
self.occupied_co[BLACK] &= ~mask
return piece_type
def remove_piece_at(self, square: Square) -> Optional[Piece]:
color = bool(self.occupied_co[RED] & BB_SQUARES[square])
piece_type = self._remove_piece_at(square)
return Piece(piece_type, color) if piece_type else None
def _set_piece_at(self, square: Square, piece_type: PieceType, color: Color) -> None:
self._remove_piece_at(square)
mask = BB_SQUARES[square]
if piece_type == PAWN:
self.pawns |= mask
elif piece_type == KNIGHT:
self.knights |= mask
elif piece_type == BISHOP:
self.bishops |= mask
elif piece_type == ROOK:
self.rooks |= mask
elif piece_type == CANNON:
self.cannons |= mask
elif piece_type == KING:
self.kings |= mask
elif piece_type == ADVISOR:
self.advisors |= mask
else:
return
self.occupied ^= mask
self.occupied_co[color] ^= mask
def set_piece_at(self, square: Square, piece: Optional[Piece]) -> None:
if piece is None:
self._remove_piece_at(square)
else:
self._set_piece_at(square, piece.piece_type, piece.color)
def pieces_mask(self, piece_type: PieceType, color: Color) -> Bitboard:
if piece_type == PAWN:
bb = self.pawns
elif piece_type == KNIGHT:
bb = self.knights
elif piece_type == BISHOP:
bb = self.bishops
elif piece_type == ROOK:
bb = self.rooks
elif piece_type == CANNON:
bb = self.cannons
elif piece_type == ADVISOR:
bb = self.advisors
elif piece_type == KING:
bb = self.kings
else:
assert False, f"expected PieceType, got {piece_type!r}"
return bb & self.occupied_co[color]
# 将square映射为棋子对象
def piece_at(self, square: Square) -> Optional[Piece]:
piece_type = self.piece_type_at(square) # 确定当前square上的棋子是什么
if piece_type:
mask = BB_SQUARES[square] # SQUARES上的位置转换为BB_SQUARES上的位置
color = bool(self.occupied_co[RED] & mask) # 确定红方还是黑方
return Piece(piece_type, color) # 返回一个棋子实例对象
else:
return None
# 确定当前square上的棋子是什么
def piece_type_at(self, square: Square) -> Optional[PieceType]:
mask = BB_SQUARES[square] # SQUARES上的位置转换为BB_SQUARES上的位置
if not self.occupied & mask:
return None
elif self.pawns & mask:
return PAWN
elif self.knights & mask:
return KNIGHT
elif self.bishops & mask:
return BISHOP
elif self.rooks & mask:
return ROOK
elif self.cannons & mask:
return CANNON
elif self.advisors & mask:
return ADVISOR
else:
return KING
def color_at(self, square: Square) -> Optional[Color]:
mask = BB_SQUARES[square]
if self.occupied_co[RED] & mask:
return RED
elif self.occupied_co[BLACK] & mask:
return BLACK
else:
return None
def king(self, color: Color) -> Optional[Square]:
king_mask = self.occupied_co[color] & self.kings
return msb(king_mask) if king_mask else None
def attacks_mask(self, square: Square) -> Bitboard:
bb_square = BB_SQUARES[square]
if bb_square & self.pawns:
color = bool(bb_square & self.occupied_co[RED])
return BB_PAWN_ATTACKS[color][square]
if bb_square & self.kings:
# 老将对脸杀
return BB_KING_ATTACKS[square] | ((BB_FILE_ATTACKS[square][BB_FILE_MASKS[square] & self.occupied] |
BB_RANK_ATTACKS[square][BB_RANK_MASKS[square] & self.occupied]) & self.kings)
if bb_square & self.advisors:
return BB_ADVISOR_ATTACKS[square]
elif bb_square & self.knights:
return BB_KNIGHT_ATTACKS[square][BB_KNIGHT_MASKS[square] & self.occupied]
elif bb_square & self.bishops:
return BB_BISHOP_ATTACKS[square][BB_BISHOP_MASKS[square] & self.occupied]
elif bb_square & self.rooks:
return (BB_FILE_ATTACKS[square][BB_FILE_MASKS[square] & self.occupied] |
BB_RANK_ATTACKS[square][BB_RANK_MASKS[square] & self.occupied])
elif bb_square & self.cannons:
return (BB_CANNON_FILE_ATTACKS[square][BB_CANNON_FILE_MASKS[square] & self.occupied] |
BB_CANNON_RANK_ATTACKS[square][BB_CANNON_RANK_MASKS[square] & self.occupied] |
((BB_FILE_ATTACKS[square][BB_FILE_MASKS[square] & self.occupied] |
BB_RANK_ATTACKS[square][BB_RANK_MASKS[square] & self.occupied]) & ~self.occupied))
else:
return BB_EMPTY
def _attackers_mask(self, color: Color, square: Square, occupied: Bitboard) -> Bitboard:
cannon_attacks = (BB_CANNON_FILE_ATTACKS[square][BB_CANNON_FILE_MASKS[square] & occupied] |
BB_CANNON_RANK_ATTACKS[square][BB_CANNON_RANK_MASKS[square] & occupied])
rook_attacks = (BB_FILE_ATTACKS[square][BB_FILE_MASKS[square] & occupied] |
BB_RANK_ATTACKS[square][BB_RANK_MASKS[square] & occupied])
attackers = (
(cannon_attacks & self.cannons) |
(rook_attacks & self.rooks) |
(BB_KNIGHT_REVERSED_ATTACKS[square][occupied & BB_KNIGHT_REVERSED_MASKS[square]] & self.knights) |
(BB_BISHOP_ATTACKS[square][occupied & BB_BISHOP_MASKS[square]] & self.bishops) |
(BB_PAWN_REVERSED_ATTACKS[color][square] & self.pawns) |
(BB_ADVISOR_ATTACKS[square] & self.advisors) |
((BB_KING_ATTACKS[square] |
(rook_attacks & self.kings)) & self.kings)
)
return attackers & self.occupied_co[color]
def attackers_mask(self, color: Color, square: Square) -> Bitboard:
return self._attackers_mask(color, square, self.occupied)
def is_attacked_by(self, color: Color, square: Square) -> bool:
return bool(self.attackers_mask(color, square))
def piece_map(self, *, mask: Bitboard = BB_IN_BOARD) -> Dict[Square, Piece]:
result = {}
for square in scan_reversed(self.occupied & mask):
result[square] = typing.cast(Piece, self.piece_at(square))
return result
def __str__(self) -> str:
builder = []
for square in SQUARES_180:
if not BB_SQUARES[square] & BB_IN_BOARD:
continue
piece = self.piece_at(square)
if piece:
builder.append(piece.symbol())
else:
builder.append(".")
if BB_SQUARES[square] & BB_FILE_I:
if square != I0:
builder.append("\n")
else:
builder.append(" ")
return "".join(builder)
def copy(self: BaseBoard) -> BaseBoard:
board = type(self)(None)
board.pawns = self.pawns
board.knights = self.knights
board.bishops = self.bishops
board.rooks = self.rooks
board.cannons = self.cannons
board.advisors = self.advisors
board.kings = self.kings
board.occupied_co[RED] = self.occupied_co[RED]
board.occupied_co[BLACK] = self.occupied_co[BLACK]
board.occupied = self.occupied
return board
def chinese(self) -> str:
builder = []
for square in SQUARES_180:
if not BB_SQUARES[square] & BB_IN_BOARD:
continue
piece = self.piece_at(square)
if BB_SQUARES[square] & BB_FILE_A:
builder.append(RANK_NAMES[square_rank(square)] + " ")
if piece:
builder.append(piece.chinese())
else:
builder.append(".")
if BB_SQUARES[square] & BB_FILE_I:
builder.append("\n")
builder.append(" abcdefghi")
return "".join(builder)
class Board(BaseBoard):
turn: Color
fullmove_number: int
move_stack: List[Move]
def __init__(self: Board, fen: Optional[str] = STARTING_FEN):
BaseBoard.__init__(self, None)
self.move_stack = []
self._stack: List[_BoardState[Board]] = []
if fen is None:
self.clear()
elif fen == STARTING_FEN:
self.reset()
else:
self.set_fen(fen)
@property
def legal_moves(self) -> LegalMoveGenerator:
return LegalMoveGenerator(self)
@property
def pseudo_legal_moves(self) -> PseudoLegalMoveGenerator:
return PseudoLegalMoveGenerator(self)
def clear(self) -> None:
self.turn = RED
self.fullmove_number = 1
self.clear_board()
def reset(self) -> None:
self.turn = RED
self.fullmove_number = 1
self.reset_board()
def set_fen(self, fen: str) -> None:
parts = fen.split()
try:
board_part = parts.pop(0)