-
-
Notifications
You must be signed in to change notification settings - Fork 531
/
__init__.py
3791 lines (3044 loc) · 129 KB
/
__init__.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
# -*- coding: utf-8 -*-
#
# This file is part of the python-chess library.
# Copyright (C) 2012-2019 Niklas Fiekas <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
A pure Python chess library with move generation and validation, Polyglot
opening book probing, PGN reading and writing, Gaviota tablebase probing,
Syzygy tablebase probing and XBoard/UCI engine communication.
"""
__author__ = "Niklas Fiekas"
__email__ = "[email protected]"
__version__ = "0.28.3"
import collections
import copy
import enum
import re
import itertools
import typing
from typing import ClassVar, Callable, Dict, Generic, Hashable, Iterable, Iterator, List, Mapping, MutableSet, Optional, SupportsInt, Tuple, Type, TypeVar, Union
Color = bool
COLORS = [WHITE, BLACK] = [True, False]
COLOR_NAMES = ["black", "white"]
PieceType = int
PIECE_TYPES = [PAWN, KNIGHT, BISHOP, ROOK, QUEEN, KING] = range(1, 7)
PIECE_SYMBOLS = [None, "p", "n", "b", "r", "q", "k"]
PIECE_NAMES = [None, "pawn", "knight", "bishop", "rook", "queen", "king"]
def piece_symbol(piece_type: PieceType, _PIECE_SYMBOLS: List[Optional[str]] = PIECE_SYMBOLS) -> str:
return typing.cast(str, _PIECE_SYMBOLS[piece_type])
def piece_name(piece_type: PieceType) -> str:
return typing.cast(str, PIECE_NAMES[piece_type])
UNICODE_PIECE_SYMBOLS = {
"R": u"♖", "r": u"♜",
"N": u"♘", "n": u"♞",
"B": u"♗", "b": u"♝",
"Q": u"♕", "q": u"♛",
"K": u"♔", "k": u"♚",
"P": u"♙", "p": u"♟",
}
FILE_NAMES = ["a", "b", "c", "d", "e", "f", "g", "h"]
RANK_NAMES = ["1", "2", "3", "4", "5", "6", "7", "8"]
STARTING_FEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"
"""The FEN for the standard chess starting position."""
STARTING_BOARD_FEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR"
"""The board part of the FEN for the standard chess starting position."""
try:
_IntFlag = enum.IntFlag # Since Python 3.6
except AttributeError:
_IntFlag = enum.IntEnum # type: ignore
class Status(_IntFlag):
VALID = 0
NO_WHITE_KING = 1
NO_BLACK_KING = 2
TOO_MANY_KINGS = 4
TOO_MANY_WHITE_PAWNS = 8
TOO_MANY_BLACK_PAWNS = 16
PAWNS_ON_BACKRANK = 32
TOO_MANY_WHITE_PIECES = 64
TOO_MANY_BLACK_PIECES = 128
BAD_CASTLING_RIGHTS = 256
INVALID_EP_SQUARE = 512
OPPOSITE_CHECK = 1024
EMPTY = 2048
RACE_CHECK = 4096
RACE_OVER = 8192
RACE_MATERIAL = 16384
STATUS_VALID = Status.VALID
STATUS_NO_WHITE_KING = Status.NO_WHITE_KING
STATUS_NO_BLACK_KING = Status.NO_BLACK_KING
STATUS_TOO_MANY_KINGS = Status.TOO_MANY_KINGS
STATUS_TOO_MANY_WHITE_PAWNS = Status.TOO_MANY_WHITE_PAWNS
STATUS_TOO_MANY_BLACK_PAWNS = Status.TOO_MANY_BLACK_PAWNS
STATUS_PAWNS_ON_BACKRANK = Status.PAWNS_ON_BACKRANK
STATUS_TOO_MANY_WHITE_PIECES = Status.TOO_MANY_WHITE_PIECES
STATUS_TOO_MANY_BLACK_PIECES = Status.TOO_MANY_BLACK_PIECES
STATUS_BAD_CASTLING_RIGHTS = Status.BAD_CASTLING_RIGHTS
STATUS_INVALID_EP_SQUARE = Status.INVALID_EP_SQUARE
STATUS_OPPOSITE_CHECK = Status.OPPOSITE_CHECK
STATUS_EMPTY = Status.EMPTY
STATUS_RACE_CHECK = Status.RACE_CHECK
STATUS_RACE_OVER = Status.RACE_OVER
STATUS_RACE_MATERIAL = Status.RACE_MATERIAL
Square = int
SQUARES = [
A1, B1, C1, D1, E1, F1, G1, H1,
A2, B2, C2, D2, E2, F2, G2, H2,
A3, B3, C3, D3, E3, F3, G3, H3,
A4, B4, C4, D4, E4, F4, G4, H4,
A5, B5, C5, D5, E5, F5, G5, H5,
A6, B6, C6, D6, E6, F6, G6, H6,
A7, B7, C7, D7, E7, F7, G7, H7,
A8, B8, C8, D8, E8, F8, G8, H8,
] = range(64)
SQUARE_NAMES = [f + r for r in RANK_NAMES for f in FILE_NAMES]
def square(file_index: int, rank_index: int) -> Square:
"""Gets a square number by file and rank index."""
return rank_index * 8 + file_index
def square_file(square: Square) -> int:
"""Gets the file index of the square where ``0`` is the a-file."""
return square & 7
def square_rank(square: Square) -> int:
"""Gets the rank index of the square where ``0`` is the first rank."""
return square >> 3
def square_name(square: Square) -> str:
"""Gets the name of the square, like ``a3``."""
return SQUARE_NAMES[square]
def square_distance(a: Square, b: Square) -> int:
"""
Gets the distance (i.e., the number of king steps) from square *a* to *b*.
"""
return max(abs(square_file(a) - square_file(b)), abs(square_rank(a) - square_rank(b)))
def square_mirror(square: Square) -> Square:
"""Mirrors the square vertically."""
return square ^ 0x38
SQUARES_180 = [square_mirror(sq) for sq in SQUARES]
Bitboard = int
BB_EMPTY = 0
BB_ALL = 0xffffffffffffffff
BB_SQUARES = [
BB_A1, BB_B1, BB_C1, BB_D1, BB_E1, BB_F1, BB_G1, BB_H1,
BB_A2, BB_B2, BB_C2, BB_D2, BB_E2, BB_F2, BB_G2, BB_H2,
BB_A3, BB_B3, BB_C3, BB_D3, BB_E3, BB_F3, BB_G3, BB_H3,
BB_A4, BB_B4, BB_C4, BB_D4, BB_E4, BB_F4, BB_G4, BB_H4,
BB_A5, BB_B5, BB_C5, BB_D5, BB_E5, BB_F5, BB_G5, BB_H5,
BB_A6, BB_B6, BB_C6, BB_D6, BB_E6, BB_F6, BB_G6, BB_H6,
BB_A7, BB_B7, BB_C7, BB_D7, BB_E7, BB_F7, BB_G7, BB_H7,
BB_A8, BB_B8, BB_C8, BB_D8, BB_E8, BB_F8, BB_G8, BB_H8
] = [1 << sq for sq in SQUARES]
BB_CORNERS = BB_A1 | BB_H1 | BB_A8 | BB_H8
BB_CENTER = BB_D4 | BB_E4 | BB_D5 | BB_E5
BB_LIGHT_SQUARES = 0x55aa55aa55aa55aa
BB_DARK_SQUARES = 0xaa55aa55aa55aa55
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
] = [0x0101010101010101 << i for i in range(8)]
BB_RANKS = [
BB_RANK_1,
BB_RANK_2,
BB_RANK_3,
BB_RANK_4,
BB_RANK_5,
BB_RANK_6,
BB_RANK_7,
BB_RANK_8
] = [0xff << (8 * i) for i in range(8)]
BB_BACKRANKS = BB_RANK_1 | BB_RANK_8
def lsb(bb: Bitboard) -> int:
return (bb & -bb).bit_length() - 1
def scan_forward(bb: Bitboard) -> Iterator[Square]:
while bb:
r = bb & -bb
yield r.bit_length() - 1
bb ^= r
def msb(bb: Bitboard) -> int:
return bb.bit_length() - 1
def scan_reversed(bb: Bitboard, *, _BB_SQUARES: List[Bitboard] = BB_SQUARES) -> Iterator[Square]:
while bb:
r = bb.bit_length() - 1
yield r
bb ^= _BB_SQUARES[r]
def popcount(bb: Bitboard, *, _bin: Callable[[int], str] = bin) -> int:
return _bin(bb).count("1")
def flip_vertical(bb: Bitboard) -> Bitboard:
# https://www.chessprogramming.org/Flipping_Mirroring_and_Rotating#FlipVertically
bb = ((bb >> 8) & 0x00ff00ff00ff00ff) | ((bb & 0x00ff00ff00ff00ff) << 8)
bb = ((bb >> 16) & 0x0000ffff0000ffff) | ((bb & 0x0000ffff0000ffff) << 16)
bb = (bb >> 32) | ((bb & 0x00000000ffffffff) << 32)
return bb
def flip_horizontal(bb: Bitboard) -> Bitboard:
# https://www.chessprogramming.org/Flipping_Mirroring_and_Rotating#MirrorHorizontally
bb = ((bb >> 1) & 0x5555555555555555) | ((bb & 0x5555555555555555) << 1)
bb = ((bb >> 2) & 0x3333333333333333) | ((bb & 0x3333333333333333) << 2)
bb = ((bb >> 4) & 0x0f0f0f0f0f0f0f0f) | ((bb & 0x0f0f0f0f0f0f0f0f) << 4)
return bb
def flip_diagonal(bb: Bitboard) -> Bitboard:
# https://www.chessprogramming.org/Flipping_Mirroring_and_Rotating#FlipabouttheDiagonal
t = (bb ^ (bb << 28)) & 0x0f0f0f0f00000000
bb = bb ^ (t ^ (t >> 28))
t = (bb ^ (bb << 14)) & 0x3333000033330000
bb = bb ^ (t ^ (t >> 14))
t = (bb ^ (bb << 7)) & 0x5500550055005500
bb = bb ^ (t ^ (t >> 7))
return bb
def flip_anti_diagonal(bb: Bitboard) -> Bitboard:
# https://www.chessprogramming.org/Flipping_Mirroring_and_Rotating#FlipabouttheAntidiagonal
t = bb ^ (bb << 36)
bb = bb ^ ((t ^ (bb >> 36)) & 0xf0f0f0f00f0f0f0f)
t = (bb ^ (bb << 18)) & 0xcccc0000cccc0000
bb = bb ^ (t ^ (t >> 18))
t = (bb ^ (bb << 9)) & 0xaa00aa00aa00aa00
bb = bb ^ (t ^ (t >> 9))
return bb
def shift_down(b: Bitboard) -> Bitboard:
return b >> 8
def shift_2_down(b: Bitboard) -> Bitboard:
return b >> 16
def shift_up(b: Bitboard) -> Bitboard:
return (b << 8) & BB_ALL
def shift_2_up(b: Bitboard) -> Bitboard:
return (b << 16) & BB_ALL
def shift_right(b: Bitboard) -> Bitboard:
return (b << 1) & ~BB_FILE_A & BB_ALL
def shift_2_right(b: Bitboard) -> Bitboard:
return (b << 2) & ~BB_FILE_A & ~BB_FILE_B & BB_ALL
def shift_left(b: Bitboard) -> Bitboard:
return (b >> 1) & ~BB_FILE_H
def shift_2_left(b: Bitboard) -> Bitboard:
return (b >> 2) & ~BB_FILE_G & ~BB_FILE_H
def shift_up_left(b: Bitboard) -> Bitboard:
return (b << 7) & ~BB_FILE_H & BB_ALL
def shift_up_right(b: Bitboard) -> Bitboard:
return (b << 9) & ~BB_FILE_A & BB_ALL
def shift_down_left(b: Bitboard) -> Bitboard:
return (b >> 9) & ~BB_FILE_H
def shift_down_right(b: Bitboard) -> Bitboard:
return (b >> 7) & ~BB_FILE_A
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 < 64) or square_distance(sq, sq - delta) > 2:
break
attacks |= BB_SQUARES[sq]
if occupied & BB_SQUARES[sq]:
break
return attacks
def _step_attacks(square: Square, deltas: Iterable[int]) -> Bitboard:
return _sliding_attacks(square, BB_ALL, deltas)
BB_KNIGHT_ATTACKS = [_step_attacks(sq, [17, 15, 10, 6, -17, -15, -10, -6]) for sq in SQUARES]
BB_KING_ATTACKS = [_step_attacks(sq, [9, 8, 7, 1, -9, -8, -7, -1]) for sq in SQUARES]
BB_PAWN_ATTACKS = [[_step_attacks(sq, deltas) for sq in SQUARES] for deltas in [[-7, -9], [7, 9]]]
def _edges(square: Square) -> Bitboard:
return (((BB_RANK_1 | BB_RANK_8) & ~BB_RANKS[square_rank(square)]) |
((BB_FILE_A | BB_FILE_H) & ~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]) -> Tuple[List[Bitboard], List[Dict[Bitboard, Bitboard]]]:
mask_table = []
attack_table = []
for square in SQUARES:
attacks = {}
mask = _sliding_attacks(square, 0, deltas) & ~_edges(square)
for subset in _carry_rippler(mask):
attacks[subset] = _sliding_attacks(square, subset, deltas)
attack_table.append(attacks)
mask_table.append(mask)
return mask_table, attack_table
BB_DIAG_MASKS, BB_DIAG_ATTACKS = _attack_table([-9, -7, 7, 9])
BB_FILE_MASKS, BB_FILE_ATTACKS = _attack_table([-8, 8])
BB_RANK_MASKS, BB_RANK_ATTACKS = _attack_table([-1, 1])
def _rays() -> Tuple[List[List[Bitboard]], List[List[Bitboard]]]:
rays = []
between = []
for a, bb_a in enumerate(BB_SQUARES):
rays_row = []
between_row = []
for b, bb_b in enumerate(BB_SQUARES):
if BB_DIAG_ATTACKS[a][0] & bb_b:
rays_row.append((BB_DIAG_ATTACKS[a][0] & BB_DIAG_ATTACKS[b][0]) | bb_a | bb_b)
between_row.append(BB_DIAG_ATTACKS[a][BB_DIAG_MASKS[a] & bb_b] & BB_DIAG_ATTACKS[b][BB_DIAG_MASKS[b] & bb_a])
elif BB_RANK_ATTACKS[a][0] & bb_b:
rays_row.append(BB_RANK_ATTACKS[a][0] | bb_a)
between_row.append(BB_RANK_ATTACKS[a][BB_RANK_MASKS[a] & bb_b] & BB_RANK_ATTACKS[b][BB_RANK_MASKS[b] & bb_a])
elif BB_FILE_ATTACKS[a][0] & bb_b:
rays_row.append(BB_FILE_ATTACKS[a][0] | bb_a)
between_row.append(BB_FILE_ATTACKS[a][BB_FILE_MASKS[a] & bb_b] & BB_FILE_ATTACKS[b][BB_FILE_MASKS[b] & bb_a])
else:
rays_row.append(BB_EMPTY)
between_row.append(BB_EMPTY)
rays.append(rays_row)
between.append(between_row)
return rays, between
BB_RAYS, BB_BETWEEN = _rays()
SAN_REGEX = re.compile(r"^([NBKRQ])?([a-h])?([1-8])?[\-x]?([a-h][1-8])(=?[nbrqkNBRQK])?(\+|#)?\Z")
FEN_CASTLING_REGEX = re.compile(r"^(?:-|[KQABCDEFGH]{0,2}[kqabcdefgh]{0,2})\Z")
class Piece:
"""A piece with type and color."""
def __init__(self, piece_type: PieceType, color: Color) -> None:
self.piece_type = piece_type
self.color = color
def symbol(self) -> str:
"""
Gets the symbol ``P``, ``N``, ``B``, ``R``, ``Q`` or ``K`` for white
pieces or the lower-case variants for the black pieces.
"""
symbol = piece_symbol(self.piece_type)
return symbol.upper() if self.color else symbol
def unicode_symbol(self, *, invert_color: bool = False) -> str:
"""
Gets the Unicode character for the piece.
"""
symbol = self.symbol().swapcase() if invert_color else self.symbol()
return UNICODE_PIECE_SYMBOLS[symbol]
def __hash__(self) -> int:
return hash(self.piece_type * (self.color + 1))
def __repr__(self) -> str:
return "Piece.from_symbol({!r})".format(self.symbol())
def __str__(self) -> str:
return self.symbol()
def _repr_svg_(self) -> str:
import chess.svg
return chess.svg.piece(self, size=45)
def __eq__(self, other: object) -> bool:
if isinstance(other, Piece):
return (self.piece_type, self.color) == (other.piece_type, other.color)
else:
return NotImplemented
@classmethod
def from_symbol(cls, symbol: str) -> "Piece":
"""
Creates a :class:`~chess.Piece` instance from a piece symbol.
:raises: :exc:`ValueError` if the symbol is invalid.
"""
return cls(PIECE_SYMBOLS.index(symbol.lower()), symbol.isupper())
class Move:
"""
Represents a move from a square to a square and possibly the promotion
piece type.
Drops and null moves are supported.
"""
def __init__(self, from_square: Square, to_square: Square, promotion: Optional[PieceType] = None, drop: Optional[PieceType] = None) -> None:
self.from_square = from_square
self.to_square = to_square
self.promotion = promotion
self.drop = drop
def uci(self) -> str:
"""
Gets an UCI string for the move.
For example, a move from a7 to a8 would be ``a7a8`` or ``a7a8q``
(if the latter is a promotion to a queen).
The UCI representation of a null move is ``0000``.
"""
if self.drop:
return piece_symbol(self.drop).upper() + "@" + SQUARE_NAMES[self.to_square]
elif self.promotion:
return SQUARE_NAMES[self.from_square] + SQUARE_NAMES[self.to_square] + piece_symbol(self.promotion)
elif self:
return SQUARE_NAMES[self.from_square] + SQUARE_NAMES[self.to_square]
else:
return "0000"
def xboard(self) -> str:
return self.uci() if self else "@@@@"
def __bool__(self) -> bool:
return bool(self.from_square or self.to_square or self.promotion or self.drop)
def __eq__(self, other: object) -> bool:
if isinstance(other, Move):
return (
self.from_square == other.from_square and
self.to_square == other.to_square and
self.promotion == other.promotion and
self.drop == other.drop)
else:
return NotImplemented
def __repr__(self) -> str:
return "Move.from_uci({!r})".format(self.uci())
def __str__(self) -> str:
return self.uci()
def __hash__(self) -> int:
return hash((self.to_square, self.from_square, self.promotion, self.drop))
@classmethod
def from_uci(cls, uci: str) -> "Move":
"""
Parses an UCI string.
:raises: :exc:`ValueError` if the UCI string is invalid.
"""
if uci == "0000":
return cls.null()
elif len(uci) == 4 and "@" == uci[1]:
drop = PIECE_SYMBOLS.index(uci[0].lower())
square = SQUARE_NAMES.index(uci[2:])
return cls(square, square, drop=drop)
elif 4 <= len(uci) <= 5:
from_square = SQUARE_NAMES.index(uci[0:2])
to_square = SQUARE_NAMES.index(uci[2:4])
promotion = PIECE_SYMBOLS.index(uci[4]) if len(uci) == 5 else None
if from_square == to_square:
raise ValueError("invalid uci (use 0000 for null moves): {!r}".format(uci))
return cls(from_square, to_square, promotion=promotion)
else:
raise ValueError("expected uci string to be of length 4 or 5: {!r}".format(uci))
@classmethod
def null(cls) -> "Move":
"""
Gets a null move.
A null move just passes the turn to the other side (and possibly
forfeits en passant capturing). Null moves evaluate to ``False`` in
boolean contexts.
>>> import chess
>>>
>>> bool(chess.Move.null())
False
"""
return cls(0, 0)
BaseBoardT = TypeVar("BaseBoardT", bound="BaseBoard")
class BaseBoard:
"""
A board representing the position of chess pieces. See
:class:`~chess.Board` for a full board with move generation.
The board is initialized with the standard chess starting position, unless
otherwise specified in the optional *board_fen* argument. If *board_fen*
is ``None``, an empty board is created.
"""
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_RANK_2 | BB_RANK_7
self.knights = BB_B1 | BB_G1 | BB_B8 | BB_G8
self.bishops = BB_C1 | BB_F1 | BB_C8 | BB_F8
self.rooks = BB_CORNERS
self.queens = BB_D1 | BB_D8
self.kings = BB_E1 | BB_E8
self.promoted = BB_EMPTY
self.occupied_co[WHITE] = BB_RANK_1 | BB_RANK_2
self.occupied_co[BLACK] = BB_RANK_7 | BB_RANK_8
self.occupied = BB_RANK_1 | BB_RANK_2 | BB_RANK_7 | BB_RANK_8
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.queens = BB_EMPTY
self.kings = BB_EMPTY
self.promoted = BB_EMPTY
self.occupied_co[WHITE] = BB_EMPTY
self.occupied_co[BLACK] = BB_EMPTY
self.occupied = BB_EMPTY
def clear_board(self) -> None:
"""Clears the board."""
self._clear_board()
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 == QUEEN:
bb = self.queens
elif piece_type == KING:
bb = self.kings
return bb & self.occupied_co[color]
def pieces(self, piece_type: PieceType, color: Color) -> "SquareSet":
"""
Gets pieces of the given type and color.
Returns a :class:`set of squares <chess.SquareSet>`.
"""
return SquareSet(self.pieces_mask(piece_type, color))
def piece_at(self, square: Square) -> Optional[Piece]:
"""Gets the :class:`piece <chess.Piece>` at the given square."""
piece_type = self.piece_type_at(square)
if piece_type:
mask = BB_SQUARES[square]
color = bool(self.occupied_co[WHITE] & mask)
return Piece(piece_type, color)
else:
return None
def piece_type_at(self, square: Square) -> Optional[PieceType]:
"""Gets the piece type at the given square."""
mask = BB_SQUARES[square]
if not self.occupied & mask:
return None # Early return
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.queens & mask:
return QUEEN
else:
return KING
def color_at(self, square: Square) -> Optional[Color]:
"""Gets the color of the piece at the given square."""
mask = BB_SQUARES[square]
if self.occupied_co[WHITE] & mask:
return WHITE
elif self.occupied_co[BLACK] & mask:
return BLACK
else:
return None
def king(self, color: Color) -> Optional[Square]:
"""
Finds the king square of the given side. Returns ``None`` if there
is no king of that color.
In variants with king promotions, only non-promoted kings are
considered.
"""
king_mask = self.occupied_co[color] & self.kings & ~self.promoted
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[WHITE])
return BB_PAWN_ATTACKS[color][square]
elif bb_square & self.knights:
return BB_KNIGHT_ATTACKS[square]
elif bb_square & self.kings:
return BB_KING_ATTACKS[square]
else:
attacks = 0
if bb_square & self.bishops or bb_square & self.queens:
attacks = BB_DIAG_ATTACKS[square][BB_DIAG_MASKS[square] & self.occupied]
if bb_square & self.rooks or bb_square & self.queens:
attacks |= (BB_RANK_ATTACKS[square][BB_RANK_MASKS[square] & self.occupied] |
BB_FILE_ATTACKS[square][BB_FILE_MASKS[square] & self.occupied])
return attacks
def attacks(self, square: Square) -> "SquareSet":
"""
Gets the set of attacked squares from the given square.
There will be no attacks if the square is empty. Pinned pieces are
still attacking other squares.
Returns a :class:`set of squares <chess.SquareSet>`.
"""
return SquareSet(self.attacks_mask(square))
def _attackers_mask(self, color: Color, square: Square, occupied: Bitboard) -> Bitboard:
rank_pieces = BB_RANK_MASKS[square] & occupied
file_pieces = BB_FILE_MASKS[square] & occupied
diag_pieces = BB_DIAG_MASKS[square] & occupied
queens_and_rooks = self.queens | self.rooks
queens_and_bishops = self.queens | self.bishops
attackers = (
(BB_KING_ATTACKS[square] & self.kings) |
(BB_KNIGHT_ATTACKS[square] & self.knights) |
(BB_RANK_ATTACKS[square][rank_pieces] & queens_and_rooks) |
(BB_FILE_ATTACKS[square][file_pieces] & queens_and_rooks) |
(BB_DIAG_ATTACKS[square][diag_pieces] & queens_and_bishops) |
(BB_PAWN_ATTACKS[not color][square] & self.pawns))
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:
"""
Checks if the given side attacks the given square.
Pinned pieces still count as attackers. Pawns that can be captured
en passant are **not** considered attacked.
"""
return bool(self.attackers_mask(color, square))
def attackers(self, color: Color, square: Square) -> "SquareSet":
"""
Gets the set of attackers of the given color for the given square.
Pinned pieces still count as attackers.
Returns a :class:`set of squares <chess.SquareSet>`.
"""
return SquareSet(self.attackers_mask(color, square))
def pin_mask(self, color: Color, square: Square) -> Bitboard:
king = self.king(color)
if king is None:
return BB_ALL
square_mask = BB_SQUARES[square]
for attacks, sliders in [(BB_FILE_ATTACKS, self.rooks | self.queens),
(BB_RANK_ATTACKS, self.rooks | self.queens),
(BB_DIAG_ATTACKS, self.bishops | self.queens)]:
rays = attacks[king][0]
if rays & square_mask:
snipers = rays & sliders & self.occupied_co[not color]
for sniper in scan_reversed(snipers):
if BB_BETWEEN[sniper][king] & (self.occupied | square_mask) == square_mask:
return BB_RAYS[king][sniper]
break
return BB_ALL
def pin(self, color: Color, square: Square) -> "SquareSet":
"""
Detects an absolute pin (and its direction) of the given square to
the king of the given color.
>>> import chess
>>>
>>> board = chess.Board("rnb1k2r/ppp2ppp/5n2/3q4/1b1P4/2N5/PP3PPP/R1BQKBNR w KQkq - 3 7")
>>> board.is_pinned(chess.WHITE, chess.C3)
True
>>> direction = board.pin(chess.WHITE, chess.C3)
>>> direction
SquareSet(0x0000000102040810)
>>> print(direction)
. . . . . . . .
. . . . . . . .
. . . . . . . .
1 . . . . . . .
. 1 . . . . . .
. . 1 . . . . .
. . . 1 . . . .
. . . . 1 . . .
Returns a :class:`set of squares <chess.SquareSet>` that mask the rank,
file or diagonal of the pin. If there is no pin, then a mask of the
entire board is returned.
"""
return SquareSet(self.pin_mask(color, square))
def is_pinned(self, color: Color, square: Square) -> bool:
"""
Detects if the given square is pinned to the king of the given color.
"""
return self.pin_mask(color, square) != BB_ALL
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 == QUEEN:
self.queens ^= mask
elif piece_type == KING:
self.kings ^= mask
else:
return None
self.occupied ^= mask
self.occupied_co[WHITE] &= ~mask
self.occupied_co[BLACK] &= ~mask
self.promoted &= ~mask
return piece_type
def remove_piece_at(self, square: Square) -> Optional[Piece]:
"""
Removes the piece from the given square. Returns the
:class:`~chess.Piece` or ``None`` if the square was already empty.
"""
color = bool(self.occupied_co[WHITE] & 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, promoted: bool = False) -> 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 == QUEEN:
self.queens |= mask
elif piece_type == KING:
self.kings |= mask
else:
return
self.occupied ^= mask
self.occupied_co[color] ^= mask
if promoted:
self.promoted ^= mask
def set_piece_at(self, square: Square, piece: Optional[Piece], promoted: bool = False) -> None:
"""
Sets a piece at the given square.
An existing piece is replaced. Setting *piece* to ``None`` is
equivalent to :func:`~chess.Board.remove_piece_at()`.
"""
if piece is None:
self._remove_piece_at(square)
else:
self._set_piece_at(square, piece.piece_type, piece.color, promoted)
def board_fen(self, *, promoted: Optional[bool] = False) -> str:
"""
Gets the board FEN.
"""
builder = []
empty = 0
for square in SQUARES_180:
piece = self.piece_at(square)
if not piece:
empty += 1
else:
if empty:
builder.append(str(empty))
empty = 0
builder.append(piece.symbol())
if promoted and BB_SQUARES[square] & self.promoted:
builder.append("~")
if BB_SQUARES[square] & BB_FILE_H:
if empty:
builder.append(str(empty))
empty = 0
if square != H1:
builder.append("/")
return "".join(builder)
def _set_board_fen(self, fen: str) -> None:
# Compability with set_fen().
fen = fen.strip()
if " " in fen:
raise ValueError("expected position part of fen, got multiple parts: {!r}".format(fen))
# Ensure the FEN is valid.
rows = fen.split("/")
if len(rows) != 8:
raise ValueError("expected 8 rows in position part of fen: {!r}".format(fen))
# Validate each row.
for row in rows:
field_sum = 0
previous_was_digit = False
previous_was_piece = False
for c in row:
if c in ["1", "2", "3", "4", "5", "6", "7", "8"]:
if previous_was_digit:
raise ValueError("two subsequent digits in position part of fen: {!r}".format(fen))
field_sum += int(c)
previous_was_digit = True
previous_was_piece = False
elif c == "~":
if not previous_was_piece:
raise ValueError("'~' not after piece in position part of fen: {!r}".format(fen))
previous_was_digit = False
previous_was_piece = False
elif c.lower() in PIECE_SYMBOLS:
field_sum += 1
previous_was_digit = False
previous_was_piece = True
else:
raise ValueError("invalid character in position part of fen: {!r}".format(fen))
if field_sum != 8:
raise ValueError("expected 8 columns per row in position part of fen: {!r}".format(fen))
# Clear the board.
self._clear_board()
# Put pieces on the board.
square_index = 0
for c in fen:
if c in ["1", "2", "3", "4", "5", "6", "7", "8"]:
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
elif c == "~":
self.promoted |= BB_SQUARES[SQUARES_180[square_index - 1]]
def set_board_fen(self, fen: str) -> None:
"""
Parses a FEN and sets the board from it.
:raises: :exc:`ValueError` if the FEN string is invalid.
"""
self._set_board_fen(fen)
def piece_map(self) -> Dict[Square, Piece]:
"""
Gets a dictionary of :class:`pieces <chess.Piece>` by square index.
"""
result = {}
for square in scan_reversed(self.occupied):
result[square] = typing.cast(Piece, self.piece_at(square))
return result
def _set_piece_map(self, pieces: Mapping[Square, Piece]) -> None:
self._clear_board()
for square, piece in pieces.items():
self._set_piece_at(square, piece.piece_type, piece.color)
def set_piece_map(self, pieces: Mapping[Square, Piece]) -> None:
"""
Sets up the board from a dictionary of :class:`pieces <chess.Piece>`
by square index.
"""
self._set_piece_map(pieces)
def _set_chess960_pos(self, sharnagl: int) -> None:
if not 0 <= sharnagl <= 959:
raise ValueError("chess960 position index not 0 <= {:d} <= 959".format(sharnagl))
# See http://www.russellcottrell.com/Chess/Chess960.htm for
# a description of the algorithm.
n, bw = divmod(sharnagl, 4)
n, bb = divmod(n, 4)
n, q = divmod(n, 6)
for n1 in range(0, 4):
n2 = n + (3 - n1) * (4 - n1) // 2 - 5
if n1 < n2 and 1 <= n2 <= 4:
break
# Bishops.
bw_file = bw * 2 + 1
bb_file = bb * 2
self.bishops = (BB_FILES[bw_file] | BB_FILES[bb_file]) & BB_BACKRANKS