-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
5893 lines (5213 loc) · 150 KB
/
index.ts
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
/**
* A 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.
*
* All credit goes to the authors of the python-chess library.
* This is a direct port of their excellent library to TypeScript.
*/
/** ========== Custom declarations (no mirror in python-chess) ========== */
import {
bitLength,
bitCount,
bool,
boolToNumber,
Counter,
divmod,
enumerate,
iterAny,
iterAll,
iterFilter,
iterIncludes,
iterMap,
iterNext,
parseIntStrict,
range,
StopIteration,
} from './utils'
export type RankOrFileIndex = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7
/** Allow the truthy/falsy indexing trick, like `this.occupiedCo[colorIdx(WHITE)]` */
export const colorIdx = (color: Color): 1 | 0 => boolToNumber(color)
/** ========== Direct transpilation ========== */
export const __author__ = 'Niklas Fiekas'
export const __email__ = '[email protected]'
export const __version__ = '1.10.0'
export const __transpilerAuthor__ = 'Jackson Thurner Hall'
export const __transpiledVersion__ = '0.0.1'
export type EnPassantSpec = 'legal' | 'fen' | 'xfen'
export type Color = boolean
export const [WHITE, BLACK] = [true, false]
export const COLORS: Color[] = [WHITE, BLACK]
export type ColorName = 'white' | 'black'
export const COLOR_NAMES: ColorName[] = ['black', 'white']
export const enum PieceType {
PAWN = 1,
KNIGHT, // = 2, etc.
BISHOP,
ROOK,
QUEEN,
KING,
}
export const PIECE_TYPES: PieceType[] = Array.from(
{ length: 6 },
(_, i) => i + 1,
)
export const [PAWN, KNIGHT, BISHOP, ROOK, QUEEN, KING] = PIECE_TYPES
export const PIECE_SYMBOLS: (string | null)[] = [
null,
'p',
'n',
'b',
'r',
'q',
'k',
]
export const PIECE_NAMES: (string | null)[] = [
null,
'pawn',
'knight',
'bishop',
'rook',
'queen',
'king',
]
export const pieceSymbol = (pieceType: PieceType) => {
return PIECE_SYMBOLS[pieceType] as string
}
export const pieceName = (pieceType: PieceType) => {
return PIECE_NAMES[pieceType] as string
}
export const UNICODE_PIECE_SYMBOLS: { [key: string]: string } = {
R: '♖',
r: '♜',
N: '♘',
n: '♞',
B: '♗',
b: '♝',
Q: '♕',
q: '♛',
K: '♔',
k: '♚',
P: '♙',
p: '♟',
}
export const FILE_NAMES: string[] = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
export const RANK_NAMES: string[] = ['1', '2', '3', '4', '5', '6', '7', '8']
/** The FEN for the standard chess starting position. */
export const STARTING_FEN =
'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'
/** The board part of the FEN for the standard chess starting position. */
export const STARTING_BOARD_FEN = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR'
export const enum Status {
VALID = 0,
NO_WHITE_KING = 1 << 0,
NO_BLACK_KING = 1 << 1,
TOO_MANY_KINGS = 1 << 2,
TOO_MANY_WHITE_PAWNS = 1 << 3,
TOO_MANY_BLACK_PAWNS = 1 << 4,
PAWNS_ON_BACKRANK = 1 << 5,
TOO_MANY_WHITE_PIECES = 1 << 6,
TOO_MANY_BLACK_PIECES = 1 << 7,
BAD_CASTLING_RIGHTS = 1 << 8,
INVALID_EP_SQUARE = 1 << 9,
OPPOSITE_CHECK = 1 << 10,
EMPTY = 1 << 11,
RACE_CHECK = 1 << 12,
RACE_OVER = 1 << 13,
RACE_MATERIAL = 1 << 14,
TOO_MANY_CHECKERS = 1 << 15,
IMPOSSIBLE_CHECK = 1 << 16,
}
export const STATUS_VALID = Status.VALID
export const STATUS_NO_WHITE_KING = Status.NO_WHITE_KING
export const STATUS_NO_BLACK_KING = Status.NO_BLACK_KING
export const STATUS_TOO_MANY_KINGS = Status.TOO_MANY_KINGS
export const STATUS_TOO_MANY_WHITE_PAWNS = Status.TOO_MANY_WHITE_PAWNS
export const STATUS_TOO_MANY_BLACK_PAWNS = Status.TOO_MANY_BLACK_PAWNS
export const STATUS_PAWNS_ON_BACKRANK = Status.PAWNS_ON_BACKRANK
export const STATUS_TOO_MANY_WHITE_PIECES = Status.TOO_MANY_WHITE_PIECES
export const STATUS_TOO_MANY_BLACK_PIECES = Status.TOO_MANY_BLACK_PIECES
export const STATUS_BAD_CASTLING_RIGHTS = Status.BAD_CASTLING_RIGHTS
export const STATUS_INVALID_EP_SQUARE = Status.INVALID_EP_SQUARE
export const STATUS_OPPOSITE_CHECK = Status.OPPOSITE_CHECK
export const STATUS_EMPTY = Status.EMPTY
export const STATUS_RACE_CHECK = Status.RACE_CHECK
export const STATUS_RACE_OVER = Status.RACE_OVER
export const STATUS_RACE_MATERIAL = Status.RACE_MATERIAL
export const STATUS_TOO_MANY_CHECKERS = Status.TOO_MANY_CHECKERS
export const STATUS_IMPOSSIBLE_CHECK = Status.IMPOSSIBLE_CHECK
/**
* Enum with reasons for a game to be over.
*/
export enum Termination {
/** See :func:`chess.Board.isCheckmate()`. */
CHECKMATE,
/** See :func:`chess.Board.isStalemate()`. */
STALEMATE,
/** See :func:`chess.Board.isInsufficientMaterial()`. */
INSUFFICIENT_MATERIAL,
/** See :func:`chess.Board.isSeventyfiveMoves()`. */
SEVENTYFIVE_MOVES,
/** See :func:`chess.Board.isFivefoldRepetition()`. */
FIVEFOLD_REPETITION,
/** See :func:`chess.Board.canClaimFiftyMoves()`. */
FIFTY_MOVES,
/** See :func:`chess.Board.canClaimThreefoldRepetition()`. */
THREEFOLD_REPETITION,
/** See :func:`chess.Board.isVariantWin()`. */
VARIANT_WIN,
/** See :func:`chess.Board.isVariantLoss()`. */
VARIANT_LOSS,
/** See :func:`chess.Board.isVariantDraw()`. */
VARIANT_DRAW,
}
/**
* Information about the outcome of an ended game, usually obtained from
* :func:`chess.Board.outcome()`.
*/
export class Outcome {
termination: Termination
/** The reason for the game to have ended. */
winner: Color | null
/** The winning color or ``null`` if drawn. */
constructor(termination: Termination, winner: Color | null) {
this.termination = termination
this.winner = winner
}
/**
* Returns ``1-0``, ``0-1`` or ``1/2-1/2``.
*/
result(): '1-0' | '0-1' | '1/2-1/2' {
return this.winner === null ? '1/2-1/2' : this.winner ? '1-0' : '0-1'
}
}
/**
* Raised when move notation is not syntactically valid
*/
export class InvalidMoveError extends Error {
constructor(message?: string) {
super(message)
this.name = 'InvalidMoveError'
Object.setPrototypeOf(this, InvalidMoveError.prototype)
}
}
/**
* Raised when the attempted move is illegal in the current position
*/
export class IllegalMoveError extends Error {
constructor(message?: string) {
super(message)
this.name = 'IllegalMoveError'
Object.setPrototypeOf(this, IllegalMoveError.prototype)
}
}
/**
* Raised when the attempted move is ambiguous in the current position
*/
export class AmbiguousMoveError extends Error {
constructor(message?: string) {
super(message)
this.name = 'AmbiguousMoveError'
Object.setPrototypeOf(this, AmbiguousMoveError.prototype)
}
}
// prettier-ignore
export const enum Square { // Instead of `Square = number`
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,
}
export const SQUARES = Array.from(range(64)) as Square[]
// prettier-ignore
export const [
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,
] = SQUARES;
export const SQUARE_NAMES = RANK_NAMES.flatMap(r => FILE_NAMES.map(f => f + r))
/**
* Gets the square index for the given square *name*
* (e.g., ``a1`` returns ``0``).
*
* @throws :exc:`Error` if the square name is invalid.
*/
export const parseSquare = (name: string): Square => {
const idx = SQUARE_NAMES.indexOf(name)
if (idx === -1) {
throw new Error(`Invalid square name ${name}`)
}
return idx as Square
}
/**
* Gets the name of the square, like ``a3``.
*/
export const squareName = (square: Square): string => {
return SQUARE_NAMES[square]
}
/**
* Gets a square number by file and rank index.
*/
export const square = (
fileIndex: RankOrFileIndex,
rankIndex: RankOrFileIndex,
): Square => {
return (rankIndex * 8 + fileIndex) as Square
}
/**
* Gets the file index of the square where ``0`` is the a-file.
*/
export const squareFile = (square: Square): RankOrFileIndex => {
return (square & 7) as RankOrFileIndex
}
/**
* Gets the rank index of the square where ``0`` is the first rank.
*/
export const squareRank = (square: Square): RankOrFileIndex => {
return (square >> 3) as RankOrFileIndex
}
/**
* Gets the Chebyshev distance (i.e., the number of king steps) from square *a* to *b*.
*/
export const squareDistance = (a: Square, b: Square): number => {
return Math.max(
Math.abs(squareFile(a) - squareFile(b)),
Math.abs(squareRank(a) - squareRank(b)),
)
}
/**
* Gets the Manhattan/Taxicab distance (i.e., the number of orthogonal king steps) from square *a* to *b*.
*/
export const squareManhattanDistance = (a: Square, b: Square): number => {
return (
Math.abs(squareFile(a) - squareFile(b)) +
Math.abs(squareRank(a) - squareRank(b))
)
}
/**
* Gets the Knight distance (i.e., the number of knight moves) from square *a* to *b*.
*/
export const squareKnightDistance = (a: Square, b: Square): number => {
const dx = Math.abs(squareFile(a) - squareFile(b))
const dy = Math.abs(squareRank(a) - squareRank(b))
if (dx + dy === 1) {
return 3
} else if (dx === dy && dy === 2) {
return 4
} else if (dx === dy && dy === 1) {
if (BB_SQUARES[a] & BB_CORNERS || BB_SQUARES[b] & BB_CORNERS) {
// Special case only for corner squares
return 4
}
}
const m = Math.ceil(Math.max(dx / 2, dy / 2, (dx + dy) / 3))
return m + ((m + dx + dy) % 2)
}
/**
* Mirrors the square vertically.
*/
export const squareMirror = (square: Square): Square => {
return square ^ (0x38 as Square)
}
export const SQUARES_180 = SQUARES.map(squareMirror)
export type Bitboard = bigint
export const BB_EMPTY = 0n
export const BB_ALL = 0xffff_ffff_ffff_ffffn
export const BB_SQUARES = SQUARES.map(s => 1n << BigInt(s))
// prettier-ignore
export const [
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,
] = BB_SQUARES;
export const BB_CORNERS = BB_A1 | BB_H1 | BB_A8 | BB_H8
export const BB_CENTER = BB_D4 | BB_E4 | BB_D5 | BB_E5
export const BB_LIGHT_SQUARES = 0x55aa_55aa_55aa_55aan
export const BB_DARK_SQUARES = 0xaa55_aa55_aa55_aa55n
export const BB_FILES = Array.from(range(8)).map(
i => 0x0101_0101_0101_0101n << BigInt(i),
)
export const [
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_FILES
export const BB_RANKS = Array.from(range(8)).map(i => 0xffn << BigInt(8 * i))
export const [
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_RANKS
export const BB_BACKRANKS = BB_RANK_1 | BB_RANK_8
export const lsb = (bb: Bitboard): Square => {
return bitLength(bb & -bb) - 1
}
export function* scanForward(bb: Bitboard): IterableIterator<Square> {
while (bb) {
let r = bb & -bb
yield (bitLength(r) - 1) as Square
bb ^= r
}
}
export const msb = (bb: Bitboard): Square => {
return (bitLength(bb) - 1) as Square
}
export function* scanReversed(bb: Bitboard): IterableIterator<Square> {
while (bb) {
let r = bitLength(bb) - 1
yield r as Square
bb ^= BB_SQUARES[r]
}
}
export const popcount = (bb: Bitboard): number => bitCount(bb)
export const flipVertical = (bb: Bitboard): Bitboard => {
// https://www.chessprogramming.org/Flipping_Mirroring_and_Rotating#FlipVertically
bb =
((bb >> 8n) & 0x00ff_00ff_00ff_00ffn) |
((bb & 0x00ff_00ff_00ff_00ffn) << 8n)
bb =
((bb >> 16n) & 0x0000_ffff_0000_ffffn) |
((bb & 0x0000_ffff_0000_ffffn) << 16n)
bb = (bb >> 32n) | ((bb & 0x0000_0000_ffff_ffffn) << 32n)
return bb
}
export const flipHorizontal = (bb: Bitboard): Bitboard => {
// https://www.chessprogramming.org/Flipping_Mirroring_and_Rotating#MirrorHorizontally
bb =
((bb >> 1n) & 0x5555_5555_5555_5555n) |
((bb & 0x5555_5555_5555_5555n) << 1n)
bb =
((bb >> 2n) & 0x3333_3333_3333_3333n) |
((bb & 0x3333_3333_3333_3333n) << 2n)
bb =
((bb >> 4n) & 0x0f0f_0f0f_0f0f_0f0fn) |
((bb & 0x0f0f_0f0f_0f0f_0f0fn) << 4n)
return bb
}
export const flipDiagonal = (bb: Bitboard): Bitboard => {
// https://www.chessprogramming.org/Flipping_Mirroring_and_Rotating#FlipabouttheDiagonal
let t = (bb ^ (bb << 28n)) & 0x0f0f_0f0f_0000_0000n
bb = bb ^ t ^ (t >> 28n)
t = (bb ^ (bb << 14n)) & 0x3333_0000_3333_0000n
bb = bb ^ t ^ (t >> 14n)
t = (bb ^ (bb << 7n)) & 0x5500_5500_5500_5500n
bb = bb ^ t ^ (t >> 7n)
return bb
}
export const flipAntiDiagonal = (bb: Bitboard): Bitboard => {
// https://www.chessprogramming.org/Flipping_Mirroring_and_Rotating#FlipabouttheAntidiagonal
let t = bb ^ (bb << 36n)
bb = bb ^ ((t ^ (bb >> 36n)) & 0xf0f0_f0f0_0f0f_0f0fn)
t = (bb ^ (bb << 18n)) & 0xcccc_0000_cccc_0000n
bb = bb ^ t ^ (t >> 18n)
t = (bb ^ (bb << 9n)) & 0xaa00_aa00_aa00_aa00n
bb = bb ^ t ^ (t >> 9n)
return bb
}
export const shiftDown = (b: Bitboard): Bitboard => {
return b >> 8n
}
export const shift2Down = (b: Bitboard): Bitboard => {
return b >> 16n
}
export const shiftUp = (b: Bitboard): Bitboard => {
return (b << 8n) & BB_ALL
}
export const shift2Up = (b: Bitboard): Bitboard => {
return (b << 16n) & BB_ALL
}
export const shiftRight = (b: Bitboard): Bitboard => {
return (b << 1n) & ~BB_FILE_A & BB_ALL
}
export const shift2Right = (b: Bitboard): Bitboard => {
return (b << 2n) & ~BB_FILE_A & ~BB_FILE_B & BB_ALL
}
export const shiftLeft = (b: Bitboard): Bitboard => {
return (b >> 1n) & ~BB_FILE_H
}
export const shift2Left = (b: Bitboard): Bitboard => {
return (b >> 2n) & ~BB_FILE_G & ~BB_FILE_H
}
export const shiftUpLeft = (b: Bitboard): Bitboard => {
return (b << 7n) & ~BB_FILE_H & BB_ALL
}
export const shiftUpRight = (b: Bitboard): Bitboard => {
return (b << 9n) & ~BB_FILE_A & BB_ALL
}
export const shiftDownLeft = (b: Bitboard): Bitboard => {
return (b >> 9n) & ~BB_FILE_H
}
export const shiftDownRight = (b: Bitboard): Bitboard => {
return (b >> 7n) & ~BB_FILE_A
}
export const _slidingAttacks = (
square: Square,
occupied: Bitboard,
deltas: number[],
) => {
let attacks = BB_EMPTY
for (const delta of deltas) {
let sq = square
while (true) {
sq += delta
if (!(0 <= sq && sq < 64) || squareDistance(sq, sq - delta) > 2) {
break
}
attacks |= BB_SQUARES[sq]
if (occupied & BB_SQUARES[sq]) {
break
}
}
}
return attacks
}
export const _stepAttacks = (square: Square, deltas: number[]): Bitboard => {
return _slidingAttacks(square, BB_ALL, deltas)
}
export const BB_KNIGHT_ATTACKS = SQUARES.map(sq =>
_stepAttacks(sq, [17, 15, 10, 6, -17, -15, -10, -6]),
)
export const BB_KING_ATTACKS = SQUARES.map(sq =>
_stepAttacks(sq, [9, 8, 7, 1, -9, -8, -7, -1]),
)
export const BB_PAWN_ATTACKS = [
[-7, -9],
[7, 9],
].map(deltas => SQUARES.map(sq => _stepAttacks(sq, deltas)))
export const _edges = (square: Square): Bitboard => {
return (
((BB_RANK_1 | BB_RANK_8) & ~BB_RANKS[squareRank(square)]) |
((BB_FILE_A | BB_FILE_H) & ~BB_FILES[squareFile(square)])
)
}
export function* _carryRippler(mask: Bitboard): IterableIterator<Bitboard> {
// # Carry-Rippler trick to iterate subsets of mask.
let subset = BB_EMPTY
while (true) {
yield subset
subset = (subset - mask) & mask
if (!subset) {
break
}
}
}
export const _attackTable = (
deltas: number[],
): [Bitboard[], Map<Bitboard, Bitboard>[]] => {
const maskTable: Bitboard[] = []
const attackTable: Map<Bitboard, Bitboard>[] = []
for (const square of SQUARES) {
const attacks = new Map<Bitboard, Bitboard>()
const mask =
_slidingAttacks(square, 0n as Bitboard, deltas) & ~_edges(square)
for (const subset of _carryRippler(mask)) {
attacks.set(subset, _slidingAttacks(square, subset, deltas))
}
attackTable.push(attacks)
maskTable.push(mask)
}
return [maskTable, attackTable]
}
export const [BB_DIAG_MASKS, BB_DIAG_ATTACKS] = _attackTable([-9, -7, 7, 9])
export const [BB_FILE_MASKS, BB_FILE_ATTACKS] = _attackTable([-8, 8])
export const [BB_RANK_MASKS, BB_RANK_ATTACKS] = _attackTable([-1, 1])
export const _rays = (): Bitboard[][] => {
let rays: Bitboard[][] = []
BB_SQUARES.forEach((bbA, a) => {
let raysRow: Bitboard[] = []
BB_SQUARES.forEach((bbB, b) => {
if ((BB_DIAG_ATTACKS[a].get(0n) as Bitboard) & bbB) {
raysRow.push(
((BB_DIAG_ATTACKS[a].get(0n) as Bitboard) &
(BB_DIAG_ATTACKS[b].get(0n) as Bitboard)) |
bbA |
bbB,
)
} else if ((BB_RANK_ATTACKS[a].get(0n) as Bitboard) & bbB) {
raysRow.push((BB_RANK_ATTACKS[a].get(0n) as Bitboard) | bbA)
} else if ((BB_FILE_ATTACKS[a].get(0n) as Bitboard) & bbB) {
raysRow.push((BB_FILE_ATTACKS[a].get(0n) as Bitboard) | bbA)
} else {
raysRow.push(BB_EMPTY)
}
})
rays.push(raysRow)
})
return rays
}
export const BB_RAYS = _rays()
export const ray = (a: Square, b: Square): Bitboard => {
return BB_RAYS[a][b]
}
export const between = (a: Square, b: Square): Bitboard => {
const bb = BB_RAYS[a][b] & ((BB_ALL << BigInt(a)) ^ (BB_ALL << BigInt(b)))
return bb & (bb - 1n)
}
export const SAN_REGEX =
/^([NBKRQ])?([a-h])?([1-8])?[\\-x]?([a-h][1-8])(=?[nbrqkNBRQK])?[\\+#]?$/
export const FEN_CASTLING_REGEX = /^(?:-|[KQABCDEFGH]{0,2}[kqabcdefgh]{0,2})$/
/**
* A piece with type and color.
*/
export class Piece {
/** The piece type. */
pieceType: PieceType
/** The piece color. */
color: Color
constructor(pieceType: PieceType, color: Color) {
this.pieceType = pieceType
this.color = color
}
/**
* Gets the symbol ``P``, ``N``, ``B``, ``R``, ``Q`` or ``K`` for white
* pieces or the lower-case variants for the black pieces.
*/
symbol(): string {
const symbol = pieceSymbol(this.pieceType)
return this.color ? symbol.toUpperCase() : symbol
}
/**
* Gets the Unicode character for the piece.
*/
unicodeSymbol(
{ invertColor }: { invertColor: boolean } = { invertColor: false },
): string {
const swapcase = (symbol: string) =>
symbol === symbol.toUpperCase()
? symbol.toLowerCase()
: symbol.toUpperCase()
const symbol = invertColor ? swapcase(this.symbol()) : this.symbol()
return UNICODE_PIECE_SYMBOLS[symbol]
}
hash(): number {
return this.pieceType + (this.color ? -1 : 5)
}
toString(): string {
return this.symbol()
}
toRepr(): string {
return `Piece.fromSymbol(${this.symbol()})`
}
_reprSvg_(): string {
// todo
throw new Error('Not implemented')
}
static fromSymbol(symbol: string): Piece {
return new Piece(
PIECE_SYMBOLS.indexOf(symbol.toLowerCase()),
symbol === symbol.toUpperCase(),
)
}
}
/**
* Represents a move from a square to a square and possibly the promotion
* piece type.
*
* Drops and null moves are supported.
*/
export class Move {
/** The source square. */
fromSquare: Square
/** The target square. */
toSquare: Square
/** The promotion piece type or ``null``. */
promotion: PieceType | null
/** The drop piece type or ``null``. */
drop: PieceType | null
constructor(
fromSquare: Square,
toSquare: Square,
{
promotion = null,
drop = null,
}: { promotion?: PieceType | null; drop?: PieceType | null } = {},
) {
this.fromSquare = fromSquare
this.toSquare = toSquare
this.promotion = promotion
this.drop = drop
}
/**
* Gets a 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``.
*/
uci(): string {
if (this.drop) {
return (
pieceSymbol(this.drop).toUpperCase() + '@' + SQUARE_NAMES[this.toSquare]
)
} else if (this.promotion) {
return (
SQUARE_NAMES[this.fromSquare] +
SQUARE_NAMES[this.toSquare] +
pieceSymbol(this.promotion)
)
} else if (this.bool()) {
return SQUARE_NAMES[this.fromSquare] + SQUARE_NAMES[this.toSquare]
} else {
return '0000'
}
}
xboard(): string {
return this.bool() ? this.uci() : '@@@@'
}
bool(): boolean {
return bool(
this.fromSquare ||
this.toSquare ||
this.promotion !== null ||
this.drop !== null,
)
}
toRepr(): string {
return `Move.fromUci(${this.uci()})`
}
toString(): string {
return this.uci()
}
copy(): Move {
// NOTE: No python-chess mirror, included for convenience
return new Move(
this.fromSquare,
this.toSquare,
{
promotion: this.promotion,
drop: this.drop,
}
)
}
equals(other: any): boolean {
// NOTE: No python-chess mirror, included for convenience
return (
other instanceof Move &&
this.fromSquare === other.fromSquare &&
this.toSquare === other.toSquare &&
this.promotion === other.promotion &&
this.drop === other.drop
)
}
static equals(a: Move, b: Move): boolean {
return a.equals(b)
}
/**
* Parses a UCI string.
*
* @thrwos :exc:`InvalidMoveError` if the UCI string is invalid.
*/
static fromUci(uci: string): Move {
if (uci === '0000') {
return Move.null()
} else if (uci.length === 4 && '@' === uci[1]) {
const drop = PIECE_SYMBOLS.indexOf(uci[0].toLowerCase()) as PieceType | -1
const square = SQUARE_NAMES.indexOf(uci.slice(2)) as Square | -1
if (drop === -1 || square === -1) {
throw new InvalidMoveError(`invalid uci: ${uci}`)
}
return new Move(square, square, { drop })
} else if (4 <= uci.length && uci.length <= 5) {
const fromSquare = SQUARE_NAMES.indexOf(uci.slice(0, 2))
const toSquare = SQUARE_NAMES.indexOf(uci.slice(2, 4))
const promotion =
uci.length === 5
? (PIECE_SYMBOLS.indexOf(uci[4]) as PieceType | -1)
: null
if (fromSquare === -1 || toSquare === -1 || promotion === -1) {
throw new InvalidMoveError(`invalid uci: {$uci}`)
}
if (fromSquare === toSquare) {
throw new InvalidMoveError(
`invalid uci (use 0000 for null moves): ${uci}`,
)
}
return new Move(fromSquare, toSquare, { promotion })
} else {
throw new InvalidMoveError(
`expected uci string to be of length 4 or 5: ${uci}`,
)
}
}
/**
* 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
*/
static null(): Move {
return new Move(0, 0)
}
}
/**
* 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 *boardFen* argument. If *boardFen*
* is ``null``, an empty board is created.
*/
export class BaseBoard {
occupied: Bitboard
occupiedCo: [Bitboard, Bitboard]
pawns: Bitboard
knights: Bitboard
bishops: Bitboard
rooks: Bitboard
queens: Bitboard
kings: Bitboard
promoted: Bitboard
constructor(boardFen: string | null = null) {
this.occupiedCo = [BB_EMPTY, BB_EMPTY]
// NOTE: We have to initialize these to avoid TS errors.
// The calls below will set them to the correct values.
this.occupied = null!
this.pawns = null!
this.knights = null!
this.bishops = null!
this.rooks = null!
this.queens = null!
this.kings = null!
this.promoted = null!
if (boardFen === null) {
this._clearBoard()
} else if (boardFen === STARTING_BOARD_FEN) {
this._resetBoard()
} else {
this._setBoardFen(boardFen)
}
}
_resetBoard(): void {
this.pawns = BB_RANK_2 | BB_RANK_7
this.knights = BB_B1 | BB_G1 | BB_B8 | BB_G8
this.bishops = BB_C1 | BB_F1 | BB_C8 | BB_F8
this.rooks = BB_CORNERS
this.queens = BB_D1 | BB_D8
this.kings = BB_E1 | BB_E8
this.promoted = BB_EMPTY
this.occupiedCo[colorIdx(WHITE)] = BB_RANK_1 | BB_RANK_2
this.occupiedCo[colorIdx(BLACK)] = BB_RANK_7 | BB_RANK_8
this.occupied = BB_RANK_1 | BB_RANK_2 | BB_RANK_7 | BB_RANK_8
}
/**
* Resets pieces to the starting position.
*
* :class:`~chess.Board` also resets the move stack, but not turn,
* castling rights and move counters. Use :func:`chess.Board.reset()` to
* fully restore the starting position.
*/
resetBoard(): void {
this._resetBoard()
}
_clearBoard(): void {
this.pawns = BB_EMPTY
this.knights = BB_EMPTY
this.bishops = BB_EMPTY
this.rooks = BB_EMPTY
this.queens = BB_EMPTY
this.kings = BB_EMPTY
this.promoted = BB_EMPTY
this.occupiedCo[colorIdx(WHITE)] = BB_EMPTY
this.occupiedCo[colorIdx(BLACK)] = BB_EMPTY
this.occupied = BB_EMPTY
}
/**
* Clears the board.
*
* :class:`~chess.Board` also clears the move stack.
*/
clearBoard(): void {
this._clearBoard()
}
piecesMask(pieceType: PieceType, color: Color): Bitboard {
let bb: Bitboard
if (pieceType === PAWN) {
bb = this.pawns
} else if (pieceType === KNIGHT) {
bb = this.knights
} else if (pieceType === BISHOP) {
bb = this.bishops
} else if (pieceType === ROOK) {
bb = this.rooks
} else if (pieceType === QUEEN) {
bb = this.queens
} else if (pieceType === KING) {
bb = this.kings
} else {
throw new Error(`expected PieceType, got ${pieceType}`)