-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChessEngine.py
More file actions
1957 lines (1698 loc) · 73.1 KB
/
Copy pathChessEngine.py
File metadata and controls
1957 lines (1698 loc) · 73.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Rules and state management for the chess engine.
"""
# ChessEngine.py
from ChessAI import ZOBRIST_PIECE, ZOBRIST_SIDE, ZOBRIST_CASTLING, ZOBRIST_ENPASSANT, piece_score, piece_position_scores, scoreBoard
try:
import cengine as _ce
except Exception:
_ce = None
def _has_native(*names: str) -> bool:
return _ce is not None and all(hasattr(_ce, name) for name in names)
_HAVE_NATIVE_ATTACKS = _has_native("_is_square_attacked_bb", "_compute_attacked_mask")
_HAVE_NATIVE_PINS = _has_native("_check_pins_and_checks")
_HAVE_NATIVE_KNIGHT_STEPS = _has_native("_gen_knight_steps")
_HAVE_NATIVE_KING_STEPS = _has_native("_gen_king_steps")
_HAVE_NATIVE_PAWN_STEPS = _has_native("_gen_pawn_steps_from")
_HAVE_NATIVE_ROOK_STEPS = _has_native("_gen_rook_steps_from")
_HAVE_NATIVE_BISHOP_STEPS = _has_native("_gen_bishop_steps_from")
_HAVE_NATIVE_QUEEN_STEPS = _has_native("_gen_queen_steps_from")
# --- Precomputed attack masks (bitboards) for knights and kings ---
def _precompute_attack_masks():
KNIGHT_DELTAS = ((-2,-1),(-2,1),(-1,-2),(-1,2),(1,-2),(1,2),(2,-1),(2,1))
KING_DELTAS = ((-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1))
knight_masks = [0] * 64
king_masks = [0] * 64
for sq in range(64):
r, c = divmod(sq, 8)
m = 0
for dr, dc in KNIGHT_DELTAS:
rr, cc = r + dr, c + dc
if 0 <= rr < 8 and 0 <= cc < 8:
m |= 1 << (rr*8 + cc)
knight_masks[sq] = m
m = 0
for dr, dc in KING_DELTAS:
rr, cc = r + dr, c + dc
if 0 <= rr < 8 and 0 <= cc < 8:
m |= 1 << (rr*8 + cc)
king_masks[sq] = m
return tuple(knight_masks), tuple(king_masks)
KNIGHT_ATTACKS, KING_ATTACKS = _precompute_attack_masks()
# Hoisted direction constants for reuse (avoid re-allocations in hot paths)
DELTAS_KNIGHT = ((-2,-1),(-2,1),(-1,-2),(-1,2),(1,-2),(1,2),(2,-1),(2,1))
DELTAS_KING = ((-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1))
DIRS_BISHOP = ((-1,-1),(-1,1),(1,-1),(1,1))
DIRS_ROOK = ((-1,0),(1,0),(0,-1),(0,1))
NOT_FILE_A = 0xFEFEFEFEFEFEFEFE # clear file A (bits 0 of each byte)
NOT_FILE_H = 0x7F7F7F7F7F7F7F7F # clear file H (bits 7 of each byte)
class GameState:
def __init__(self):
"""
Board is an 8x8 2d list, each element in list has 2 characters.
The first character represents the color of the piece: 'b' or 'w'.
The second character represents the type of the piece: 'R', 'N', 'B', 'Q', 'K' or 'p'.
"--" represents an empty space with no piece.
"""
self.board = [
["bR", "bN", "bB", "bQ", "bK", "bB", "bN", "bR"],
["bp", "bp", "bp", "bp", "bp", "bp", "bp", "bp"],
["--", "--", "--", "--", "--", "--", "--", "--"],
["--", "--", "--", "--", "--", "--", "--", "--"],
["--", "--", "--", "--", "--", "--", "--", "--"],
["--", "--", "--", "--", "--", "--", "--", "--"],
["wp", "wp", "wp", "wp", "wp", "wp", "wp", "wp"],
["wR", "wN", "wB", "wQ", "wK", "wB", "wN", "wR"]]
# self.board = [
# ["--", "--", "--", "--", "--", "--", "--", "--"],
# ["--", "--", "--", "--", "--", "--", "--", "--"],
# ["--", "--", "--", "--", "--", "--", "--", "--"],
# ["--", "--", "--", "--", "--", "--", "--", "--"],
# ["--", "--", "--", "--", "--", "--", "--", "--"],
# ["--", "--", "--", "--", "--", "--", "--", "--"],
# ["--", "--", "--", "--", "--", "--", "--", "--"],
# ["--", "--", "--", "--", "--", "--", "--", "--"]
# ]
self.moveFunctions = {"p": self.getPawnMoves, "R": self.getRookMoves, "B": self.getBishopMoves, "Q": self.getQueenMoves}
self.white_to_move = True
# Map each piece‐code to its own 64-bit bitboard:
self.bitboards = {
'wp': 0, 'wN': 0, 'wB': 0, 'wR': 0, 'wQ': 0, 'wK': 0,
'bp': 0, 'bN': 0, 'bB': 0, 'bR': 0, 'bQ': 0, 'bK': 0,
}
# Occupancy bitboards:
self.occ_white = 0
self.occ_black = 0
self.occ_all = 0
# Initialize from self.board and detect king squares:
self.white_king_location = None
self.black_king_location = None
for r in range(8):
for c in range(8):
p = self.board[r][c]
if p != '--':
sq = r*8 + c
self.bitboards[p] |= (1 << sq)
if p == 'wK':
self.white_king_location = (r, c)
elif p == 'bK':
self.black_king_location = (r, c)
# Fallback to start squares if not found (e.g., custom boards still at start):
if self.white_king_location is None:
self.white_king_location = (7, 4)
if self.black_king_location is None:
self.black_king_location = (0, 4)
self._recalc_occupancies()
self.current_castling_rights = self._derive_castling_rights_from_board()
self.castle_rights_log = [CastleRights(
self.current_castling_rights.wks,
self.current_castling_rights.wqs,
self.current_castling_rights.bks,
self.current_castling_rights.bqs
)]
self.enpassant_possible = () # (row, col) square where EP capture is possible; empty tuple = none
self.enpassant_possible_log = [self.enpassant_possible]
self.zobrist_key = self._compute_zobrist() # Zobrist key for the current position
self.current_eval = self._compute_full_eval() # Current evaluation of the position
self.move_log = [] # list keeping track of all the moves made in the game
self.checkmate = False # No valid moves + check
self.stalemate = False # No valid moves + no check
self.in_check = False
self.pins = []
self.checks = []
self.pinned_map = {}
# Half-move clock for 50-move rule (reset on pawn move or capture)
self.halfmove_clock = 0
self.halfmove_clock_log = [0]
# Position history for repetition detection: maps a simple position key → count
self.position_history = {}
# Record the initial position
self._update_position_history()
def _hydrate_move_fields(self, move):
# Ensure piece_moved / piece_captured are populated from the current board
if getattr(move, "piece_moved", "--") == "--":
move.piece_moved = self.board[move.start_row][move.start_col]
if getattr(move, "is_enpassant_move", False):
# EP capture sits one rank behind the target
cap_row = move.end_row + (1 if move.piece_moved[0] == "w" else -1)
move.piece_captured = self.board[cap_row][move.end_col]
else:
if getattr(move, "piece_captured", "--") == "--":
move.piece_captured = self.board[move.end_row][move.end_col]
def _bb_args(self): # Helper
bb = self.bitboards
return (
bb['wp'], bb['wN'], bb['wB'], bb['wR'], bb['wQ'], bb['wK'],
bb['bp'], bb['bN'], bb['bB'], bb['bR'], bb['bQ'], bb['bK'],
)
def _derive_castling_rights_from_board(self): # Stays Python Only
cr = CastleRights(False, False, False, False)
b = self.board
cr.wks = (b[7][4] == 'wK' and b[7][7] == 'wR')
cr.wqs = (b[7][4] == 'wK' and b[7][0] == 'wR')
cr.bks = (b[0][4] == 'bK' and b[0][7] == 'bR')
cr.bqs = (b[0][4] == 'bK' and b[0][0] == 'bR')
return cr
def _python_check_pins_and_checks(self):
"""Pure-Python pin/check detector used when the native helper is unavailable."""
pins = []
checks = []
in_check = False
if self.white_to_move:
enemy_color = 'b'
ally_color = 'w'
start_row, start_col = self.white_king_location
else:
enemy_color = 'w'
ally_color = 'b'
start_row, start_col = self.black_king_location
directions = ((-1, 0), (0, -1), (1, 0), (0, 1), (-1, -1), (-1, 1), (1, -1), (1, 1))
for j, (dr, dc) in enumerate(directions):
possible_pin = ()
r = start_row + dr
c = start_col + dc
while 0 <= r < 8 and 0 <= c < 8:
end_piece = self.board[r][c]
if end_piece[0] == ally_color and end_piece[1] != 'K':
if not possible_pin:
possible_pin = (r, c, dr, dc)
else:
break
elif end_piece[0] == enemy_color:
piece_type = end_piece[1]
orth = 0 <= j <= 3 and piece_type in ('R', 'Q')
diag = 4 <= j <= 7 and piece_type in ('B', 'Q')
pawn = (
piece_type == 'p'
and (
(enemy_color == 'w' and j in (6, 7))
or (enemy_color == 'b' and j in (4, 5))
)
)
king = piece_type == 'K' and max(abs(r - start_row), abs(c - start_col)) == 1
if orth or diag or pawn or king:
if not possible_pin:
in_check = True
checks.append((r, c, dr, dc))
else:
pins.append(possible_pin)
break
break
r += dr
c += dc
knight_moves = ((-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1))
for dr, dc in knight_moves:
r = start_row + dr
c = start_col + dc
if 0 <= r < 8 and 0 <= c < 8:
end_piece = self.board[r][c]
if end_piece[0] == enemy_color and end_piece[1] == 'N':
in_check = True
checks.append((r, c, dr, dc))
return in_check, pins, checks
def _gen_knight_moves_py(self, moves):
wtm = self.white_to_move
board = self.board
knights = self.bitboards['wN' if wtm else 'bN']
us_occ = self.occ_white if wtm else self.occ_black
pinned = self._pinned_knights_mask()
while knights:
lsb = knights & -knights
from_sq = lsb.bit_length() - 1
knights ^= lsb
if (pinned >> from_sq) & 1:
continue
targets = KNIGHT_ATTACKS[from_sq] & ~us_occ
while targets:
to_lsb = targets & -targets
to_sq = to_lsb.bit_length() - 1
targets ^= to_lsb
r0, c0 = divmod(from_sq, 8)
r1, c1 = divmod(to_sq, 8)
moves.append(Move((r0, c0), (r1, c1), board))
def _gen_king_moves_py(self, moves, opp_attacks=None):
wtm = self.white_to_move
board = self.board
king_bb = self.bitboards['wK' if wtm else 'bK']
us_occ = self.occ_white if wtm else self.occ_black
if not king_bb:
return
from_sq = (king_bb & -king_bb).bit_length() - 1
targets = KING_ATTACKS[from_sq] & ~us_occ
if opp_attacks is not None:
targets &= ~int(opp_attacks)
while targets:
to_lsb = targets & -targets
to_sq = to_lsb.bit_length() - 1
targets ^= to_lsb
r0, c0 = divmod(from_sq, 8)
r1, c1 = divmod(to_sq, 8)
moves.append(Move((r0, c0), (r1, c1), board))
def _gen_pawn_moves_py(self, row, col, moves):
board = self.board
wtm = self.white_to_move
move_amount = -1 if wtm else 1
start_row = 6 if wtm else 1
enemy_color = 'b' if wtm else 'w'
promo_row = 0 if wtm else 7
pin = self.pinned_map.get((row, col))
piece_pinned = pin is not None
pin_dr, pin_dc = pin if pin else (0, 0)
one_step_row = row + move_amount
if 0 <= one_step_row < 8:
if board[one_step_row][col] == '--' and ((not piece_pinned) or (pin_dr, pin_dc) == (move_amount, 0)):
if one_step_row == promo_row:
for ch in ('Q', 'R', 'B', 'N'):
moves.append(Move((row, col), (one_step_row, col), board, promotion_choice=ch))
else:
moves.append(Move((row, col), (one_step_row, col), board))
two_step_row = row + 2 * move_amount
if row == start_row and board[two_step_row][col] == '--':
moves.append(Move((row, col), (two_step_row, col), board))
for dc in (-1, 1):
end_col = col + dc
end_row = row + move_amount
if not (0 <= end_col < 8 and 0 <= end_row < 8):
continue
if piece_pinned and (pin_dr, pin_dc) != (move_amount, dc):
continue
target = board[end_row][end_col]
if target != '--' and target[0] == enemy_color:
if end_row == promo_row:
for ch in ('Q', 'R', 'B', 'N'):
moves.append(Move((row, col), (end_row, end_col), board, promotion_choice=ch))
else:
moves.append(Move((row, col), (end_row, end_col), board))
def is_square_attacked_bb(self, sq, by_white: bool) -> bool: # C++
"""True if square index `sq` is attacked by side `by_white` on the *current* board."""
# Try native first (cached if you've imported cengine as _ce at module top)
if _HAVE_NATIVE_ATTACKS:
return bool(_ce._is_square_attacked_bb(int(sq), bool(by_white), *map(int, self._bb_args())))
# --- Python fallback (your current implementation) ---
one = 1 << sq
# Rebuild occupancies from piece bitboards (avoids any stale occ_* issues)
bb = self.bitboards
occ_w = (bb['wp'] | bb['wN'] | bb['wB'] | bb['wR'] | bb['wQ'] | bb['wK'])
occ_b = (bb['bp'] | bb['bN'] | bb['bB'] | bb['bR'] | bb['bQ'] | bb['bK'])
occ_all = occ_w | occ_b
wN, bN = bb['wN'], bb['bN']
wK, bK = bb['wK'], bb['bK']
wR, bR = bb['wR'], bb['bR']
wB, bB = bb['wB'], bb['bB']
wQ, bQ = bb['wQ'], bb['bQ']
wp, bp = bb['wp'], bb['bp']
# Knights
if KNIGHT_ATTACKS[sq] & (wN if by_white else bN):
return True
# Kings
if KING_ATTACKS[sq] & (wK if by_white else bK):
return True
# Pawns (with sq = r*8+c, r=0 at top; white attacks "up" → right shifts)
if by_white:
wp = bb['wp']
# White attacks: up-right (−7) and up-left (−9)
if (((wp & NOT_FILE_H) >> 7) & one):
return True
if (((wp & NOT_FILE_A) >> 9) & one):
return True
else:
bp = bb['bp']
# Black attacks: down-left (+7) and down-right (+9)
if (((bp & NOT_FILE_A) << 7) & one):
return True
if (((bp & NOT_FILE_H) << 9) & one):
return True
# Slider helpers
rook_like = (wR | wQ) if by_white else (bR | bQ)
bishop_like = (wB | wQ) if by_white else (bB | bQ)
r = sq >> 3
c = sq & 7
# ---- Rooks/Queens (orthogonals) ----
# North
rr = r - 1
while rr >= 0:
s = (rr << 3) | c
bbm = 1 << s
if occ_all & bbm:
pc_is_white = bool(occ_w & bbm)
if pc_is_white == by_white and (rook_like & bbm):
return True
break
rr -= 1
# South
rr = r + 1
while rr < 8:
s = (rr << 3) | c
bbm = 1 << s
if occ_all & bbm:
pc_is_white = bool(occ_w & bbm)
if pc_is_white == by_white and (rook_like & bbm):
return True
break
rr += 1
# West
cc = c - 1
while cc >= 0:
s = (r << 3) | cc
bbm = 1 << s
if occ_all & bbm:
pc_is_white = bool(occ_w & bbm)
if pc_is_white == by_white and (rook_like & bbm):
return True
break
cc -= 1
# East
cc = c + 1
while cc < 8:
s = (r << 3) | cc
bbm = 1 << s
if occ_all & bbm:
pc_is_white = bool(occ_w & bbm)
if pc_is_white == by_white and (rook_like & bbm):
return True
break
cc += 1
# ---- Bishops/Queens (diagonals) ----
# NW
rr, cc = r - 1, c - 1
while rr >= 0 and cc >= 0:
s = (rr << 3) | cc
bbm = 1 << s
if occ_all & bbm:
pc_is_white = bool(occ_w & bbm)
if pc_is_white == by_white and (bishop_like & bbm):
return True
break
rr -= 1; cc -= 1
# NE
rr, cc = r - 1, c + 1
while rr >= 0 and cc < 8:
s = (rr << 3) | cc
bbm = 1 << s
if occ_all & bbm:
pc_is_white = bool(occ_w & bbm)
if pc_is_white == by_white and (bishop_like & bbm):
return True
break
rr -= 1; cc += 1
# SW
rr, cc = r + 1, c - 1
while rr < 8 and cc >= 0:
s = (rr << 3) | cc
bbm = 1 << s
if occ_all & bbm:
pc_is_white = bool(occ_w & bbm)
if pc_is_white == by_white and (bishop_like & bbm):
return True
break
rr += 1; cc -= 1
# SE
rr, cc = r + 1, c + 1
while rr < 8 and cc < 8:
s = (rr << 3) | cc
bbm = 1 << s
if occ_all & bbm:
pc_is_white = bool(occ_w & bbm)
if pc_is_white == by_white and (bishop_like & bbm):
return True
break
rr += 1; cc += 1
return False
def compute_attacked_mask(self, by_white: bool) -> int: # C++
"""
Bitboard of all squares attacked by the given side (ignores pins & legality;
includes blockers on slider rays). Cheap to compute and reuse.
"""
if _HAVE_NATIVE_ATTACKS:
return int(_ce._compute_attacked_mask(bool(by_white), *map(int, self._bb_args())))
# --- Python fallback (your current implementation) ---
bb = self.bitboards
occ_w = (bb['wp'] | bb['wN'] | bb['wB'] | bb['wR'] | bb['wQ'] | bb['wK'])
occ_b = (bb['bp'] | bb['bN'] | bb['bB'] | bb['bR'] | bb['bQ'] | bb['bK'])
occ_all = occ_w | occ_b
attack = 0
# Knights
kn = bb['wN'] if by_white else bb['bN']
t = kn
while t:
lsb = t & -t
sq = lsb.bit_length() - 1
attack |= KNIGHT_ATTACKS[sq]
t ^= lsb
# King
kbb = bb['wK'] if by_white else bb['bK']
if kbb:
ksq = (kbb & -kbb).bit_length() - 1
attack |= KING_ATTACKS[ksq]
# Pawns
if by_white:
wp = bb['wp']
attack |= ((wp & NOT_FILE_H) >> 7) # up-right
attack |= ((wp & NOT_FILE_A) >> 9) # up-left
else:
bp = bb['bp']
attack |= ((bp & NOT_FILE_A) << 7) # down-left
attack |= ((bp & NOT_FILE_H) << 9) # down-right
# Sliders
# Rook-like
rook_like = (bb['wR'] | bb['wQ']) if by_white else (bb['bR'] | bb['bQ'])
t = rook_like
while t:
lsb = t & -t
sq = lsb.bit_length() - 1
r, c = divmod(sq, 8)
# North
rr = r - 1
while rr >= 0:
s = (rr << 3) | c
attack |= (1 << s)
if (occ_all >> s) & 1:
break
rr -= 1
# South
rr = r + 1
while rr < 8:
s = (rr << 3) | c
attack |= (1 << s)
if (occ_all >> s) & 1:
break
rr += 1
# West
cc = c - 1
while cc >= 0:
s = (r << 3) | cc
attack |= (1 << s)
if (occ_all >> s) & 1:
break
cc -= 1
# East
cc = c + 1
while cc < 8:
s = (r << 3) | cc
attack |= (1 << s)
if (occ_all >> s) & 1:
break
cc += 1
t ^= lsb
# Bishop-like
bishop_like = (bb['wB'] | bb['wQ']) if by_white else (bb['bB'] | bb['bQ'])
t = bishop_like
while t:
lsb = t & -t
sq = lsb.bit_length() - 1
r, c = divmod(sq, 8)
# NW
rr, cc = r - 1, c - 1
while rr >= 0 and cc >= 0:
s = (rr << 3) | cc
attack |= (1 << s)
if (occ_all >> s) & 1:
break
rr -= 1; cc -= 1
# NE
rr, cc = r - 1, c + 1
while rr >= 0 and cc < 8:
s = (rr << 3) | cc
attack |= (1 << s)
if (occ_all >> s) & 1:
break
rr -= 1; cc += 1
# SW
rr, cc = r + 1, c - 1
while rr < 8 and cc >= 0:
s = (rr << 3) | cc
attack |= (1 << s)
if (occ_all >> s) & 1:
break
rr += 1; cc -= 1
# SE
rr, cc = r + 1, c + 1
while rr < 8 and cc < 8:
s = (rr << 3) | cc
attack |= (1 << s)
if (occ_all >> s) & 1:
break
rr += 1; cc += 1
t ^= lsb
return attack
def _ep_is_legal(self, row, col, r1, c): # Stays Python Only
"""Return True if EP (row,col)->(r1,c) keeps our king safe."""
assert self.enpassant_possible == (r1, c), "EP target mismatch"
wtm = self.white_to_move
mover = 'wp' if wtm else 'bp'
victim = 'bp' if wtm else 'wp'
from_sq = row*8 + col
to_sq = r1*8 + c
cap_sq = row*8 + c # victim stands on mover's start rank, target file
# Ensure a victim pawn actually exists on the capture square
if ((self.bitboards[victim] >> cap_sq) & 1) == 0:
return False
m_from, m_to, m_cap = (1<<from_sq), (1<<to_sq), (1<<cap_sq)
# snapshot
bb_mover, bb_victim = self.bitboards[mover], self.bitboards[victim]
ow, ob, oa = self.occ_white, self.occ_black, self.occ_all
# apply EP effect on bitboards/occupancy
self.bitboards[mover] ^= (m_from | m_to)
self.bitboards[victim] ^= m_cap
if wtm:
self.occ_white ^= (m_from | m_to)
self.occ_black ^= m_cap
else:
self.occ_black ^= (m_from | m_to)
self.occ_white ^= m_cap
self.occ_all = self.occ_white | self.occ_black
# king square (unchanged)
kr, kc = (self.white_king_location if wtm else self.black_king_location)
illegal = self.is_square_attacked_bb(kr*8 + kc, by_white=not wtm)
# restore
self.bitboards[mover], self.bitboards[victim] = bb_mover, bb_victim
self.occ_white, self.occ_black, self.occ_all = ow, ob, oa
return not illegal
def _ep_capturable_given_side(self, ep_square, white_to_move): # Stays Python Only
"""Return True if side-to-move (given) has a pawn that could capture on ep_square."""
if not ep_square:
return False
r, c = ep_square # target square of the EP capture
if white_to_move:
# White would capture from r+1,c-1 or r+1,c+1
from_r = r + 1
if not (0 <= from_r < 8):
return False
mask = 0
if c > 0: mask |= 1 << (from_r*8 + (c-1))
if c < 7: mask |= 1 << (from_r*8 + (c+1))
return bool(self.bitboards['wp'] & mask)
else:
# Black would capture from r-1,c-1 or r-1,c+1
from_r = r - 1
if not (0 <= from_r < 8):
return False
mask = 0
if c > 0: mask |= 1 << (from_r*8 + (c-1))
if c < 7: mask |= 1 << (from_r*8 + (c+1))
return bool(self.bitboards['bp'] & mask)
def _pinned_knights_mask(self) -> int: # Helper
"""Bitboard of our KNIGHTS that are line-pinned (from self.pinned_map)."""
wtm = self.white_to_move
mask = 0
for (r, c), _ray in self.pinned_map.items():
sq = r * 8 + c
p = self.board[r][c]
if p != "--" and p[1] == "N" and ((p[0] == 'w') == wtm):
mask |= (1 << sq)
return mask
def gen_knight_moves_bb(self, moves):
if not _HAVE_NATIVE_KNIGHT_STEPS:
self._gen_knight_moves_py(moves)
return
wtm = self.white_to_move
us_occ = self.occ_white if wtm else self.occ_black
knights = self.bitboards['wN' if wtm else 'bN']
if not knights:
return
pinned = self._pinned_knights_mask()
steps = _ce._gen_knight_steps(int(knights), int(us_occ), int(pinned))
board = self.board
append = moves.append
for s in steps:
fr = (s >> 6) & 63
to = s & 63
r0, c0 = divmod(fr, 8)
r1, c1 = divmod(to, 8)
append(Move((r0, c0), (r1, c1), board))
def gen_king_moves_bb(self, moves, opp_attacks=None):
if not _HAVE_NATIVE_KING_STEPS:
self._gen_king_moves_py(moves, opp_attacks=opp_attacks)
return
wtm = self.white_to_move
us_occ = self.occ_white if wtm else self.occ_black
king_bb = self.bitboards['wK' if wtm else 'bK']
if not king_bb:
return
use_mask = opp_attacks is not None
mask = int(opp_attacks) if use_mask else 0
steps = _ce._gen_king_steps(int(king_bb), int(us_occ), mask, bool(use_mask))
board = self.board
append = moves.append
for s in steps:
fr = (s >> 6) & 63
to = s & 63
r0, c0 = divmod(fr, 8)
r1, c1 = divmod(to, 8)
append(Move((r0, c0), (r1, c1), board))
def _recalc_occupancies(self): # Stays Python Only
self.occ_white = (
self.bitboards['wp'] | self.bitboards['wN'] | self.bitboards['wB'] |
self.bitboards['wR'] | self.bitboards['wQ'] | self.bitboards['wK']
)
self.occ_black = (
self.bitboards['bp'] | self.bitboards['bN'] | self.bitboards['bB'] |
self.bitboards['bR'] | self.bitboards['bQ'] | self.bitboards['bK']
)
self.occ_all = self.occ_white | self.occ_black
def _compute_full_eval(self): # Stays Python Only
"""Scan board once to get material + PST total (white-positive)."""
ps, pps = piece_score, piece_position_scores
board = self.board
s = 0.0
for r in range(8):
row = board[r]
for c in range(8):
sq = row[c]
if sq != "--":
v = ps[sq[1]] + pps[sq][r][c]
s += v if sq[0] == 'w' else -v
return s
def _canonicalize_move_codes(self, move):
"""Ensure move.piece_moved / piece_captured are concrete like 'wN', 'bp'."""
sr, sc, er, ec = move.start_row, move.start_col, move.end_row, move.end_col
from_sq = sr * 8 + sc
mask = 1 << from_sq
# ---- piece_moved ----
pm = getattr(move, "piece_moved", None)
if not pm or pm == "--":
side = (move.piece_moved[0]
if move.piece_moved and move.piece_moved != "--"
else ('w' if self.white_to_move else 'b'))
# Prefer bitboards – reliable even if board was mutated earlier
for code in (side + 'p', side + 'N', side + 'B', side + 'R', side + 'Q', side + 'K'):
if self.bitboards[code] & mask:
pm = code
break
if not pm or pm == "--":
# Last resort: current board snapshot
pm = self.board[sr][sc]
# If promotion move called late, infer the pawn color
if (not pm or pm == "--") and getattr(move, "is_pawn_promotion", False):
pm = side + 'p'
move.piece_moved = pm
# ---- piece_captured ----
pc = getattr(move, "piece_captured", None)
if getattr(move, "is_enpassant_move", False):
pc = ('b' if pm[0] == 'w' else 'w') + 'p'
else:
if not pc or pc == "--":
pc = self.board[er][ec] or "--"
move.piece_captured = pc
def _calc_move_delta(self, move): # Stays Python only
"""
Incremental eval change (material + PST).
Positive = White gain; Negative = Black gain.
Handles promotions, normal & EP captures, and rook PST during castling.
"""
# Hydrate if needed; but we'll repair fields if board already mutated
self._hydrate_move_fields(move)
ps, pps = piece_score, piece_position_scores
sr, sc, er, ec = move.start_row, move.start_col, move.end_row, move.end_col
pm = move.piece_moved # e.g. 'wN', 'bp'
# If called after board mutation, start square may be empty → pm == "--".
if pm == "--" or pm is None or pm not in pps:
post = self.board[er][ec]
if move.is_pawn_promotion:
# Mover was a pawn of the color now on the end square
color = post[0] if post != "--" else ('b' if self.white_to_move else 'w')
pm = color + 'p'
else:
pm = post # moved piece now sits on end square
# If still unknown, give up gracefully (shouldn't happen if moves are legal)
if not pm or pm == "--":
return 0.0
color_mult = 1 if pm[0] == 'w' else -1
# 1) remove mover's old term (material+PST at the START square)
start_key = pm if not move.is_pawn_promotion else (pm[0] + 'p') # pawn before promotion
delta = -color_mult * (ps[start_key[1]] + pps[start_key][sr][sc])
# 2) add mover's new term (material+PST at the END square)
end_key = pm if not move.is_pawn_promotion else (pm[0] + move.promotion_choice) # e.g. 'wQ'
delta += color_mult * (ps[end_key[1]] + pps[end_key][er][ec])
# 3) captured piece (subtract opponent’s term once)
cp = move.piece_captured
if cp != "--":
cap_mult = 1 if cp[0] == 'w' else -1
rc, cc = er, ec
if move.is_enpassant_move:
rc = er + (1 if pm[0] == 'w' else -1)
cc = ec
delta -= cap_mult * (ps[cp[1]] + pps[cp][rc][cc])
# 4) castling: rook PST delta (material unchanged)
if move.is_castle_move and pm[1] == 'K':
if pm[0] == 'w':
delta += (pps['wR'][7][5] - pps['wR'][7][7]) if ec == 6 else (pps['wR'][7][3] - pps['wR'][7][0])
else:
delta += (pps['bR'][0][5] - pps['bR'][0][7]) if ec == 6 else (pps['bR'][0][3] - pps['bR'][0][0])
return delta
def makeMove(self, move):
"""
Execute a Move, updating:
- incremental evaluatio
- board/bitboards/occupancies
- move_logn
- side to move
- king locations
- en-passant rights
- castling rights
- Zobrist key
- halfmove clock & repetition history
"""
# Save Zobrist key so undoMove can restore it directly
move.zobrist_key_before = self.zobrist_key
# Flags
is_ep = move.is_enpassant_move
is_promo = move.is_pawn_promotion
is_castle = move.is_castle_move
# Canonicalize pm/pc ONCE, before anything else uses them
self._canonicalize_move_codes(move)
# Hydrate masks etc.
self._hydrate_move_fields(move)
# ─── Incremental Eval ───
move.eval_delta = self._calc_move_delta(move)
self.current_eval += move.eval_delta
# ─── Hot locals ───
board = self.board
bb = self.bitboards
sr, sc, er, ec = move.start_row, move.start_col, move.end_row, move.end_col
from_mask, to_mask = move.from_mask, move.to_mask
pm, pc = move.piece_moved, move.piece_captured
mover_side = pm[0]
# ─── Board update ───
board[sr][sc] = "--"
board[er][ec] = pm
# Bitboards: mover from→to
bb[pm] ^= (from_mask | to_mask)
# Occupancies
if mover_side == 'w':
self.occ_white ^= (from_mask | to_mask)
else:
self.occ_black ^= (from_mask | to_mask)
# Captures
if is_ep:
# captured pawn is behind the pawn’s landing square (relative to mover)
ep_sq = (er + (1 if pm[0] == 'w' else -1)) * 8 + ec
move.ep_captured_sq = ep_sq
cap_mask = 1 << ep_sq
cap_r, cap_c = divmod(ep_sq, 8)
board[cap_r][cap_c] = "--"
bb[pc] ^= cap_mask
if pc[0] == 'w': self.occ_white ^= cap_mask
else: self.occ_black ^= cap_mask
elif pc != "--":
bb[pc] ^= to_mask
if pc[0] == 'w': self.occ_white ^= to_mask
else: self.occ_black ^= to_mask
# Promotion
if is_promo:
choice = move.promotion_choice
promoted = pm[0] + choice # e.g. 'wQ'
board[er][ec] = promoted
bb[pm] ^= to_mask # remove pawn at 'to'
bb[promoted] ^= to_mask # add promoted at 'to' (XOR to mirror undo)
# Castling rook move
if is_castle:
if ec - sc == 2: # O-O
rf, cf, rt, ct = er, 7, er, 5
else: # O-O-O
rf, cf, rt, ct = er, 0, er, 3
move.rook_from = (rf, cf)
move.rook_to = (rt, ct)
rook_code = pm[0] + 'R'
board[rf][cf] = "--"
board[rt][ct] = rook_code
m_from = 1 << (rf*8 + cf)
m_to = 1 << (rt*8 + ct)
bb[rook_code] ^= (m_from | m_to)
if mover_side == 'w': self.occ_white ^= (m_from | m_to)
else: self.occ_black ^= (m_from | m_to)
# Recompute combined
self.occ_all = self.occ_white | self.occ_black
# King square
if pm == 'wK': self.white_king_location = (er, ec)
elif pm == 'bK': self.black_king_location = (er, ec)
# Old rights/EP snapshot (before changes)
move.old_cr = (self.current_castling_rights.wks,
self.current_castling_rights.wqs,
self.current_castling_rights.bks,
self.current_castling_rights.bqs)
move.old_ep = self.enpassant_possible
move.old_ep_hashable = bool(move.old_ep) and self._ep_capturable_given_side(
move.old_ep, self.white_to_move
)
# Update CR (pre side-flip)
self.updateCastleRights(move)
self.castle_rights_log.append(CastleRights(
self.current_castling_rights.wks,
self.current_castling_rights.wqs,
self.current_castling_rights.bks,
self.current_castling_rights.bqs
))
# En-passant square
if pm[1] == 'p' and abs(sr - er) == 2:
self.enpassant_possible = ((sr + er)//2, sc)
else:
self.enpassant_possible = ()
self.enpassant_possible_log.append(self.enpassant_possible)
# New rights/EP (for Zobrist)
move.new_cr = (self.current_castling_rights.wks,
self.current_castling_rights.wqs,
self.current_castling_rights.bks,
self.current_castling_rights.bqs)
move.new_ep = self.enpassant_possible
move.new_ep_hashable = bool(move.new_ep) and self._ep_capturable_given_side(
move.new_ep, not self.white_to_move
)
# Halfmove clock
if pm[1] == 'p' or pc != '--': self.halfmove_clock = 0
else: self.halfmove_clock += 1
self.halfmove_clock_log.append(self.halfmove_clock)
# Flip side
self.white_to_move = not self.white_to_move
# Zobrist then repetition history
self._update_zobrist(move)
self._update_position_history()
# Log move
self.move_log.append(move)
def undoMove(self):
"""
Undo the last move, restoring:
eval, board/bitboards/occupancies, side, king squares,
EP & castling rights, halfmove + repetition history, and Zobrist.
"""