-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJungleChessUI.py
More file actions
1844 lines (1644 loc) · 83.1 KB
/
Copy pathJungleChessUI.py
File metadata and controls
1844 lines (1644 loc) · 83.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
# JungleChessUI.py (v15.6 - Analysis toggle fix)
import tkinter as tk
from tkinter import ttk, messagebox
import math
import random
import time
import re
from GameLogic import *
from AI import ChessBot, board_hash
from OpponentAI import OpponentAI
from enum import Enum
import multiprocessing as mp
class GameMode(Enum):
HUMAN_VS_BOT = "bot"
HUMAN_VS_HUMAN = "human"
AI_VS_AI = "ai_vs_ai"
_CASUALTIES_RE = re.compile(r'\s*\(.*?\)')
_FEN_CHAR_TO_CLASS = {'p': Pawn, 'n': Knight, 'b': Bishop, 'r': Rook, 'q': Queen, 'k': King}
_CLASS_TO_FEN_CHAR = {Pawn:'P', Knight:'N', Bishop:'B', Rook:'R', Queen:'Q', King:'K'}
# ---------------------------------------------------------------------------
# Persistent worker — runs in a subprocess, imports happen ONCE at startup.
# ---------------------------------------------------------------------------
class TaskQueueWrapper:
"""Intercepts worker messages and tags them with the current task_id."""
def __init__(self, real_queue, task_id):
self.real_queue = real_queue
self.task_id = task_id
def put(self, item):
if isinstance(item, tuple) and item and item[0] in {'move', 'log', 'eval', 'pv'}:
self.real_queue.put(item + (self.task_id,))
else:
self.real_queue.put(item)
def persistent_worker(work_queue, comm_queue, cancel_event, bot_class):
"""
Sits in a loop waiting for task dicts. Each task dict contains everything
the bot needs. Sending None shuts the worker down.
"""
while True:
task = work_queue.get() # blocks until a task arrives
if task is None: # shutdown signal
break
# The worker clears the event AFTER receiving the task.
# This prevents the UI from accidentally "un-cancelling" an aborting task.
cancel_event.clear()
task_id = task.get('task_id', -1)
wrapped_comm = TaskQueueWrapper(comm_queue, task_id)
try:
try:
# Try with full modern signature (including use_tablebase)
bot = bot_class(
task['board'], task['color'], task['position_counts'],
wrapped_comm, cancel_event,
task['bot_name'], task['ply_count'], task['game_mode'],
time_left=task.get('time_left'),
increment=task.get('increment'),
use_opening_book=task.get('use_opening_book', True),
use_tablebase=task.get('use_tablebase', True),
)
except TypeError:
try:
bot = bot_class(
task['board'], task['color'], task['position_counts'],
wrapped_comm, cancel_event,
task['bot_name'], task['ply_count'], task['game_mode'],
time_left=task.get('time_left'),
increment=task.get('increment'),
use_opening_book=task.get('use_opening_book', True),
)
except TypeError:
try:
bot = bot_class(
task['board'], task['color'], task['position_counts'],
wrapped_comm, cancel_event,
task['bot_name'], task['ply_count'], task['game_mode'],
time_left=task.get('time_left'),
increment=task.get('increment'),
)
except TypeError:
bot = bot_class(
task['board'], task['color'], task['position_counts'],
wrapped_comm, cancel_event,
task['bot_name'], task['ply_count'], task['game_mode'],
)
bot.search_depth = task['search_depth']
if task['search_depth'] == 99:
bot.ponder_indefinitely()
else:
bot.make_move()
except Exception as e:
# Prevents a silent crash from locking up the UI forever
import traceback
traceback.print_exc()
wrapped_comm.put(('move', None))
# ---------------------------------------------------------------------------
# Main application
# ---------------------------------------------------------------------------
class EnhancedChessApp:
MAIN_AI_NAME = "AI Bot"
OPPONENT_AI_NAME = "OP Bot"
ANALYSIS_AI_NAME = "Analysis"
slidermaxvalue = 12
MAX_GAME_MOVES = 200
AI_SERIES_GAMES = 300
def __init__(self, master):
self.master = master
self.master.title("Jungle Chess")
random.seed()
# --- COMMUNICATION ---
self.comm_queue = mp.Queue()
# --- PERSISTENT WORKER STATE ---
self.current_task_id = 0
self.main_work_queue = mp.Queue()
self.op_work_queue = mp.Queue()
self.main_cancel_event = mp.Event()
self.op_cancel_event = mp.Event()
self.active_worker_name = None # 'main' | 'op' | None
self.analysis_thinking = False
self.main_worker = None
self.op_worker = None
self._shutting_down = False
# --- BOARD / GAME STATE ---
self.board = Board()
self.turn = "white"
self.selected = None
self.valid_moves = []
self.game_over = False
self.game_result = None
self.dragging = False
self.drag_piece_ghost = None
self.drag_start = None
self.is_interactive = True
# --- DRAWING / ARROWS STATE ---
self.custom_arrows = set()
self.custom_highlights = set()
self.rc_start_pos = None
self.full_history = []
self.history_pointer = -1
self.position_counts = {}
self.current_opening_sequence = []
self.square_size = 75
self.base_sidebar_width = 280
self.game_mode = tk.StringVar(value=GameMode.HUMAN_VS_BOT.value)
self.analysis_mode_var = tk.BooleanVar(value=True)
self.ai_series_running = False
self.ai_series_stats = {'game_count': 0, 'my_ai_wins': 0, 'op_ai_wins': 0, 'draws': 0}
self.move_stats = {}
self._pending_move_stat = {}
self.auto_save_stats_var = tk.BooleanVar(value=True)
self.show_pv_var = tk.BooleanVar(value=True)
self.long_notation_var = tk.BooleanVar(value=False)
self.instant_move = tk.BooleanVar(value=False)
self.use_opening_book_var = tk.BooleanVar(value=True)
self.use_tablebase_var = tk.BooleanVar(value=True)
self.auto_adjudicate_var = tk.BooleanVar(value=True)
self.current_pv_raw = []
self.current_pv_san = []
self.last_pv_message = None
self.white_playing_bot_type = "main"
self.human_color = "white"
self.board_orientation = "white"
self.last_move_timestamp = None
self.game_started = False
self.last_eval_score = 0.0
self.last_eval_depth = None
self.last_eval_bar_w = 0
self.last_eval_bar_h = 0
# --- TIME STATE ---
self.time_control_seconds = tk.IntVar(value=300)
self.white_time = 0.0
self.black_time = 0.0
self.increment = 0.0
self.last_clock_tick = None
self.clock_running = False
self.use_clock_var = tk.BooleanVar(value=True)
self.COLORS = self.setup_styles()
self.master.configure(bg=self.COLORS['bg_dark'])
self.build_ui()
self.master.bind("<Key>", self.handle_key_press)
self.master.protocol("WM_DELETE_WINDOW", self._on_close)
self._start_persistent_workers()
self.process_comm_queue()
self.reset_game()
# ------------------------------------------------------------------ workers
def _start_persistent_workers(self):
self.main_worker = mp.Process(
target=persistent_worker,
args=(self.main_work_queue, self.comm_queue,
self.main_cancel_event, ChessBot),
daemon=True,
)
self.op_worker = mp.Process(
target=persistent_worker,
args=(self.op_work_queue, self.comm_queue,
self.op_cancel_event, OpponentAI),
daemon=True,
)
self.main_worker.start()
self.op_worker.start()
def _on_close(self):
"""Shut down workers and queues so window close can't hang the process."""
if self._shutting_down:
return
self._shutting_down = True
self.clock_running = False
try:
self._stop_ai_process(drain_queue=False, invalidate_task=True)
except Exception:
pass
for event in (self.main_cancel_event, self.op_cancel_event):
try:
event.set()
except Exception:
pass
for queue in (self.main_work_queue, self.op_work_queue):
try:
queue.put_nowait(None)
except Exception:
try:
queue.put(None, timeout=0.1)
except Exception:
pass
for worker in (self.main_worker, self.op_worker):
if worker is None:
continue
try:
worker.join(timeout=0.4)
except Exception:
pass
if worker.is_alive():
try:
worker.terminate()
except Exception:
pass
try:
worker.join(timeout=0.4)
except Exception:
pass
for queue in (self.comm_queue, self.main_work_queue, self.op_work_queue):
try:
queue.close()
except Exception:
pass
try:
queue.cancel_join_thread()
except Exception:
pass
try:
self.master.quit()
except Exception:
pass
self.master.destroy()
def _message_task_id(self, msg):
if not isinstance(msg, tuple) or not msg:
return None
bare_lengths = {'log': 2, 'eval': 3, 'pv': 5, 'move': 2}
bare_len = bare_lengths.get(msg[0])
if bare_len is None or len(msg) != bare_len + 1:
return None
task_id = msg[-1]
return task_id if isinstance(task_id, int) else None
# ------------------------------------------------------------------ helpers
def _format_san_display(self, s):
return s if (self.long_notation_var.get() or not s) else _CASUALTIES_RE.sub('', s)
def _on_notation_toggle(self):
self.update_moves_list()
self._render_pv()
# ------------------------------------------------------------------ clock helpers
def _start_clock(self):
if not self.use_clock_var.get() or self.game_over or self.clock_running:
return
self.last_clock_tick = time.time()
self.clock_running = True
self._tick_clock()
def _pause_clock(self):
was_running = self.clock_running
self.clock_running = False
return was_running
def _reset_clock_state(self):
base = float(self.time_control_seconds.get())
self.white_time = base
self.black_time = base
self.increment = base / 60.0
self.clock_running = False
self.last_clock_tick = None
# ------------------------------------------------------------------ UI build
def build_ui(self):
sw, sh = self.master.winfo_screenwidth(), self.master.winfo_screenheight()
self.master.geometry(f"{sw}x{sh}+0+0")
self.master.state('zoomed')
self.main_frame = ttk.Frame(self.master, style='Left.TFrame')
self.main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
# --- LEFT PANEL ---
self.left_panel = ttk.Frame(self.main_frame, style='Left.TFrame')
self.left_panel.pack(side=tk.LEFT, fill=tk.Y, padx=(0, 10))
self.left_panel.pack_propagate(False)
ttk.Label(self.left_panel, text="JUNGLE CHESS", style='Header.TLabel',
font=('Helvetica', 22, 'bold')).pack(pady=(0, 5))
self.pv_text = tk.Text(self.left_panel, height=6, bg=self.COLORS['bg_medium'],
fg=self.COLORS['text_light'], font=('Helvetica', 10),
wrap=tk.WORD, borderwidth=1, relief="solid")
self.pv_text.pack(side=tk.BOTTOM, fill=tk.X, padx=5, pady=10)
self.pv_text.config(state=tk.DISABLED)
self._build_control_widgets(self.left_panel)
# --- CENTER PANEL ---
self.center_panel = ttk.Frame(self.main_frame, style='Right.TFrame')
self.center_panel.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
self.board_column = ttk.Frame(self.center_panel, style='Right.TFrame')
self.board_column.pack(expand=True, fill=tk.BOTH)
self.eval_frame = ttk.Frame(self.board_column, style='Right.TFrame',
width=COLS * self.square_size, height=58)
self.eval_frame.pack(side=tk.TOP, anchor=tk.CENTER, pady=(6, 5))
self.eval_frame.pack_propagate(False)
self.eval_score_label = ttk.Label(self.eval_frame, text="Even",
style='Status.TLabel', anchor="center")
self.eval_score_label.pack(side=tk.TOP, pady=(0, 4))
self.eval_bar_canvas = tk.Canvas(self.eval_frame, width=COLS * self.square_size,
height=20, bg=self.COLORS['bg_light'],
highlightthickness=1,
highlightbackground=self.COLORS['text_dark'])
self.eval_bar_canvas.pack(side=tk.TOP, anchor=tk.CENTER)
self.eval_bar_canvas.bind("<Configure>", self.redraw_eval_bar_on_resize)
self.board_row_frame = ttk.Frame(self.board_column, style='Right.TFrame')
self.board_row_frame.pack(expand=True, fill=tk.BOTH)
self.canvas_frame = ttk.Frame(self.board_row_frame, style='Canvas.TFrame')
self.canvas_frame.pack(expand=True, fill=tk.BOTH)
self.canvas = tk.Canvas(self.canvas_frame,
width=COLS * self.square_size, height=ROWS * self.square_size,
bg=self.COLORS['bg_medium'], highlightthickness=0)
self.board_image = self.create_board_image()
self.board_image_id = self.canvas.create_image(0, 0, anchor='nw', tags="board")
self.canvas.pack(expand=True)
for attr in ('top_bot_label', 'bottom_bot_label'):
setattr(self, attr, ttk.Label(
self.board_row_frame, text="", font=("Helvetica", 11, "bold"),
background=self.COLORS['bg_medium'], foreground=self.COLORS['text_light'],
anchor="center", justify=tk.CENTER))
# Navigation bar
self.navigation_frame = ttk.Frame(self.center_panel, style='Right.TFrame')
self.navigation_frame.pack(fill=tk.X, pady=(5, 10))
self.start_button, self.undo_button, self.redo_button, self.end_button = [
ttk.Button(self.navigation_frame, text=t, command=c,
style='Nav.TButton', state=tk.DISABLED)
for t, c in [("«", self.go_to_start), ("‹", self.undo_move),
("›", self.redo_move), ("»", self.go_to_end)]]
self.navigation_frame.columnconfigure(0, weight=1)
self.navigation_frame.columnconfigure(5, weight=1)
for col, btn in enumerate([self.start_button, self.undo_button,
self.redo_button, self.end_button], start=1):
btn.grid(row=0, column=col, padx=5)
# --- RIGHT PANEL ---
self.right_panel = ttk.Frame(self.main_frame, style='Left.TFrame')
self.right_panel.pack(side=tk.RIGHT, fill=tk.Y, padx=(10, 0))
self.right_panel.pack_propagate(False)
self._build_right_sidebar_widgets(self.right_panel)
self.main_frame.bind("<Configure>", self.handle_main_resize)
self.center_panel.bind("<Configure>", self.handle_board_resize)
# --- PERMANENT CANVAS EVENT BINDINGS ---
self.canvas.bind("<Button-1>", self.on_drag_start)
self.canvas.bind("<B1-Motion>", self.on_drag_motion)
self.canvas.bind("<ButtonRelease-1>", self.on_drag_end)
self.canvas.bind("<Button-3>", self.on_right_click_start)
self.canvas.bind("<B3-Motion>", self.on_right_click_drag)
self.canvas.bind("<ButtonRelease-3>", self.on_right_click_end)
# Mac OS fallback for right-click support
self.canvas.bind("<Button-2>", self.on_right_click_start)
self.canvas.bind("<B2-Motion>", self.on_right_click_drag)
self.canvas.bind("<ButtonRelease-2>", self.on_right_click_end)
def _build_control_widgets(self, parent):
gf = ttk.Frame(parent, style='Left.TFrame')
gf.pack(fill=tk.X, pady=(0, 5))
ttk.Label(gf, text="GAME MODE", style='Header.TLabel').pack(anchor=tk.W)
for mode in GameMode:
ttk.Radiobutton(gf, text=mode.name.replace("_", " ").title(),
variable=self.game_mode, value=mode.value,
command=self.on_mode_changed,
style='Custom.TRadiobutton').pack(anchor=tk.W, pady=(2, 0))
cf = ttk.Frame(parent, style='Left.TFrame')
cf.pack(fill=tk.X, pady=5)
self.controls_frame = cf
for txt, cmd in [("NEW GAME", self.reset_game),
("SWAP SIDES", self.swap_sides),
("AI vs OP Series", self.start_ai_series)]:
ttk.Button(cf, text=txt, command=cmd, style='Control.TButton').pack(fill=tk.X, pady=3)
self.flip_view_btn = ttk.Button(cf, text="FLIP VIEW",
command=self.toggle_board_view, style='Control.TButton')
self.flip_view_btn.pack(fill=tk.X, pady=3)
ttk.Label(cf, text="Depth:", style='SmallHeader.TLabel').pack(anchor=tk.W, pady=(5, 0))
self.bot_depth_slider = tk.Scale(cf, from_=1, to=self.slidermaxvalue,
orient=tk.HORIZONTAL, bg=self.COLORS['bg_dark'],
fg=self.COLORS['text_light'],
highlightthickness=0, relief='flat')
self.bot_depth_slider.set(ChessBot.search_depth)
self.bot_depth_slider.pack(fill=tk.X, pady=(0, 3))
for text, var, cmd in [
("Use Opening Book", self.use_opening_book_var, None),
("Use Tablebase", self.use_tablebase_var, None),
("Instant Moves", self.instant_move, None),
("Auto Adjudicate TB Draw", self.auto_adjudicate_var, None),
("Analysis Mode (H-vs-H)", self.analysis_mode_var, self._update_analysis_after_state_change),
("Auto-save Depth Stats", self.auto_save_stats_var, None),
("Show Engine Lines (PV)", self.show_pv_var, self._render_pv),
("Long Notation (Casualties)", self.long_notation_var, self._on_notation_toggle),
]:
kw = {'command': cmd} if cmd else {}
ttk.Checkbutton(cf, text=text, variable=var,
style='Custom.TCheckbutton', **kw).pack(anchor=tk.W, pady=0)
def _build_right_sidebar_widgets(self, parent):
info = ttk.Frame(parent, style='Left.TFrame')
info.pack(side=tk.TOP, fill=tk.X, pady=(0, 5))
self.info_frame = info
self.game_info_label = ttk.Label(info, text="Match Info", style='Header.TLabel')
self.game_info_label.pack(anchor=tk.W)
self.turn_label = ttk.Label(info, text="WHITE'S TURN", style='Status.TLabel')
self.turn_label.pack(fill=tk.X, pady=(5, 5))
ttk.Checkbutton(info, text="Use Clock", variable=self.use_clock_var,
command=self._toggle_clock).pack(anchor=tk.W, pady=(2, 2))
self.clock_frame = ttk.Frame(info, style='Left.TFrame')
self.clock_frame.pack(fill=tk.X, pady=(5, 5))
self.black_clock_lbl = tk.Label(self.clock_frame, text="00:00.0",
font=('Courier', 18, 'bold'),
bg=self.COLORS['bg_medium'],
fg=self.COLORS['text_light'], pady=2)
self.black_clock_lbl.pack(side=tk.TOP, fill=tk.X, pady=1)
self.white_clock_lbl = tk.Label(self.clock_frame, text="00:00.0",
font=('Courier', 18, 'bold'),
bg=self.COLORS['bg_light'],
fg=self.COLORS['text_light'], pady=2)
self.white_clock_lbl.pack(side=tk.BOTTOM, fill=tk.X, pady=1)
self.time_control_frame = ttk.Frame(info, style='Left.TFrame')
self.time_control_frame.pack(fill=tk.X, pady=(5, 5))
self.time_control_label = ttk.Label(self.time_control_frame,
text="Time Control: 05:00",
style='SmallHeader.TLabel')
self.time_control_label.pack(anchor=tk.W)
self.time_control_slider = tk.Scale(
self.time_control_frame, from_=10, to=600, orient=tk.HORIZONTAL,
bg=self.COLORS['bg_dark'], fg=self.COLORS['text_light'],
highlightthickness=0, relief='flat', showvalue=False,
variable=self.time_control_seconds,
command=lambda _=None: self._update_time_control_label())
self.time_control_slider.set(int(self.time_control_seconds.get()))
self.time_control_slider.pack(fill=tk.X, pady=(2, 2))
self.time_control_slider.bind("<ButtonRelease-1>", lambda e: self.reset_game())
self.bottom_tools_frame = ttk.Frame(parent, style='Left.TFrame')
self.bottom_tools_frame.pack(side=tk.BOTTOM, fill=tk.X, pady=(0, 10))
self.fen_entry = self._create_import_export_widget(
self.bottom_tools_frame, "FEN String:", self.load_fen_from_entry, self.copy_fen_to_clipboard)
self.pgn_entry = self._create_import_export_widget(
self.bottom_tools_frame, "PGN Record:", self.load_pgn_from_entry, self.copy_pgn_to_clipboard)
self.scoreboard_label = ttk.Label(parent, text="", font=("Helvetica", 11),
justify=tk.LEFT, background=self.COLORS['bg_dark'],
foreground=self.COLORS['text_light'])
self.scoreboard_label.pack(side=tk.BOTTOM, fill=tk.X, pady=(5, 5))
ttk.Label(parent, text="Move History", style='SmallHeader.TLabel').pack(side=tk.TOP, anchor=tk.W)
self.tree_frame = tk.Frame(parent, bg=self.COLORS['bg_medium'])
self.tree_frame.pack(side=tk.TOP, fill=tk.BOTH, expand=True, pady=(2, 10))
hdr = tk.Frame(self.tree_frame, bg=self.COLORS['bg_light'])
hdr.pack(fill=tk.X)
tk.Label(hdr, text=" # " + "White".center(14) + "Black".center(14),
bg=self.COLORS['bg_light'], fg=self.COLORS['text_light'],
font=('Courier', 11, 'bold'), anchor=tk.W).pack(side=tk.LEFT, fill=tk.X)
self.moves_text = tk.Text(self.tree_frame, font=('Courier', 11),
bg=self.COLORS['bg_medium'], fg=self.COLORS['text_light'],
borderwidth=0, highlightthickness=0,
state=tk.DISABLED, cursor="arrow", wrap=tk.NONE)
sb = ttk.Scrollbar(self.tree_frame, orient=tk.VERTICAL, command=self.moves_text.yview)
self.moves_text.configure(yscrollcommand=sb.set)
self.moves_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
sb.pack(side=tk.RIGHT, fill=tk.Y)
def _create_import_export_widget(self, parent, label, load_cmd, copy_cmd):
frame = ttk.Frame(parent, style='Left.TFrame')
frame.pack(fill=tk.X, pady=(2, 2))
ttk.Label(frame, text=label, style='SmallHeader.TLabel').pack(anchor=tk.W)
entry = ttk.Entry(frame, font=('Courier', 10), style='TEntry')
entry.pack(fill=tk.X, pady=(2, 2))
bf = ttk.Frame(frame, style='Left.TFrame')
bf.pack(fill=tk.X)
prefix = label.split()[0]
ttk.Button(bf, text=f"Load {prefix}", command=load_cmd,
style='Control.TButton').pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 2))
ttk.Button(bf, text=f"Copy {prefix}", command=copy_cmd,
style='Control.TButton').pack(side=tk.RIGHT, fill=tk.X, expand=True, padx=(2, 0))
return entry
def setup_styles(self):
style = ttk.Style()
style.theme_use('clam')
C = {'bg_dark': '#1a1a2e', 'bg_medium': '#16213e', 'bg_light': '#0f3460',
'accent': '#e94560', 'text_light': '#ffffff', 'text_dark': '#a2a2a2',
'warning': '#FF8C00'}
style.configure('.', background=C['bg_dark'], foreground=C['text_light'])
style.configure('TFrame', background=C['bg_dark'])
style.configure('Left.TFrame', background=C['bg_dark'])
style.configure('Right.TFrame', background=C['bg_medium'])
style.configure('Canvas.TFrame', background=C['bg_medium'])
style.configure('Header.TLabel', background=C['bg_dark'], foreground=C['text_light'], font=('Helvetica', 14, 'bold'), padding=(0, 5))
style.configure('SmallHeader.TLabel', background=C['bg_dark'], foreground=C['text_light'], font=('Helvetica', 12, 'bold'), padding=(0, 1))
style.configure('Status.TLabel', background=C['bg_light'], foreground=C['text_light'], font=('Helvetica', 14, 'bold'), padding=(6, 4), relief='solid', borderwidth=1)
style.configure('Nav.TButton', background=C['bg_light'], foreground=C['text_light'],
font=('Helvetica', 16, 'bold'), padding=(10, 5), borderwidth=0)
style.map('Nav.TButton', background=[('active', C['bg_light']), ('pressed', C['bg_medium'])],
foreground=[('disabled', C['text_dark'])])
for name, bg, pressed in [('Control', C['accent'], '#d13550'),
('Flipped', C['warning'], '#E07B00')]:
style.configure(f'{name}.TButton', background=bg, foreground=C['text_light'],
font=('Helvetica', 11, 'bold'), padding=(8, 4), borderwidth=0)
style.map(f'{name}.TButton', background=[('active', bg), ('pressed', pressed)])
for name in ('Custom.TRadiobutton', 'Custom.TCheckbutton'):
style.configure(name, background=C['bg_dark'], foreground=C['text_light'],
font=('Helvetica', 11))
style.map(name, background=[('active', C['bg_dark'])],
indicatorcolor=[('selected', C['accent'])])
style.configure('TEntry', fieldbackground='#FFFFFF', foreground='#000000', insertcolor='#000000')
return C
# ------------------------------------------------------------------ resize
def handle_main_resize(self, event):
w = max(240, int(event.width * 0.20))
if w != self.left_panel.winfo_width():
self.left_panel.config(width=w)
self.right_panel.config(width=w + 20)
def handle_board_resize(self, event):
eval_h = max(self.eval_frame.winfo_height(), self.eval_frame.winfo_reqheight())
nav_h = max(self.navigation_frame.winfo_height(), self.navigation_frame.winfo_reqheight())
vw, vh = event.width - 40, event.height - eval_h - nav_h - 35
if vw <= 1 or vh <= 1:
return
new_sq = min(vw // COLS, vh // ROWS)
bw = COLS * self.square_size
self.eval_frame.config(width=bw)
self.eval_bar_canvas.config(width=bw)
if new_sq != self.square_size and new_sq > 0:
self.square_size = new_sq
bw = COLS * self.square_size
self.canvas.config(width=bw, height=ROWS * self.square_size)
self.eval_frame.config(width=bw)
self.eval_bar_canvas.config(width=bw)
self.board_image = self.create_board_image()
self.draw_board()
self._position_side_labels()
def handle_key_press(self, event):
if self.is_ai_thinking() and not self.analysis_thinking:
return
action = {'Left': self.undo_move, 'Right': self.redo_move,
'Home': self.go_to_start, 'End': self.go_to_end}.get(event.keysym)
if action:
action()
def redraw_eval_bar_on_resize(self, event):
self.draw_eval_bar(self.last_eval_score, self.last_eval_depth)
def _analysis_output_enabled(self):
return bool(getattr(self, 'analysis_mode_var', None) and self.analysis_mode_var.get())
def _clear_analysis_output(self):
self.last_eval_score = 0.0
self.last_eval_depth = None
self.current_pv_raw = []
self.current_pv_san = []
self.last_pv_message = None
self.draw_eval_bar(0)
self.eval_score_label.config(text="Even")
if hasattr(self, 'pv_text'):
self.pv_text.config(state=tk.NORMAL)
self.pv_text.delete(1.0, tk.END)
self.pv_text.config(state=tk.DISABLED)
def _sync_analysis_output_visibility(self):
if self._analysis_output_enabled():
if not self.eval_frame.winfo_manager():
self.eval_frame.pack(side=tk.TOP, anchor=tk.CENTER, pady=(6, 5),
before=self.board_row_frame)
self._render_pv()
else:
self.eval_frame.pack_forget()
self.pv_text.pack_forget()
# ------------------------------------------------------------------ flip / swap / mode
def _update_flip_view_button_style(self):
mode = self.game_mode.get()
warn = (mode == GameMode.HUMAN_VS_BOT.value and self.board_orientation != self.human_color) or \
(mode != GameMode.HUMAN_VS_BOT.value and self.board_orientation == "black")
self.flip_view_btn.configure(style='Flipped.TButton' if warn else 'Control.TButton')
def toggle_board_view(self):
self.board_orientation = "black" if self.board_orientation == "white" else "white"
self._update_flip_view_button_style()
self.update_bot_labels()
self.draw_board()
def on_mode_changed(self):
self._stop_ai_process()
mode = self.game_mode.get()
if mode == GameMode.HUMAN_VS_BOT.value:
self.board_orientation = self.human_color
if not self.game_over and self.turn != self.human_color:
self.master.after(self._get_ai_move_delay(), self._make_game_ai_move)
elif mode == GameMode.AI_VS_AI.value:
if not self.game_over:
self.master.after(self._get_ai_move_delay(), self._make_game_ai_move)
else:
self._update_analysis_after_state_change()
self._update_flip_view_button_style()
self.update_ui_after_state_change()
def swap_sides(self):
self._stop_ai_process()
if self.game_mode.get() == GameMode.HUMAN_VS_BOT.value:
self.human_color = "black" if self.human_color == "white" else "white"
self.board_orientation = self.human_color
self._update_flip_view_button_style()
self.update_ui_after_state_change()
if not self.game_over and self.turn != self.human_color:
print(f"Swapped sides. AI ({self.turn}) taking over...")
self.master.after(self._get_ai_move_delay(), self._make_game_ai_move)
def _reset_game_state_vars(self):
self.full_history = [(self.board.clone(), self.turn, None)]
self.history_pointer = 0
self.position_counts = {board_hash(self.board, self.turn): 1}
self.game_over = False
self.game_result = None
self.last_eval_score = 0.0
self.last_eval_depth = None
self.draw_eval_bar(0)
self.current_pv_raw = []
self.last_pv_message = None
self.custom_arrows.clear()
self.custom_highlights.clear()
self.rc_start_pos = None
if hasattr(self, 'pv_text'):
self.pv_text.config(state=tk.NORMAL)
self.pv_text.delete(1.0, tk.END)
self.pv_text.config(state=tk.DISABLED)
# ------------------------------------------------------------------ FEN / PGN
def get_current_fen(self):
rows = []
for r in range(ROWS):
row, empty = "", 0
for c in range(COLS):
p = self.board.grid[r][c]
if p is None:
empty += 1
else:
if empty:
row += str(empty)
empty = 0
ch = _CLASS_TO_FEN_CHAR[type(p)]
row += ch if p.color == "white" else ch.lower()
if empty:
row += str(empty)
rows.append(row)
return "/".join(rows) + f" {'w' if self.turn == 'white' else 'b'} - - 0 1"
def copy_fen_to_clipboard(self):
fen = self.get_current_fen()
self.fen_entry.delete(0, tk.END)
self.fen_entry.insert(0, fen)
self.master.clipboard_clear()
self.master.clipboard_append(fen)
def load_fen_from_entry(self):
fen = self.fen_entry.get().strip()
if not fen:
return
parts = fen.split()
self._stop_ai_process()
self.board = Board(setup=False)
r = c = 0
for ch in parts[0]:
if ch == '/':
r += 1; c = 0
elif ch.isdigit():
c += int(ch)
else:
pc = _FEN_CHAR_TO_CLASS.get(ch.lower())
if pc:
self.board.add_piece(pc("white" if ch.isupper() else "black"), r, c)
c += 1
self.turn = "white" if (parts[1] if len(parts) > 1 else 'w').lower() == 'w' else "black"
self.game_started = True
self._reset_clock_state()
self.render_clocks()
self._reset_game_state_vars()
status, winner = get_game_state(self.board, self.turn, self.position_counts,
self.history_pointer, self.MAX_GAME_MOVES)
if status != "ongoing":
self.game_over = True
self.game_result = (status, winner)
self.board_orientation = self.human_color
self._update_flip_view_button_style()
self.update_ui_after_state_change()
self._update_analysis_after_state_change()
if not self.game_over and self.game_mode.get() == GameMode.HUMAN_VS_BOT.value \
and self.turn != self.human_color:
self.master.after(self._get_ai_move_delay(), self._make_game_ai_move)
def get_current_pgn(self):
moves = []
start_turn = self.full_history[0][1]
for i in range(1, len(self.full_history)):
m = self.full_history[i][2]
if m:
moves.append(format_move_san(self.full_history[i-1][0], self.full_history[i][0], m))
pgn, move_num = "", 1
if start_turn == 'black' and moves:
pgn += f"{move_num}... {moves[0]} "
moves = moves[1:]
move_num += 1
for i in range(0, len(moves), 2):
w, b = moves[i], moves[i+1] if i+1 < len(moves) else None
pgn += f"{move_num}. {w}, {b} " if b else f"{move_num}. {w} "
move_num += 1
if self.game_result:
r = self.game_result[1]
pgn += "1-0" if r == 'white' else "0-1" if r == 'black' else "1/2-1/2"
else:
pgn += "*"
return pgn.strip()
def copy_pgn_to_clipboard(self):
pgn = self.get_current_pgn()
self.pgn_entry.delete(0, tk.END)
self.pgn_entry.insert(0, pgn)
self.master.clipboard_clear()
self.master.clipboard_append(pgn)
def load_pgn_from_entry(self):
pgn_text = self.pgn_entry.get().strip()
if not pgn_text:
return
self.reset_game()
self._pause_clock()
self.last_clock_tick = None
for res in ["1-0", "0-1", "1/2-1/2", "*"]:
pgn_text = pgn_text.replace(res, "")
pgn_text = re.sub(r'\d+\.+', '', pgn_text).replace(',', ' ')
while pgn_text.strip():
pgn_text = pgn_text.strip()
san_map = {}
for m in get_all_legal_moves(self.board, self.turn):
child = self.board.clone()
child.make_move(m[0], m[1])
san_map[format_move_san(self.board, child, m)] = m
matched_move = matched_san = None
for san in sorted(san_map, key=len, reverse=True):
if pgn_text.startswith(san) and \
(len(pgn_text) == len(san) or pgn_text[len(san)].isspace()):
matched_move = san_map[san]
matched_san = san
break
if matched_move:
self.board.make_move(matched_move[0], matched_move[1])
self.execute_move_and_check_state(self.turn, matched_move)
pgn_text = pgn_text[len(matched_san):]
if self.game_over:
break
else:
messagebox.showwarning("PGN Error", f"Could not parse: {pgn_text[:20]}...")
break
self.last_clock_tick = time.time()
# ------------------------------------------------------------------ move history UI
def update_moves_list(self):
self.moves_text.config(state=tk.NORMAL)
self.moves_text.delete(1.0, tk.END)
for tag in self.moves_text.tag_names():
if tag.startswith("ply_"):
self.moves_text.tag_delete(tag)
formatted = []
start_turn = self.full_history[0][1]
for i in range(1, len(self.full_history)):
m = self.full_history[i][2]
if m:
formatted.append(format_move_san(self.full_history[i-1][0], self.full_history[i][0], m))
pairs = []
if start_turn == 'black' and formatted:
pairs.append(["...", formatted[0]])
formatted = formatted[1:]
for i in range(0, len(formatted), 2):
pairs.append([formatted[i], formatted[i+1] if i+1 < len(formatted) else ""])
for i, pair in enumerate(pairs):
self.moves_text.insert(tk.END, f"{i+1}.".ljust(4), "num")
w_ptr = (i * 2) + 1 if start_turn == 'white' else (i * 2)
b_ptr = w_ptr + 1
w_tag, b_tag = f"ply_{w_ptr}", f"ply_{b_ptr}"
self.moves_text.insert(tk.END, self._format_san_display(pair[0]).center(14), w_tag)
self.moves_text.insert(
tk.END,
self._format_san_display(pair[1]).center(14) if pair[1] else " " * 14,
b_tag if pair[1] else "")
self.moves_text.insert(tk.END, "\n")
if pair[0] != "...":
self.moves_text.tag_bind(w_tag, "<Button-1>", lambda e, p=w_ptr: self._navigate_history(p))
self.moves_text.tag_bind(w_tag, "<Enter>", lambda e: self.moves_text.config(cursor="hand2"))
self.moves_text.tag_bind(w_tag, "<Leave>", lambda e: self.moves_text.config(cursor="arrow"))
if pair[1]:
self.moves_text.tag_bind(b_tag, "<Button-1>", lambda e, p=b_ptr: self._navigate_history(p))
self.moves_text.tag_bind(b_tag, "<Enter>", lambda e: self.moves_text.config(cursor="hand2"))
self.moves_text.tag_bind(b_tag, "<Leave>", lambda e: self.moves_text.config(cursor="arrow"))
self.moves_text.tag_configure("num", foreground=self.COLORS['text_dark'])
for tag in self.moves_text.tag_names():
if tag.startswith("ply_"):
self.moves_text.tag_configure(tag, background=self.COLORS['bg_medium'],
foreground=self.COLORS['text_light'])
if self.history_pointer > 0:
atag = f"ply_{self.history_pointer}"
self.moves_text.tag_configure(atag, background=self.COLORS['accent'],
foreground=self.COLORS['text_light'])
try:
self.moves_text.see(f"{atag}.first")
except tk.TclError:
pass
self.moves_text.config(state=tk.DISABLED)
# ------------------------------------------------------------------ core gameplay
def execute_move_and_check_state(self, player_who_moved, move):
if self.use_clock_var.get() and not self.game_over and self.increment:
if player_who_moved == 'white':
self.white_time += self.increment
else:
self.black_time += self.increment
self.render_clocks()
self.switch_turn()
self._start_clock()
if self.history_pointer < len(self.full_history) - 1:
self.full_history = self.full_history[:self.history_pointer + 1]
self.position_counts.clear()
for board, turn, _ in self.full_history:
h = board_hash(board, turn)
self.position_counts[h] = self.position_counts.get(h, 0) + 1
self.full_history.append((self.board.clone(), self.turn, move))
self.history_pointer += 1
key = board_hash(self.board, self.turn)
self.position_counts[key] = self.position_counts.get(key, 0) + 1
status, winner = get_game_state(self.board, self.turn, self.position_counts,
self.history_pointer, self.MAX_GAME_MOVES)
if status != "ongoing":
self.game_over = True
self.game_result = (status, winner)
self.update_ui_after_state_change()
if self.game_over:
print(f"Game Over! Result: {self.game_result[0]}")
self._stop_ai_process()
if self.game_mode.get() == GameMode.AI_VS_AI.value and self.ai_series_running:
self.process_ai_series_result()
def _execute_ai_move(self, the_move):
if self.game_over:
return
if the_move:
self.board.make_move(the_move[0], the_move[1])
self.execute_move_and_check_state(self.turn, the_move)
# --- AUTO ADJUDICATE TB DRAW ---
if not self.game_over and self.auto_adjudicate_var.get() and \
self.game_mode.get() != GameMode.HUMAN_VS_HUMAN.value:
if self.last_eval_depth == "TB" and abs(self.last_eval_score) < 0.05:
self.game_over = True
self.game_result = ("tb draw", None)
self.update_ui_after_state_change()
print("Game Over! Result: TB Draw (Auto-adjudicated)")
if self.game_mode.get() == GameMode.AI_VS_AI.value and self.ai_series_running:
self.process_ai_series_result()
# -------------------------------
if not self.game_over and self.game_mode.get() == GameMode.AI_VS_AI.value:
self.master.after(self._get_ai_move_delay(), self._make_game_ai_move)
else:
print("AI reported no valid move.")
self._stop_ai_process()
self.update_bot_labels()
self.set_interactivity(True)
def on_drag_start(self, event):
cleared_custom = False
if self.custom_arrows or self.custom_highlights:
self.custom_arrows.clear()
self.custom_highlights.clear()
cleared_custom = True
if not getattr(self, 'is_interactive', True) or self.game_over:
if cleared_custom:
self.draw_board()
return
if self.is_ai_thinking() and not self.analysis_thinking:
if cleared_custom:
self.draw_board()
return
r, c = self.canvas_to_board(event.x, event.y)
if r == -1 or not self.board.grid[r][c]:
if cleared_custom:
self.draw_board()
return
piece = self.board.grid[r][c]
if piece.color != self.turn:
if cleared_custom:
self.draw_board()
return
if self.game_mode.get() == GameMode.HUMAN_VS_BOT.value and self.turn != self.human_color:
if cleared_custom:
self.draw_board()
return
self.selected = (r, c)
self.drag_start = (r, c)
self.dragging = True
self.valid_moves = get_all_legal_moves(self.board, self.turn)
self.valid_moves_for_highlight = [e for s, e in self.valid_moves if s == self.selected]
self.drag_piece_ghost = self.canvas.create_text(
event.x, event.y, text=piece.symbol(),
font=("Arial Unicode MS", int(self.square_size * 0.7)),
fill=self.turn, tags="drag_ghost")
self.draw_board()
self.canvas.tag_raise("drag_ghost")