-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
2937 lines (2600 loc) · 151 KB
/
Copy pathmain.py
File metadata and controls
2937 lines (2600 loc) · 151 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
import sys
import warnings
import os
# --- FIX 1: Silence specific DeprecationWarnings (pkg_resources/pygame) ---
warnings.filterwarnings("ignore", category=UserWarning)
warnings.filterwarnings("ignore", category=DeprecationWarning)
import pygame
import chess
import chess.engine
import logging
# Silences harmless python-chess engine warnings in the console
logging.getLogger("chess.engine").setLevel(logging.CRITICAL)
import chess.pgn
import chess.polyglot
import threading
import time
import queue
import random
import json
import re
import tkinter as tk
from tkinter import filedialog, messagebox
from database_explorer import OpeningExplorer, ExplorerUI
# --- FIX: Prevent Stockfish 18 "Illegal Ponder Move" Crashes ---
# python-chess strictly validates ponder moves. Stockfish 18 sometimes sends
# illegal ponder moves when finding a forced mate, crashing the entire app.
_original_parse_uci = chess.Board.parse_uci
def _safe_parse_uci(self, uci):
try:
return _original_parse_uci(self, uci)
except chess.IllegalMoveError:
return chess.Move.from_uci(uci)
chess.Board.parse_uci = _safe_parse_uci
# ---------------------------------------------------------------
# --- FIX 2: REMOVED the WindowsSelectorEventLoopPolicy setting ---
# Python 3.8+ on Windows defaults to ProactorEventLoop, which IS required
# for chess.engine to communicate with Stockfish via subprocesses.
# The previous override was causing the NotImplementedError.
# Custom Modules
try: import bot_personalities
except ImportError: bot_personalities = None
import analysis_engine
try: import game_logic
except ImportError: game_logic = None
from assets import AssetLoader, SoundManager, BOTS, THEME, BOT_VOICE_MAP, PIECE_VALS
from popups import (PGNSavePopup, AnalyzePromptPopup, BotPopup, PGNSelectionPopup, GMPopup, PromotionPopup,
ReviewPopup, SideSelectionPopup, ProfilePopup, SettingsPopup, EnginePopup,
PhaseStatsPopup, PuzzlePopup, SaveMatePopup, TrainerCompletePopup, ButtonsPopup, FastImportLoadingPopup)
from ui_renderer import UIRenderer
class TrainerPopup:
def __init__(self, app):
self.app = app
self.active = True
# --- FIX: Widen popup to fit new tutorial/practice buttons ---
w, h = 800, 750
self.rect = pygame.Rect((app.width - w)//2, (app.height - h)//2, w, h)
self.scroll_y = 0
self.max_scroll = 0
self.groups = {}
self.expanded_groups = set()
self.click_zones = []
self.tab = "openings" # "openings" or "mates"
self.btn_tab_openings = None
self.btn_tab_mates = None
self.font_title = pygame.font.SysFont("Segoe UI", 22, bold=True)
self.font_group = pygame.font.SysFont("Segoe UI", 16, bold=True)
self.font_var = pygame.font.SysFont("Segoe UI", 15, bold=True)
self.font_moves = pygame.font.SysFont("Consolas", 13)
self.close_icon = None
icon_path = os.path.join("assets", "icons", "close_btn.png")
if os.path.exists(icon_path):
try:
img = pygame.image.load(icon_path).convert_alpha()
self.close_icon = pygame.transform.smoothscale(img, (24, 24))
except: pass
self.filter_text = ""
self.cursor_timer = 0
self.load_data()
def load_data(self):
self.groups.clear()
self.expanded_groups.clear()
data_source = self.app.assets.opening_list if self.tab == "openings" else self.app.assets.mate_list
if data_source:
for op in data_source:
name = op.get('name', 'Unknown')
if ":" in name:
group, var = name.split(":", 1)
group = group.strip()
var = var.strip()
else:
group = name
var = "Main Line" if self.tab == "openings" else "Sequence"
if group not in self.groups: self.groups[group] = []
move_str = self.generate_san_string(op.get('moves', []))
self.groups[group].append({'name': var, 'moves_str': move_str, 'data': op})
if len(self.groups) < 5:
for g in self.groups: self.expanded_groups.add(g)
def generate_san_string(self, moves):
try:
temp_board = chess.Board()
san_list = []
for i, move in enumerate(moves):
if isinstance(move, str):
try: move = chess.Move.from_uci(move)
except: break
if move not in temp_board.legal_moves: break
san = temp_board.san(move)
temp_board.push(move)
if i % 2 == 0: san_list.append(f"{i//2 + 1}.{san}")
else: san_list.append(san)
return " ".join(san_list)
except: return "Moves unavailable"
def draw_chevron(self, screen, color, center, pointing_down=True, size=6):
x, y = center
if pointing_down:
points = [(x-size, y-size//2), (x, y+size//2), (x+size, y-size//2)]
else: # Pointing Right
points = [(x-size//2, y-size), (x+size//2, y), (x-size//2, y+size)]
pygame.draw.lines(screen, color, False, points, 2)
def draw(self, screen, fb, fm):
surf = pygame.Surface((self.app.width, self.app.height), pygame.SRCALPHA)
surf.fill((0, 0, 0, 120))
screen.blit(surf, (0, 0))
pygame.draw.rect(screen, (252, 252, 252), self.rect, border_radius=12)
pygame.draw.rect(screen, (200, 200, 200), self.rect, 1, border_radius=12)
screen.blit(self.font_title.render("Opening & Mates Trainer", True, (40, 40, 40)), (self.rect.x + 25, self.rect.y + 20))
# Tabs
tab_y = self.rect.y + 60
self.btn_tab_openings = pygame.Rect(self.rect.x + 25, tab_y, 140, 35)
col_op = THEME["accent"] if self.tab == "openings" else (220, 220, 220)
pygame.draw.rect(screen, col_op, self.btn_tab_openings, border_radius=6)
screen.blit(fm.render("Openings", True, (255,255,255) if self.tab=="openings" else (0,0,0)), (self.btn_tab_openings.x+35, self.btn_tab_openings.y+8))
self.btn_tab_mates = pygame.Rect(self.rect.x + 175, tab_y, 140, 35)
col_mt = THEME["accent"] if self.tab == "mates" else (220, 220, 220)
pygame.draw.rect(screen, col_mt, self.btn_tab_mates, border_radius=6)
screen.blit(fm.render("Mates", True, (255,255,255) if self.tab=="mates" else (0,0,0)), (self.btn_tab_mates.x+45, self.btn_tab_mates.y+8))
# Search Bar
screen.blit(self.font_group.render("Search:", True, (100, 100, 100)), (self.rect.right - 260, tab_y + 8))
search_rect = pygame.Rect(self.rect.right - 190, tab_y + 2, 160, 30)
pygame.draw.rect(screen, (255, 255, 255), search_rect, border_radius=4)
pygame.draw.rect(screen, (180, 180, 180), search_rect, 1, border_radius=4)
txt_surf = self.font_var.render(self.filter_text, True, (0, 0, 0))
screen.blit(txt_surf, (search_rect.x + 8, search_rect.y + 5))
self.cursor_timer += 1
if (self.cursor_timer // 30) % 2 == 0:
cx = search_rect.x + 10 + txt_surf.get_width()
pygame.draw.line(screen, (0,0,0), (cx, search_rect.y + 6), (cx, search_rect.bottom - 6), 2)
close_rect = pygame.Rect(self.rect.right - 40, self.rect.y + 20, 24, 24)
if self.close_icon: screen.blit(self.close_icon, close_rect)
else: screen.blit(self.font_group.render("X", True, (100, 100, 100)), (close_rect.x + 5, close_rect.y))
self.click_zones = [((close_rect, 'close', None))]
content_rect = pygame.Rect(self.rect.x + 10, self.rect.y + 110, self.rect.width - 20, self.rect.height - 120)
if not self.groups:
msg = "Loading Openings from ECO.pgn..." if self.tab == "openings" else "Loading Mates from file..."
screen.blit(fm.render(msg, True, (150, 150, 150)), (self.rect.centerx - 120, self.rect.centery))
return
clip_rect = screen.get_clip()
screen.set_clip(content_rect)
y_off = -self.scroll_y
f_text = self.filter_text.lower()
for group in sorted(self.groups.keys()):
matching_vars = [v for v in self.groups[group] if f_text in v['name'].lower() or f_text in group.lower()]
if f_text and not matching_vars: continue
grp_height = 45
grp_rect = pygame.Rect(content_rect.x + 10, content_rect.y + y_off, content_rect.width - 30, grp_height)
is_expanded = group in self.expanded_groups or f_text != ""
if y_off + grp_height > 0 and y_off < content_rect.height:
m_pos = pygame.mouse.get_pos()
is_hover = grp_rect.collidepoint(m_pos)
bg_col = (235, 235, 240) if is_hover else (245, 245, 245)
pygame.draw.rect(screen, bg_col, grp_rect, border_radius=8)
pygame.draw.rect(screen, (220, 220, 230), grp_rect, 1, border_radius=8)
txt = self.font_group.render(group, True, (30, 30, 30))
screen.blit(txt, (grp_rect.x + 35, grp_rect.y + 12))
chev_pos = (grp_rect.x + 20, grp_rect.y + 22)
self.draw_chevron(screen, (100, 100, 100), chev_pos, pointing_down=is_expanded)
self.click_zones.append((grp_rect, 'group', group))
y_off += grp_height + 5
if is_expanded:
for var in matching_vars:
moves_str = var['moves_str']
words = moves_str.split()
lines = []
curr_line = ""
max_w = content_rect.width - 70
# --- FIX: Increased margin to prevent text overlapping the buttons! ---
max_w = content_rect.width - 320
for w in words:
if self.font_moves.size(curr_line + w)[0] < max_w:
curr_line += w + " "
else:
lines.append(curr_line)
curr_line = w + " "
lines.append(curr_line)
text_h = len(lines) * 16
item_h = max(55, 30 + text_h + 10)
var_rect = pygame.Rect(content_rect.x + 25, content_rect.y + y_off, content_rect.width - 45, item_h)
if y_off + item_h > 0 and y_off < content_rect.height:
m_pos = pygame.mouse.get_pos()
is_hover = var_rect.collidepoint(m_pos)
bg_col = (240, 245, 255) if is_hover else (255, 255, 255)
pygame.draw.rect(screen, bg_col, var_rect, border_radius=6)
if is_hover:
pygame.draw.rect(screen, (180, 200, 240), var_rect, 1, border_radius=6)
else:
pygame.draw.rect(screen, (230, 230, 230), var_rect, 1, border_radius=6)
v_name = self.font_var.render(var['name'], True, (50, 50, 50))
screen.blit(v_name, (var_rect.x + 10, var_rect.y + 8))
my = var_rect.y + 32
for line in lines:
l_surf = self.font_moves.render(line, True, (100, 100, 100))
screen.blit(l_surf, (var_rect.x + 10, my))
my += 16
# --- NEW: Tutorial & Practice Buttons ---
btn_tut = pygame.Rect(var_rect.right - 220, var_rect.y + (item_h - 36)//2, 95, 36)
col_tut = (240, 140, 50) if btn_tut.collidepoint(m_pos) else (230, 130, 40)
pygame.draw.rect(screen, col_tut, btn_tut, border_radius=6)
t_tut = self.app.font_s.render("Tutorial", True, (255,255,255))
screen.blit(t_tut, (btn_tut.centerx - t_tut.get_width()//2, btn_tut.centery - t_tut.get_height()//2))
btn_prac = pygame.Rect(var_rect.right - 110, var_rect.y + (item_h - 36)//2, 95, 36)
col_prac = (60, 190, 60) if btn_prac.collidepoint(m_pos) else (50, 170, 50)
pygame.draw.rect(screen, col_prac, btn_prac, border_radius=6)
t_prac = self.app.font_s.render("Practice", True, (255,255,255))
screen.blit(t_prac, (btn_prac.centerx - t_prac.get_width()//2, btn_prac.centery - t_prac.get_height()//2))
self.click_zones.append((btn_tut, 'start_tut', var['data']))
self.click_zones.append((btn_prac, 'start_prac', var['data']))
y_off += item_h + 5
self.max_scroll = max(0, y_off + self.scroll_y - content_rect.height)
screen.set_clip(clip_rect)
def handle_scroll(self, event):
if event.button == 4: self.scroll_y = max(0, self.scroll_y - 40)
elif event.button == 5: self.scroll_y = min(self.max_scroll, self.scroll_y + 40)
def handle_click(self, pos):
if self.btn_tab_openings and self.btn_tab_openings.collidepoint(pos):
self.tab = "openings"; self.scroll_y = 0; self.load_data(); return
if self.btn_tab_mates and self.btn_tab_mates.collidepoint(pos):
self.tab = "mates"; self.scroll_y = 0; self.load_data(); return
for rect, type_, data in self.click_zones:
if rect.collidepoint(pos):
if type_ == 'close':
self.active = False
self.app.mode_idx = 0
self.app.mode = "manual"
self.app.status_msg = "Mode: Manual (PvP)"
self.app.active_bot = None
elif type_ == 'group':
if data in self.expanded_groups: self.expanded_groups.remove(data)
else: self.expanded_groups.add(data)
elif type_ == 'start_tut':
from popups import TrainerSideSelectionPopup
self.app.side_popup = TrainerSideSelectionPopup(self.app, data, is_tutorial=True)
self.app.side_popup.active = True
elif type_ == 'start_prac':
from popups import TrainerSideSelectionPopup
self.app.side_popup = TrainerSideSelectionPopup(self.app, data, is_tutorial=False)
self.app.side_popup.active = True
return
def handle_input(self, event):
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
self.active = False
self.app.mode_idx = 0
self.app.mode = "manual"
self.app.status_msg = "Mode: Manual (PvP)"
self.app.active_bot = None
elif event.key == pygame.K_BACKSPACE:
self.filter_text = self.filter_text[:-1]
else:
self.filter_text += event.unicode
class ChessApp:
def __init__(self):
pygame.init()
pygame.key.set_repeat(300, 40) # <-- NEW: Enables continuous key-hold typing/backspacing
self.sound_manager = SoundManager()
self.root = tk.Tk(); self.root.withdraw()
self.running = True
# Initialize in fullscreen mode using the monitor's native resolution
self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN | pygame.DOUBLEBUF | pygame.HWSURFACE, vsync=1)
self.width, self.height = self.screen.get_size()
self.is_fullscreen = True # <-- FIX: Attached to self instead of self.screen
self.logical_width, self.logical_height = 1400, 1000
pygame.display.set_caption("Chess Studio Pro")
try: pygame.display.set_icon(pygame.image.load("assets/icons/main.png"))
except: pass
# Core State
self.mode = "play" # play, manual, trainer, puzzle
self.board_style = "wood"
self.history = []
self.view_ply = 0
self.arrows = []
self.user_arrows = [] # Right-Click Arrows
self.eval_val = 0.0
self.real_time_score = "+0.0"
self.status_msg = "Ready"
self.opening_name = "Starting Position"
self.white_opening = "Starting Position"
self.black_opening = "Starting Position"
self.chat_log = []
self.chat_scroll = 0
self.show_hints = False
self.pgn_headers = {}
self.cached_review = None
self.active_puzzle = None
self.multi_arrows = [] # NEW: To store multiple engine PV arrows
self.show_threats = False # Toggle for threat arrows display
# Trainer State
self.trainer_moves = []
self.trainer_idx = 0
self.trainer_hint_arrow = None
# Config
# 'show_threats' removed from settings (feature kept internal but no UI toggle)
self.settings = {"sound": True, "theme": "wood", "speech": True, "live_annotations": True}
self.active_bot = BOTS[0]
self.playing_white = True
self.mode_idx = 1
self.current_engine_info = {"name": "Stockfish Default", "path": ""}
if not self.current_engine_info.get("path") and hasattr(self, "assets") and self.assets.engines:
default = self.assets.engines[0]
self.current_engine_info["name"] = default["name"]
self.current_engine_info["path"] = default["path"]
print(f"[Engine Auto-Select] Using {default['name']} @ {default['path']}")
# Input/UI State
self.selected = None
self.valid_moves = []
self.btn_rects = {}
self.scroll_hist = 0
self.move_click_zones = []
self.ui_queue = []
self.lock = threading.Lock()
self.speech_queue = queue.Queue()
# Engine Fail-Safe
self.engine_crash_count = 0
# Performance optimization state
self.dirty_rects = []
self.static_board_surface = None
self.static_pieces_surface = None
self.last_board_state = None
self.animation_active = False
self.target_fps = 144
self.static_fps = 30
self.needs_full_redraw = True
# Animation/Drag/RightClick
self.dragging_piece = None
self.drag_pos_Rect = pygame.Rect(0, 0, 0, 0)
self.threat_arrow = None
self.right_click_start = None
self.temp_arrow_start = None
self.temp_arrow_end = None
# Pre-move system
self.pre_move = None # (from_sq, to_sq) queued while bot thinks
self.pre_move_promotion = None
self.pre_move_queue = [] # List of (from_sq, to_sq, promo) for chained premoves
# Move time tracking
self._last_move_time = None
self._last_move_time_delta = 0.0
# Popups
self.active_popup = None
self.review_popup = None; self.bot_popup = None; self.promo_popup = None
self.side_popup = None; self.pgn_popup = None; self.gm_move_popup = None
self.save_popup = None; self.settings_popup = None; self.trainer_popup = None
self.engine_popup = None; self.phase_popup = None; self.puzzle_popup = None
self.save_mate_popup = None
self.trainer_complete_popup = None
self.fast_import_popup = None
self.unsaved_popup = None
self.unsaved_analysis = False
self.current_pgn_path = None
# Enhanced features initialization
self.account_popup = None
self.add_account_popup = None
self.complexity_popup = None
self.chat_messages = []
self.current_depth = 0
self.max_depth = 20
self.nodes_per_second = 0
self.engine_status = 'Ready'
self.is_analyzing = False
self.network_status = 'offline'
self.last_move_analysis = None
self.clock = pygame.time.Clock()
self.font_s = pygame.font.SysFont("Segoe UI", 14)
self.font_m = pygame.font.SysFont("Segoe UI", 16)
self.font_b = pygame.font.SysFont("Segoe UI", 20, bold=True)
self.font_chat = pygame.font.SysFont("Segoe UI", 14)
self.font_huge = pygame.font.SysFont("Segoe UI", 60, bold=True)
self.font_mono = pygame.font.SysFont("Consolas", 14)
_saved_piece_set = "default"
try:
import json as _json
with open("settings.json", "r") as _f:
_saved_piece_set = _json.load(_f).get("piece_set", "infinix")
except Exception:
pass
self.assets = AssetLoader(piece_set_name=_saved_piece_set)
self.load_config()
self.renderer = UIRenderer(self)
# --- ADDED: Grandmaster Database Explorer ---
self.explorer_db = OpeningExplorer("assets/database/explorer.sqlite")
self.explorer_ui = ExplorerUI(font_small=self.font_s, font_medium=self.font_m)
# --- FIX: Load Stockfish Icon for the Chat Box ---
try:
icon_path = os.path.join("assets", "bots", "stockfish.png")
self.stockfish_icon = pygame.transform.smoothscale(pygame.image.load(icon_path).convert_alpha(), (30, 30))
except Exception as e:
print(f"Could not load Stockfish icon: {e}")
self.stockfish_icon = None
# -------------------------------------------------
if game_logic: self.logic = game_logic.GameLogic(); self.board = self.logic.board
else: self.logic = None; self.board = chess.Board()
# --- NEW: Profile & Archive System ---
self.archive_dir = os.path.join("assets", "archive")
if not os.path.exists(self.archive_dir):
os.makedirs(self.archive_dir)
self.ledger_path = os.path.join("assets", "match_history.json")
self.match_ledger = []
if os.path.exists(self.ledger_path):
try:
with open(self.ledger_path, "r", encoding="utf-8") as f:
self.match_ledger = json.load(f)
except Exception as e: print(f"Ledger load error: {e}")
self.practice_ledger_path = os.path.join("assets", "practice_history.json")
self.practice_ledger = []
if os.path.exists(self.practice_ledger_path):
try:
with open(self.practice_ledger_path, "r", encoding="utf-8") as f:
self.practice_ledger = json.load(f)
except Exception as e: print(f"Practice Ledger load error: {e}")
self.import_status = "" # For the Profile loading bar
self.profile_popup = None # Will hold the UI
# --- FIX: Initialize Player Elo from settings (default to 400 if new) ---
self.player_elo = self.settings.get("player_elo", 400)
self.settings["player_elo"] = self.player_elo
# Initial Engine Setup
self.init_engine()
# Initialize enhanced managers AFTER engine is set up
try:
from account_manager import ChessAccountManager, GameChatAnalyzer, NetworkStatusMonitor
self.account_manager = ChessAccountManager()
self.chat_analyzer = GameChatAnalyzer(self.analyzer) if hasattr(self, 'analyzer') and self.analyzer else None
self.network_monitor = NetworkStatusMonitor()
except ImportError as e:
print(f"Enhanced features not available: {e}")
self.account_manager = None
self.chat_analyzer = None
self.network_monitor = None
# Start Threads
threading.Thread(target=self.tts_worker, daemon=True).start()
threading.Thread(target=self.task_analysis, daemon=True).start()
threading.Thread(target=self.task_play, daemon=True).start()
self.add_chat("System", f"Welcome! Playing against {self.active_bot['name']}.")
self.calc_layout()
self.sound_manager.play("game_start")
self.side_popup = SideSelectionPopup(self, BOTS[0])
self.side_popup.active = True
def load_config(self):
try:
with open("settings.json", "r") as f:
data = json.load(f)
self.settings.update(data) # Merge saved data into defaults
self.board_style = self.settings.get("board_style", "wood")
except:
self.board_style = "wood"
# Initialize Player Elo safely right as the app starts
self.player_elo = self.settings.get("player_elo", 400)
# Restore dark theme if it was previously enabled
if self.settings.get("dark_theme", False):
THEME["bg"] = (28, 28, 32)
THEME["panel"] = (38, 38, 44)
THEME["text"] = (220, 220, 225)
THEME["text_dim"] = (140, 140, 150)
THEME["border"] = (60, 60, 70)
# --- FIX: Restore Engine Configurations from settings.json ---
self.max_depth = self.settings.get("engine_depth", 20)
self.engine_threads = self.settings.get("engine_threads", 4)
self.engine_hash = self.settings.get("engine_hash", 512)
self.engine_multipv = self.settings.get("engine_multipv", 3)
self.use_cloud_analysis = self.settings.get("use_cloud_analysis", True)
# Restore piece set from settings
saved_piece_set = self.settings.get("piece_set", "infinix")
if hasattr(self, 'assets') and saved_piece_set != "default":
self.assets.piece_set_name = saved_piece_set
self.assets.load_piece_set(saved_piece_set)
def apply_piece_set(self, set_name):
"""Loads a piece set by name, resets scaled cache, and saves to settings."""
self.assets.piece_set_name = set_name
self.assets.load_piece_set(set_name)
self.settings["piece_set"] = set_name
# Invalidate the renderer's scaled piece cache so it rescales the new set
if hasattr(self, 'renderer'):
self.renderer.scaled = {}
self.renderer.needs_full_redraw = True
# Force static board layer rebuild
self.static_pieces_surface = None
self.static_board_surface = None
self.save_config()
self.status_msg = f"Piece Set: {set_name.capitalize()}"
def save_config(self):
try:
# Sync variables before saving
self.settings["board_style"] = self.board_style
self.settings["player_elo"] = getattr(self, 'player_elo', 1200)
# --- FIX: Ensure Engine Configurations are synced before saving ---
self.settings["engine_depth"] = getattr(self, 'max_depth', 20)
self.settings["engine_threads"] = getattr(self, 'engine_threads', 4)
self.settings["engine_hash"] = getattr(self, 'engine_hash', 512)
self.settings["engine_multipv"] = getattr(self, 'engine_multipv', 3)
self.settings["use_cloud_analysis"] = getattr(self, 'use_cloud_analysis', True)
with open("settings.json", "w") as f:
json.dump(self.settings, f, indent=4)
except Exception as e:
print(f"Save config error: {e}")
def fast_load_pgn_to_ui(self, path, offset=0):
"""Instantly loads an already-analyzed PGN directly to the UI and Review Panel."""
import threading
# --- NEW: Launch the Loading Popup ---
self.fast_import_popup = FastImportLoadingPopup(self)
self.fast_import_popup.active = True
def update_progress(pct, text="Fast Importing Game..."):
if hasattr(self, 'fast_import_popup') and self.fast_import_popup:
self.fast_import_popup.progress = pct
self.fast_import_popup.status_text = text
def worker():
try:
if not self.analyzer:
self.status_msg = "Error: Engine not loaded. Cannot analyze."
time.sleep(2)
self.status_msg = ""
if self.fast_import_popup: self.fast_import_popup.active = False
return
self.status_msg = "Running Fast Import..."
self.current_pgn_path = path
with open(path, "r", encoding="utf-8") as f:
f.seek(offset)
g = chess.pgn.read_game(f)
if not g:
if self.fast_import_popup: self.fast_import_popup.active = False
return
mainline = list(g.mainline())
# --- Execute the fast parser with progress tracking ---
res = self.analyzer.fast_analyze_full_game(mainline, progress_callback=update_progress)
if res:
h, s, r, graph, bf = res
with self.lock:
self.board.reset()
for h_item in h:
self.board.push(h_item["move"])
self.history = h
self.view_ply = len(self.history)
self.mode = "review"
# --- FIX: Switch to Manual Mode so the bot doesn't auto-play ---
self.mode_idx = 0
self.active_bot = None
# ---------------------------------------------------------------
# --- FIX: Update the game headers so names change! ---
self.pgn_headers = dict(g.headers)
# -----------------------------------------------------
self.stats = s
self.ratings = r
self.graph_surface = graph
self.cached_review = (h, s, r, graph, bf)
if hasattr(self, 'logic'):
self.logic.board = self.board.copy()
self.logic.history = [dict(hi) for hi in h]
self.logic.view_ply = self.view_ply
if bf:
from popups import SaveMatePopup
self.save_mate_popup = SaveMatePopup(self, bf)
self.save_mate_popup.active = True
self.unsaved_analysis = True
self.status_msg = "Fast Import Complete"
self.sound_manager.play("game_start")
except Exception as e:
print(f"Fast Load Error: {e}")
self.status_msg = "Import Failed"
finally:
if hasattr(self, 'fast_import_popup') and self.fast_import_popup:
self.fast_import_popup.active = False
threading.Thread(target=worker, daemon=True).start()
def init_engine(self, custom_path=None):
# --- FIX: Prevent double/concurrent initialization ---
if getattr(self, '_is_initializing', False): return
self._is_initializing = True
try:
# --- FIX: Cleanup existing engines properly before restart ---
if hasattr(self, 'analyzer') and self.analyzer:
try: self.analyzer.stop()
except: pass
if hasattr(self, 'eng_play') and self.eng_play:
try:
self.eng_play.quit()
# Give it a moment to release file/process locks
time.sleep(0.1)
except: pass
self.analyzer = None
self.eng_play = None
self.last_bot_config = None
# 1. Determine Path
path = custom_path
if not path:
path = self.find_engine()
# 2. Check if path exists (Bypass for Lichess Cloud)
if not path or (path != "lichess_cloud" and not os.path.exists(path)):
print("WARNING: No valid engine path found. Defaulting to Manual Mode.")
self.mode = "manual"
self.status_msg = "No Engine - Manual Mode"
self.add_chat("System", "Engine not found. Switched to Manual Mode.")
return
print(f"DEBUG: Attempting to load engine from: {path}")
self.current_engine_info["path"] = path
# Properly name the virtual engine so it displays correctly in the UI
if path == "lichess_cloud":
self.current_engine_info["name"] = "Lichess Cloud API"
else:
self.current_engine_info["name"] = os.path.basename(path).replace(".exe","")
# 3. Initialize Analysis Engine (Safe Mode)
if analysis_engine:
try:
self.analyzer = analysis_engine.AnalysisEngine(
path,
opening_book=self.assets.openings,
book_positions=self.assets.book_positions,
threads=getattr(self, 'engine_threads', 4),
hash_size=getattr(self, 'engine_hash', 512)
)
success = self.analyzer.start()
if not success:
print("Analysis Engine failed to start.")
self.analyzer = None
except Exception as e:
print(f"Analysis Engine Init Exception: {e}")
self.analyzer = None
# 4. Initialize Playing Engine (Safe Mode)
try:
if path == "lichess_cloud":
self.eng_play = "lichess_cloud" # Safely bypass executable logic
else:
# On Windows, suppress the console window
if sys.platform == "win32":
self.eng_play = chess.engine.SimpleEngine.popen_uci(path, creationflags=0x08000000)
else:
self.eng_play = chess.engine.SimpleEngine.popen_uci(path)
# Configure Syzygy if present
if self.assets.path_syzygy and os.path.isdir(self.assets.path_syzygy):
try: self.eng_play.configure({"SyzygyPath": self.assets.path_syzygy})
except: pass
# Use User Settings for Live Engine
try:
self.eng_play.configure({
"Threads": getattr(self, 'engine_threads', 4),
"Hash": getattr(self, 'engine_hash', 512)
})
except: pass
# --- NNUE AUTO-DETECTION (Live Engine) ---
base_name = os.path.splitext(os.path.basename(path))[0]
nnue_path = os.path.join(os.path.dirname(path), "nnue", f"{base_name}.nnue")
if os.path.exists(nnue_path) and hasattr(self.eng_play, 'options'):
try:
opts = self.eng_play.options
nnue_config = {}
# Dynamically match the engine's expected keys
if "Use NNUE" in opts: nnue_config["Use NNUE"] = True
elif "Use_NNUE" in opts: nnue_config["Use_NNUE"] = True
if "EvalFile" in opts: nnue_config["EvalFile"] = nnue_path
elif "NNUENetpath" in opts: nnue_config["NNUENetpath"] = nnue_path
if nnue_config:
self.eng_play.configure(nnue_config)
print(f"[*] Live Engine NNUE Loaded: {base_name}.nnue")
except Exception as e:
print(f"[*] Live NNUE skipped: {e}")
except Exception as e:
print(f"Playing Engine Init Error: {e}")
self.eng_play = None
# --- RECOVERY MECHANISM ---
print("Trying to recover by asking user for a valid engine...")
new_path = self.find_engine(force_dialog=True)
if new_path and new_path != path:
# Clear initializing flag so the retry isn't blocked
self._is_initializing = False
self.init_engine(new_path)
return
else:
# User cancelled or same path failed; break the loop
self.mode = "manual"
self.status_msg = "Engine Load Cancelled."
self.mode = "manual"
self.status_msg = "Engine Failed - Manual Mode"
self.add_chat("System", "Engine failed to load. Manual Mode active.")
finally:
# Always release the lock when done
self._is_initializing = False
def find_engine(self, force_dialog=False):
"""
Locates the Stockfish executable.
Priority:
1. Common local paths.
2. Assets folder lists.
3. Ask the user via File Dialog.
"""
if not force_dialog:
# Common locations to check
priority_list = [
"stockfish.exe",
"engines/stockfish.exe",
"bin/stockfish.exe",
"stockfish_16.exe",
"engines/stockfish_16.exe",
r"C:\stockfish\stockfish.exe" # Common Windows path
]
# 1. Check Priority List
for p in priority_list:
if os.path.exists(os.path.abspath(p)):
return os.path.abspath(p)
# 2. Check Assets detected engines
if self.assets.engines:
for eng in self.assets.engines:
if "stockfish" in eng["name"].lower() and os.path.exists(eng["path"]):
return eng["path"]
if os.path.exists(self.assets.engines[0]["path"]):
return self.assets.engines[0]["path"]
# 3. Last Resort: Ask User
try:
# FIX: Iconify fullscreen pygame window so the OS dialog appears on top
pygame.display.iconify()
if self.root:
self.root.update()
print("Prompting user for Stockfish executable...")
file_path = filedialog.askopenfilename(
title="Select Stockfish Engine (stockfish.exe)",
filetypes=[("Executable", "*.exe"), ("All Files", "*.*")]
)
if self.root:
self.root.withdraw()
pygame.event.clear()
if file_path and os.path.exists(file_path):
return file_path
except Exception as e:
print(f"Error opening file dialog: {e}")
return None
def change_engine(self, engine_data):
self.status_msg = "Switching Engine..."
if self.analyzer: self.analyzer.stop()
if self.eng_play:
if self.eng_play != "lichess_cloud":
try: self.eng_play.quit()
except: pass
self.last_bot_config = None # FIX: Reset configuration cache so the new engine initializes!
self.init_engine(engine_data["path"])
self.status_msg = f"Loaded {self.current_engine_info['name']}"
self.cached_review = None
def calc_layout(self):
w, h = self.width, self.height
self.r_eval = pygame.Rect(10, 20, 30, h-40)
aw = w - 550; ah = h - 60
self.sq_sz = min(aw//8, ah//8)
self.bd_sz = self.sq_sz * 8
self.bd_x = 80; self.bd_y = (h - self.bd_sz) // 2
self.sb_x = self.bd_x + self.bd_sz + 40; self.sb_w = w - self.sb_x - 20
self.renderer.rescale_pieces()
def update_opening_label(self):
if not hasattr(self.assets, 'openings') or not self.assets.openings:
return
temp = chess.Board()
w_book = "Starting Position"
b_book = "Starting Position"
w_in_book = True
b_in_book = True
# Trace the game to find the deepest known opening name for EACH side
for i in range(self.view_ply):
step = self.history[i]
move = step["move"] if isinstance(step, dict) else step
temp.push(move)
name = self.assets.get_opening_name(temp.fen())
if i % 2 == 0: # White's turn just resulted in this position
if name and "Unknown" not in name:
w_book = name
w_in_book = True
else:
w_in_book = False
else: # Black's turn just resulted in this position
if name and "Unknown" not in name:
b_book = name
b_in_book = True
else:
b_in_book = False
# Set the generic overall name
self.opening_name = w_book if self.view_ply % 2 != 0 else b_book
# Assign independent labels
if self.view_ply == 0:
self.white_opening = "Starting Position"
self.black_opening = "Starting Position"
elif self.view_ply == 1:
self.white_opening = w_book if w_in_book else f"{w_book} *"
self.black_opening = "Waiting..."
else:
self.white_opening = w_book if w_in_book else f"{w_book} *"
self.black_opening = b_book if b_in_book else f"{b_book} *"
# --- THREADS ---
# --- THREADS ---
def tts_worker(self):
"""Plays TTS natively and offline using pyttsx3 with dynamic accents."""
import time
import queue
try:
import pyttsx3
except ImportError:
print("[AUDIO THREAD] pyttsx3 not installed. Please run: pip install pyttsx3")
return
print("\n[AUDIO THREAD] Starting local pyttsx3 engine loop...")
# ---------------------------------------------------------
# THE BOT PERSONA MATRIX (Speed-Adjusted)
# Maps bot names to their specific voice index and speed
# ---------------------------------------------------------
bot_personas = {
"Spark": {"index": 11, "rate": 160}, # Mark (US) - Energetic but clear
"Cassidy": {"index": 2, "rate": 140}, # Linda (CA) - Safe, friendly female
"Byte": {"index": 1, "rate": 150}, # James (AU) - Confident, upbeat Australian
"Vincent": {"index": 0, "rate": 125}, # David (US) - Very slow, hesitant learner
"Oliver": {"index": 10, "rate": 140}, # David (US) - Standard, balanced
"Arthur": {"index": 7, "rate": 155}, # Sean (IE) - Aggressive, punchy Irish
"Niles": {"index": 4, "rate": 155}, # George (UK) - Fast, aggressive British
"Nova": {"index": 5, "rate": 135}, # Hazel (UK) - Calm, passive
"Eleanor": {"index": 6, "rate": 125}, # Susan (UK) - Very measured, slow defender
"Armando": {"index": 3, "rate": 145}, # Richard (CA) - Sharp, tactical
"Veda": {"index": 8, "rate": 135}, # Heera (IN) - Calculating Indian female
"Catherine":{"index": 14, "rate": 140}, # Catherine (AU) - Crisp Australian historian
"Maximus": {"index": 9, "rate": 130}, # Ravi (IN) - Deep, authoritative Grandmaster
"Stockfish":{"index": 12, "rate": 165}, # Zira (US) - Brisk, robotic female
"Checkmate Master": {"index": 4, "rate": 160} # George (UK) - Intense assassin
}
while getattr(self, 'running', True):
try:
try:
text, bot_name = self.speech_queue.get(timeout=0.1)
except queue.Empty:
continue
print(f"\n[AUDIO THREAD] Speaking line: {text[:40]}...")
# --- THE FIX: INITIALIZE INSIDE THE LOOP ---
tts_engine = pyttsx3.init()
voices = tts_engine.getProperty('voices')
total_voices = len(voices)
# Fetch persona (Default to David US if bot isn't found)
persona = bot_personas.get(bot_name, {"index": 0, "rate": 150})
# SAFETY CHECK: If someone clones your GitHub repo and only has 3 voices,
# this prevents the app from crashing by wrapping the index back to 0.
safe_index = persona["index"] if persona["index"] < total_voices else (persona["index"] % max(1, total_voices))
# Apply the specific voice and speed
try:
tts_engine.setProperty('voice', voices[safe_index].id)
tts_engine.setProperty('rate', persona["rate"])
except Exception:
pass # Fallback to system default if property fails
# Speak!
tts_engine.say(text)
tts_engine.runAndWait()
# --- THE FIX: DESTROY ENGINE AFTER SPEAKING ---
del tts_engine
except Exception as e:
print(f"[AUDIO ERROR] Loop crashed: {e}")
time.sleep(1)
def start_ranked_match(self):
"""Finds a bot near the player's Elo and starts a ranked match."""
# Get BOTS directly from the global import at the top of main.py
from assets import BOTS
# Use the persistent Elo from Settings
player_elo = getattr(self, "player_elo", 1200)
# Filter for standard bots within +/- 150 Elo
valid_bots = [b for b in BOTS if b.get("type") != "book" and abs(b.get("elo", 1200) - player_elo) <= 150]
# Failsafe: If no bots perfectly match the range, pick the absolutely closest one
if not valid_bots:
valid_bots = [min(BOTS, key=lambda b: abs(b.get("elo", 1200) - player_elo) if b.get("type") != "book" else 9999)]
selected_bot = random.choice(valid_bots)
# Randomize Color (Standard Ranked Rule)
play_as_white = random.choice([True, False])