-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChessMain.py
More file actions
893 lines (737 loc) · 30.2 KB
/
Copy pathChessMain.py
File metadata and controls
893 lines (737 loc) · 30.2 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
"""
Pygame front-end for the chess engine.
This module handles:
- rendering
- user input
- move-log display
- a background AI worker thread
- synchronisation between the UI board and a python-chess mirror board
"""
from __future__ import annotations
from pathlib import Path
import queue
import sys
import threading
import chess as pc
import pygame as p
try:
from .ChessEngine import GameState, Move, perft
from . import ChessAI
except ImportError:
from ChessEngine import GameState, Move, perft
import ChessAI
BOARD_WIDTH = BOARD_HEIGHT = 512
MOVE_LOG_PANEL_WIDTH = 350
MOVE_LOG_PANEL_HEIGHT = BOARD_HEIGHT
DIMENSION = 8
SQUARE_SIZE = BOARD_HEIGHT // DIMENSION
MAX_FPS = 60
EVAL_BAR_WIDTH = 40
EVAL_BAR_CLAMP = 6.0
BOARD_X = EVAL_BAR_WIDTH
IMAGES: dict[str, p.Surface] = {}
# SAN/book side tables (keep engine objects pristine)
SAN_TAG: dict[int, str] = {}
BOOK_TAG: set[int] = set()
LIGHT_COLOR = p.Color("mediumturquoise")
DARK_COLOR = p.Color("royalblue")
WHITE = p.Color("white")
BLACK = p.Color("black")
GRAY = p.Color("gray")
HIGHLIGHT_LAST = p.Surface((SQUARE_SIZE, SQUARE_SIZE))
HIGHLIGHT_LAST.set_alpha(100)
HIGHLIGHT_LAST.fill(p.Color("green"))
HIGHLIGHT_MOVE = p.Surface((SQUARE_SIZE, SQUARE_SIZE))
HIGHLIGHT_MOVE.set_alpha(100)
HIGHLIGHT_MOVE.fill(p.Color("yellow"))
HIGHLIGHT_CHECK = p.Surface((SQUARE_SIZE, SQUARE_SIZE), p.SRCALPHA)
HIGHLIGHT_CHECK.fill((255, 0, 0, 90))
ENDGAME_FONT = None
PROMPT_FONT = None
EVAL_FONT = None
ASSET_DIR = Path(__file__).resolve().parent
IMAGE_DIR = ASSET_DIR / "images"
def _uci_from_mv(mv: Move) -> str:
"""Build UCI from the engine move coordinates."""
def sq(r: int, c: int) -> str:
return "abcdefgh"[c] + str(8 - r)
u = sq(mv.start_row, mv.start_col) + sq(mv.end_row, mv.end_col)
if getattr(mv, "is_pawn_promotion", False):
promo = (mv.promotion_choice or "Q").lower()
u += promo
return u
def _engine_to_pc_move(pc_board: pc.Board, mv: Move) -> pc.Move | None:
"""
Convert our Move into a legal python-chess Move on the current board.
"""
try:
uci = _uci_from_mv(mv)
candidate = pc.Move.from_uci(uci)
except Exception:
try:
candidate = pc.Move.from_uci(_uci_from_mv(mv) + "q")
except Exception:
return None
if candidate in pc_board.legal_moves:
return candidate
matches = [
legal for legal in pc_board.legal_moves
if legal.from_square == candidate.from_square and legal.to_square == candidate.to_square
]
if getattr(mv, "is_pawn_promotion", False):
want = {
"q": pc.QUEEN,
"r": pc.ROOK,
"b": pc.BISHOP,
"n": pc.KNIGHT,
}[(mv.promotion_choice or "Q").lower()]
matches = [legal for legal in matches if legal.promotion == want]
return matches[0] if matches else None
def _push_pc_and_tag_san(pc_board: pc.Board, mv: Move) -> None:
"""
Compute SAN on the pre-move board, push the move, and store SAN for UI display.
"""
u = _engine_to_pc_move(pc_board, mv)
if u is None:
try:
SAN_TAG[id(mv)] = mv.getChessNotation()
except Exception:
SAN_TAG[id(mv)] = "?"
return
SAN_TAG[id(mv)] = pc_board.san(u)
pc_board.push(u)
def loadImages() -> None:
"""
Load and cache piece sprites.
Must be called after pygame display initialisation so convert_alpha()
can match the display format.
"""
assert p.display.get_surface() is not None, "Call loadImages() after set_mode()."
pieces = ["wp", "wR", "wN", "wB", "wK", "wQ", "bp", "bR", "bN", "bB", "bK", "bQ"]
for piece in pieces:
image_path = IMAGE_DIR / f"{piece}.png"
IMAGES[piece] = p.transform.scale(
p.image.load(str(image_path)).convert_alpha(),
(SQUARE_SIZE, SQUARE_SIZE),
)
def getPromotionChoice(screen: p.Surface, pawn_color: str) -> str:
"""
Modal overlay prompting Q/R/B/N. ESC or window close defaults to Queen.
"""
global PROMPT_FONT
if PROMPT_FONT is None:
PROMPT_FONT = p.font.SysFont("Arial", 24, True, False)
prompt = f"Promote {pawn_color} pawn: [Q]ueen [R]ook [B]ishop K[N]ight"
choice = None
clock = p.time.Clock()
while choice not in ("Q", "R", "B", "N"):
for event in p.event.get():
if event.type == p.QUIT:
p.quit()
sys.exit()
if event.type == p.KEYDOWN:
if event.key == p.K_q:
choice = "Q"
elif event.key == p.K_r:
choice = "R"
elif event.key == p.K_b:
choice = "B"
elif event.key == p.K_n:
choice = "N"
elif event.key == p.K_ESCAPE:
choice = "Q"
overlay = p.Surface((BOARD_WIDTH, BOARD_HEIGHT), p.SRCALPHA)
overlay.fill((0, 0, 0, 200))
screen.blit(overlay, (BOARD_X, 0))
text_surf = PROMPT_FONT.render(prompt, True, WHITE)
screen.blit(
text_surf,
(
BOARD_X + BOARD_WIDTH // 2 - text_surf.get_width() // 2,
BOARD_HEIGHT // 2 - text_surf.get_height() // 2,
),
)
p.display.flip()
clock.tick(60)
return choice
def _pack_move_log(move_log: list[Move]) -> list[tuple[int, int, int, int, str | None]]:
return [
(
m.start_row,
m.start_col,
m.end_row,
m.end_col,
m.promotion_choice if getattr(m, "is_pawn_promotion", False) else None,
)
for m in move_log
]
def _drain_queue(q: queue.Queue) -> None:
while True:
try:
q.get_nowait()
except queue.Empty:
break
def main() -> None:
"""
Main UI loop.
"""
global ENDGAME_FONT, EVAL_FONT
p.init()
EVAL_FONT = p.font.SysFont("Arial", 18, True, False)
ENDGAME_FONT = p.font.SysFont("Arial", 32, True, False)
screen = p.display.set_mode((BOARD_X + BOARD_WIDTH + MOVE_LOG_PANEL_WIDTH, BOARD_HEIGHT))
p.display.set_caption("Chess")
clock = p.time.Clock()
loadImages()
game_state = GameState()
pc_board = pc.Board()
valid_moves = game_state.getValidMoves()
move_log_font = p.font.SysFont("Arial", 14, False, False)
ai_request_q: queue.Queue = queue.Queue()
ai_response_q: queue.Queue = queue.Queue()
search_gen = 0
active_search_gen = None
def ai_worker(request_q: queue.Queue, response_q: queue.Queue) -> None:
gs_ai = GameState()
def _apply_packed(gs: GameState, packed: list[tuple[int, int, int, int, str | None]] | None) -> bool:
if not packed:
return True
for sr, sc, er, ec, promo in packed:
pick = None
for m in gs.getValidMoves():
if (m.start_row, m.start_col, m.end_row, m.end_col) == (sr, sc, er, ec):
if promo and getattr(m, "is_pawn_promotion", False):
m.promotion_choice = promo
if hasattr(m, "recompute_id"):
m.recompute_id()
pick = m
break
if pick is None:
return False
gs.makeMove(pick)
return True
def _clear_search_state() -> None:
try:
ChessAI.TT.clear()
except Exception:
pass
try:
ChessAI.history_scores.clear()
except Exception:
try:
ChessAI.history_scores = type(ChessAI.history_scores)()
except Exception:
pass
try:
for idx in range(len(ChessAI.killers)):
ChessAI.killers[idx][0] = 0
ChessAI.killers[idx][1] = 0
except Exception:
pass
while True:
msg = request_q.get()
if msg == "reset":
gs_ai = GameState()
_clear_search_state()
continue
if isinstance(msg, tuple) and msg[0] == "reset":
packed_log = msg[1] if len(msg) >= 2 else None
gs_ai = GameState()
ok = _apply_packed(gs_ai, packed_log)
_clear_search_state()
if not ok:
print("[AI] reset replay failed: could not reconstruct packed move log.")
continue
if msg == "undo":
if getattr(gs_ai, "move_log", None):
gs_ai.undoMove()
continue
if isinstance(msg, tuple) and msg[0] == "apply":
_, sr, sc, er, ec, promo = msg
pick = None
for m in gs_ai.getValidMoves():
if (m.start_row, m.start_col, m.end_row, m.end_col) == (sr, sc, er, ec):
if promo and getattr(m, "is_pawn_promotion", False):
m.promotion_choice = promo
if hasattr(m, "recompute_id"):
m.recompute_id()
pick = m
break
if pick is not None:
gs_ai.makeMove(pick)
continue
if isinstance(msg, tuple) and msg[0] == "search":
gen = msg[1]
packed_log = msg[2] if len(msg) >= 3 else None
if packed_log is None:
snap = gs_ai
else:
snap = GameState()
if not _apply_packed(snap, packed_log):
response_q.put((gen, None))
continue
tmp_q = queue.Queue()
ChessAI.findBestMove(snap, snap.getValidMoves(), tmp_q)
ai_move = tmp_q.get()
if ai_move is None:
response_q.put((gen, None))
continue
if isinstance(ai_move, tuple):
if len(ai_move) >= 6 and isinstance(ai_move[0], str) and ai_move[0] in ("book", "move"):
tag, sr, sc, er, ec, promo = ai_move[:6]
response_q.put((gen, (tag, sr, sc, er, ec, promo)))
else:
if len(ai_move) == 5:
sr, sc, er, ec, promo = ai_move
elif len(ai_move) == 4:
sr, sc, er, ec = ai_move
promo = None
else:
response_q.put((gen, None))
continue
response_q.put((gen, ("move", sr, sc, er, ec, promo)))
else:
promo = (
ai_move.promotion_choice
if getattr(ai_move, "is_pawn_promotion", False)
else None
)
response_q.put(
(
gen,
(
"move",
ai_move.start_row,
ai_move.start_col,
ai_move.end_row,
ai_move.end_col,
promo,
),
)
)
threading.Thread(target=ai_worker, args=(ai_request_q, ai_response_q), daemon=True).start()
running = True
square_selected = ()
player_clicks: list[tuple[int, int]] = []
move_made = False
animate = False
game_over = False
ai_thinking = False
player_one = True
player_two = False
def _resync_ai_from_ui() -> None:
nonlocal ai_thinking, active_search_gen
_drain_queue(ai_response_q)
ai_request_q.put(("reset", _pack_move_log(game_state.move_log)))
ai_thinking = False
active_search_gen = None
while running:
human_turn = (game_state.white_to_move and player_one) or (
not game_state.white_to_move and player_two
)
for event in p.event.get():
if event.type == p.QUIT:
p.quit()
sys.exit()
elif event.type == p.MOUSEBUTTONDOWN and event.button == 1 and not game_over:
x, y = p.mouse.get_pos()
if x < BOARD_X or x >= BOARD_X + BOARD_WIDTH or y >= BOARD_HEIGHT:
square_selected, player_clicks = (), []
continue
col = (x - BOARD_X) // SQUARE_SIZE
row = y // SQUARE_SIZE
if square_selected == (row, col) or col >= DIMENSION:
square_selected = ()
player_clicks = []
else:
square_selected = (row, col)
player_clicks.append(square_selected)
if len(player_clicks) == 2 and human_turn:
move = Move(player_clicks[0], player_clicks[1], game_state.board)
for mv in valid_moves:
if (
move.start_row == mv.start_row
and move.start_col == mv.start_col
and move.end_row == mv.end_row
and move.end_col == mv.end_col
):
if mv.is_pawn_promotion:
choice = getPromotionChoice(
screen,
"White" if mv.piece_moved[0] == "w" else "Black",
)
mv.promotion_choice = choice
if hasattr(mv, "recompute_id"):
mv.recompute_id()
_push_pc_and_tag_san(pc_board, mv)
game_state.makeMove(mv)
ai_request_q.put(
(
"apply",
mv.start_row,
mv.start_col,
mv.end_row,
mv.end_col,
mv.promotion_choice if getattr(mv, "is_pawn_promotion", False) else None,
)
)
move_made = True
animate = True
square_selected = ()
player_clicks = []
break
if not move_made:
player_clicks = [square_selected]
elif event.type == p.KEYDOWN:
if event.key == p.K_z:
last = game_state.move_log[-1] if game_state.move_log else None
game_state.undoMove()
if pc_board.move_stack:
pc_board.pop()
if last is not None:
SAN_TAG.pop(id(last), None)
BOOK_TAG.discard(id(last))
_resync_ai_from_ui()
valid_moves = game_state.getValidMoves()
square_selected, player_clicks = (), []
move_made = True
animate = False
game_over = False
elif event.key == p.K_r:
game_state = GameState()
pc_board = pc.Board()
SAN_TAG.clear()
BOOK_TAG.clear()
ai_request_q.put("reset")
ai_thinking = False
active_search_gen = None
valid_moves = game_state.getValidMoves()
square_selected = ()
player_clicks = []
move_made = False
animate = False
game_over = False
if not game_over and not human_turn:
if not ai_thinking:
ai_thinking = True
search_gen += 1
active_search_gen = search_gen
ai_request_q.put(("search", active_search_gen, _pack_move_log(game_state.move_log)))
else:
try:
item = ai_response_q.get_nowait()
except queue.Empty:
item = None
if item is not None:
if isinstance(item, tuple) and len(item) == 2 and isinstance(item[0], int):
gen, payload = item
else:
gen, payload = active_search_gen, item
if gen == active_search_gen:
def _reconstruct(sr: int, sc: int, er: int, ec: int, promo: str | None) -> Move | None:
for m in game_state.getValidMoves():
if (m.start_row, m.start_col, m.end_row, m.end_col) == (sr, sc, er, ec):
if promo and getattr(m, "is_pawn_promotion", False):
m.promotion_choice = promo
if hasattr(m, "recompute_id"):
m.recompute_id()
return m
return None
if payload is None:
_ = game_state.getValidMoves()
ai_thinking = False
elif isinstance(payload, tuple):
try:
tag, sr, sc, er, ec, promo = payload
except Exception:
print("AI returned malformed move tuple; resynchronising worker.")
_resync_ai_from_ui()
continue
legal = _reconstruct(sr, sc, er, ec, promo)
if legal is None:
print("AI returned an illegal move; resynchronising worker.")
_resync_ai_from_ui()
else:
if tag == "book":
BOOK_TAG.add(id(legal))
try:
legal.from_book = True
except Exception:
pass
_push_pc_and_tag_san(pc_board, legal)
game_state.makeMove(legal)
ai_request_q.put(
(
"apply",
legal.start_row,
legal.start_col,
legal.end_row,
legal.end_col,
legal.promotion_choice if getattr(legal, "is_pawn_promotion", False) else None,
)
)
move_made = True
animate = True
ai_thinking = False
else:
legal = payload
_push_pc_and_tag_san(pc_board, legal)
game_state.makeMove(legal)
ai_request_q.put(
(
"apply",
legal.start_row,
legal.start_col,
legal.end_row,
legal.end_col,
legal.promotion_choice if getattr(legal, "is_pawn_promotion", False) else None,
)
)
move_made = True
animate = True
ai_thinking = False
if move_made:
if animate and game_state.move_log:
animateMove(game_state.move_log[-1], screen, game_state.board, clock)
valid_moves = game_state.getValidMoves()
move_made = False
animate = False
drawGameState(screen, game_state, valid_moves, square_selected)
if not game_over:
drawMoveLog(screen, game_state, move_log_font)
if game_state.checkmate:
game_over = True
text = "Black wins by checkmate" if game_state.white_to_move else "White wins by checkmate"
drawEndGameText(screen, text)
elif game_state.stalemate:
game_over = True
drawEndGameText(screen, "Stalemate")
elif game_state.is_threefold_repetition():
game_over = True
drawEndGameText(screen, "Draw by three-fold repetition")
elif game_state.is_fifty_move_rule():
game_over = True
drawEndGameText(screen, "Draw by 50-move rule")
elif game_state.is_insufficient_material():
game_over = True
drawEndGameText(screen, "Draw by insufficient material")
clock.tick(MAX_FPS)
p.display.flip()
def drawEvalBar(screen: p.Surface, game_state: GameState) -> None:
"""
Draw a vertical eval bar at x=[0..EVAL_BAR_WIDTH).
Uses ChessAI.scoreBoard (white-positive, in pawns).
"""
bar_rect = p.Rect(0, 0, EVAL_BAR_WIDTH, BOARD_HEIGHT)
p.draw.rect(screen, p.Color(30, 30, 30), bar_rect)
inner = bar_rect.inflate(-8, -8)
p.draw.rect(screen, p.Color(50, 50, 50), inner)
try:
val_pawns = float(ChessAI.scoreBoard(game_state, fast=True))
except Exception:
val_pawns = 0.0
v = max(-EVAL_BAR_CLAMP, min(EVAL_BAR_CLAMP, val_pawns))
white_frac = 0.5 + (v / (2.0 * EVAL_BAR_CLAMP))
white_frac = max(0.0, min(1.0, white_frac))
split_y = int(inner.top + inner.height * (1.0 - white_frac))
black_rect = p.Rect(inner.left, inner.top, inner.width, split_y - inner.top)
white_rect = p.Rect(inner.left, split_y, inner.width, inner.bottom - split_y)
if black_rect.height > 0:
p.draw.rect(screen, p.Color("black"), black_rect)
if white_rect.height > 0:
p.draw.rect(screen, p.Color("white"), white_rect)
if EVAL_FONT:
txt = f"{val_pawns:+.1f}".replace("+", "")
if val_pawns >= 0:
surf = EVAL_FONT.render(txt, True, p.Color("black"))
screen.blit(
surf,
(
inner.centerx - surf.get_width() // 2,
min(inner.bottom - surf.get_height() - 6, inner.bottom - 26),
),
)
else:
surf = EVAL_FONT.render(txt, True, p.Color("white"))
screen.blit(
surf,
(
inner.centerx - surf.get_width() // 2,
max(inner.top + 6, inner.top + 10),
),
)
def drawGameState(
screen: p.Surface,
game_state: GameState,
valid_moves: list[Move],
square_selected: tuple[int, int] | tuple,
) -> None:
drawEvalBar(screen, game_state)
drawBoard(screen)
highlightSquares(screen, game_state, valid_moves, square_selected)
drawPieces(screen, game_state.board)
def drawBoard(screen: p.Surface) -> None:
for row in range(DIMENSION):
for column in range(DIMENSION):
color = LIGHT_COLOR if (row + column) % 2 == 0 else DARK_COLOR
p.draw.rect(
screen,
color,
p.Rect(
BOARD_X + column * SQUARE_SIZE,
row * SQUARE_SIZE,
SQUARE_SIZE,
SQUARE_SIZE,
),
)
def highlightSquares(
screen: p.Surface,
game_state: GameState,
valid_moves: list[Move],
square_selected: tuple[int, int] | tuple,
) -> None:
board = game_state.board
if game_state.move_log:
last = game_state.move_log[-1]
screen.blit(HIGHLIGHT_LAST, (BOARD_X + last.start_col * SQUARE_SIZE, last.start_row * SQUARE_SIZE))
screen.blit(HIGHLIGHT_LAST, (BOARD_X + last.end_col * SQUARE_SIZE, last.end_row * SQUARE_SIZE))
if game_state.inCheck():
kr, kc = (
game_state.white_king_location
if game_state.white_to_move
else game_state.black_king_location
)
screen.blit(HIGHLIGHT_CHECK, (BOARD_X + kc * SQUARE_SIZE, kr * SQUARE_SIZE))
if square_selected:
r, c = square_selected
own = "w" if game_state.white_to_move else "b"
if 0 <= r < 8 and 0 <= c < 8 and board[r][c] != "--" and board[r][c][0] == own:
screen.blit(HIGHLIGHT_MOVE, (BOARD_X + c * SQUARE_SIZE, r * SQUARE_SIZE))
for m in valid_moves:
if m.start_row == r and m.start_col == c:
ex = BOARD_X + m.end_col * SQUARE_SIZE
ey = m.end_row * SQUARE_SIZE
cx = ex + SQUARE_SIZE // 2
cy = ey + SQUARE_SIZE // 2
if board[m.end_row][m.end_col] == "--" and not m.is_enpassant_move:
p.draw.circle(screen, GRAY, (cx, cy), max(4, SQUARE_SIZE // 10))
else:
p.draw.circle(
screen,
GRAY,
(cx, cy),
max(12, SQUARE_SIZE // 3),
width=max(2, SQUARE_SIZE // 16),
)
def drawPieces(screen: p.Surface, board: list[list[str]]) -> None:
for row in range(DIMENSION):
for column in range(DIMENSION):
piece = board[row][column]
if piece != "--":
screen.blit(
IMAGES[piece],
p.Rect(
BOARD_X + column * SQUARE_SIZE,
row * SQUARE_SIZE,
SQUARE_SIZE,
SQUARE_SIZE,
),
)
def drawMoveLog(screen: p.Surface, game_state: GameState, font: p.font.Font) -> None:
rect = p.Rect(BOARD_X + BOARD_WIDTH, 0, MOVE_LOG_PANEL_WIDTH, MOVE_LOG_PANEL_HEIGHT)
p.draw.rect(screen, BLACK, rect)
moves = game_state.move_log
def _mv_str(m: Move) -> str:
s = SAN_TAG.get(id(m)) or m.getChessNotation()
if (id(m) in BOOK_TAG) or getattr(m, "from_book", False):
s += " (book)"
return s
lines = []
for i in range(0, len(moves), 2):
left = _mv_str(moves[i])
if i + 1 < len(moves):
right = _mv_str(moves[i + 1])
lines.append(f"{i // 2 + 1}. {left} {right}")
else:
lines.append(f"{i // 2 + 1}. {left}")
padding = 5
line_spacing = 2
sample = font.render("8. ...", True, WHITE)
line_h = sample.get_height()
max_rows = max(1, (MOVE_LOG_PANEL_HEIGHT - 2 * padding) // (line_h + line_spacing))
start = max(0, len(lines) - max_rows * 3)
y = padding
for i in range(start, len(lines), 3):
text = " ".join(lines[i:i + 3])
surf = font.render(text, True, WHITE)
screen.blit(surf, rect.move(padding, y))
y += line_h + line_spacing
def drawEndGameText(screen: p.Surface, text: str) -> None:
global ENDGAME_FONT
if ENDGAME_FONT is None:
ENDGAME_FONT = p.font.SysFont("Helvetica", 32, True, False)
main_surf = ENDGAME_FONT.render(text, True, GRAY)
shadow_surf = ENDGAME_FONT.render(text, True, BLACK)
x = BOARD_X + BOARD_WIDTH // 2 - main_surf.get_width() // 2
y = BOARD_HEIGHT // 2 - main_surf.get_height() // 2
screen.blit(shadow_surf, (x + 2, y + 2))
screen.blit(main_surf, (x, y))
def animateMove(move: Move, screen: p.Surface, board: list[list[str]], clock: p.time.Clock) -> None:
dr = move.end_row - move.start_row
dc = move.end_col - move.start_col
frames_per_sq = 10
total_frames = max(1, (abs(dr) + abs(dc)) * frames_per_sq)
for frame in range(total_frames + 1):
r = move.start_row + dr * frame / total_frames
c = move.start_col + dc * frame / total_frames
drawBoard(screen)
drawPieces(screen, board)
sq_color = LIGHT_COLOR if (move.end_row + move.end_col) % 2 == 0 else DARK_COLOR
p.draw.rect(
screen,
sq_color,
p.Rect(
BOARD_X + move.end_col * SQUARE_SIZE,
move.end_row * SQUARE_SIZE,
SQUARE_SIZE,
SQUARE_SIZE,
),
)
if move.piece_captured != "--":
if move.is_enpassant_move:
er = move.end_row + 1 if move.piece_captured[0] == "b" else move.end_row - 1
dest = p.Rect(BOARD_X + move.end_col * SQUARE_SIZE, er * SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE)
else:
dest = p.Rect(
BOARD_X + move.end_col * SQUARE_SIZE,
move.end_row * SQUARE_SIZE,
SQUARE_SIZE,
SQUARE_SIZE,
)
screen.blit(IMAGES[move.piece_captured], dest)
x = BOARD_X + int(round(c * SQUARE_SIZE))
y = int(round(r * SQUARE_SIZE))
screen.blit(IMAGES[move.piece_moved], p.Rect(x, y, SQUARE_SIZE, SQUARE_SIZE))
p.display.flip()
clock.tick(60)
if __name__ == "__main__":
main()
# Optional perft smoke tests:
# gs = GameState()
# for d in range(1, 6):
# import time
# t0 = time.perf_counter()
# n = perft(gs, d)
# dt = time.perf_counter() - t0
# print(f"depth {d}: {n:,} nodes in {dt:.3f}s ({n / dt:,.0f} nps)")
'''
Best perft harness result:
depth 1: 20 nodes in 0.001s (38,873 nps)
depth 2: 400 nodes in 0.018s (21,770 nps)
depth 3: 8,902 nodes in 0.220s (40,445 nps)
depth 4: 197,281 nodes in 0.761s (259,078 nps)
depth 5: 4,865,609 nodes in 5.035s (966,341 nps)
depth 6: 119,060,324 nodes in 80.988s (1,470,098 nps)
depth 7: 3,195,901,860 nodes in 2035.135s (1,570,364 nps)
Current:
'''