Repository navigation
Expand file tree
/
Copy pathpython_easy_chess_gui.py
More file actions
10324 lines (9239 loc) · 459 KB
/
Copy pathpython_easy_chess_gui.py
File metadata and controls
10324 lines (9239 loc) · 459 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
#!/usr/bin/env python3
"""
python_easy_chess_gui.py
Requirements:
Python 3.8 and up
PySimpleGUI Square Mapping
board = [
56, 57, ... 63
...
8, 9, ...
0, 1, 2, ...
]
row = [
0, 0, ...
1, 1, ...
...
7, 7 ...
]
col = [
0, 1, 2, ... 7
0, 1, 2, ...
...
0, 1, 2, ... 7
]
Python-Chess Square Mapping
board is the same as in PySimpleGUI
row is reversed
col is the same as in PySimpleGUI
"""
import FreeSimpleGUI as sg
import os
import sys
import subprocess
import threading
from pathlib import Path, PurePath # Python 3.4 and up
import queue
import copy
import time
from datetime import datetime
import json
import chess
import chess.pgn
import chess.engine
import chess.polyglot
import logging
import webbrowser
import re
import tkinter as tk
import tkinter.font as tkfont
from tkinter import filedialog
import platform as sys_plat
log_format = '%(asctime)s :: %(funcName)s :: line: %(lineno)d :: %(levelname)s :: %(message)s'
logging.basicConfig(
filename='pecg_log.txt',
filemode='w',
level=logging.INFO,
format=log_format
)
# python-chess logs every UCI line exchanged with the engine at DEBUG level.
# During live (infinite/long) analysis this floods pecg_log.txt with thousands
# of lines and adds constant disk I/O, so keep the engine-communication logger
# quiet regardless of the root level.
logging.getLogger('chess.engine').setLevel(logging.WARNING)
APP_NAME = 'Python Easy Chess GUI'
APP_VERSION = 'v3.0.0'
BOX_TITLE = f'{APP_NAME} {APP_VERSION}'
REVIEW_MAX_DISPLAY_GAMES = 10000
REVIEW_ANALYSIS_MULTIPV_LINES = 3 # lines of analysis, until changed
REVIEW_ANALYSIS_MULTIPV_MAX = 10 # most lines the Analysis panel offers
# Hash sizes in MB offered by the Analysis and Threat panels (those the
# engine accepts, plus the size it has now).
REVIEW_HASH_CHOICES_MB = [16, 32, 64, 128, 256, 512, 1024, 2048, 4096,
8192, 16384]
# Colour of the line of search figures (depth, time, nodes) in the
# Analysis and Threat boxes; readable on light and dark themes.
REVIEW_INFO_COLOR = '#7a7f87'
REVIEW_NAV_DEBOUNCE_SEC = 0.3
REVIEW_MOVE_LIST_HEIGHT = 4 # lines, until its panel is made taller
REVIEW_GAME_LIST_ROWS = 4 # games, until its panel is made taller
# Columns of the Game list panel and their widths in characters. The
# first four fit a panel of the default width; the rest is reached with
# the scrollbar under the list, or by making the panel wider.
REVIEW_GAME_LIST_HEADINGS = ['#', 'White', 'Black', 'Result', 'Date', 'Event']
REVIEW_GAME_LIST_WIDTHS = [5, 14, 14, 8, 11, 16]
# Lines of the Analysis and Threat boxes until their panel is made
# taller: the search figures, then one line per variation.
REVIEW_ANALYSIS_BOX_HEIGHT = 1 + REVIEW_ANALYSIS_MULTIPV_LINES
REVIEW_THREAT_BOX_HEIGHT = 2
# Annotations (the $n codes of PGN, "NAGs") the Review move list shows
# and its right-click menu offers: (code, symbol, name). A move has at
# most one move annotation and one position annotation; any other code
# of a game is kept and shown as '$n'.
REVIEW_MOVE_NAGS = (
(1, '!', 'Good move'),
(2, '?', 'Mistake'),
(3, '!!', 'Brilliant move'),
(4, '??', 'Blunder'),
(5, '!?', 'Interesting move'),
(6, '?!', 'Dubious move'),
(7, '□', 'Only move'),
)
REVIEW_POSITION_NAGS = (
(10, '=', 'Equal position'),
(13, '∞', 'Unclear position'),
(14, '+=', 'White is slightly better'),
(15, '=+', 'Black is slightly better'),
(16, '+/-', 'White is better'),
(17, '-/+', 'Black is better'),
(18, '+-', 'White is winning'),
(19, '-+', 'Black is winning'),
)
REVIEW_NAG_SYMBOLS = {nag: symbol for nag, symbol, _
in REVIEW_MOVE_NAGS + REVIEW_POSITION_NAGS}
# The codes one choice of the menu replaces: move annotations are $1-$9,
# evaluations of the position $10-$21.
REVIEW_MOVE_NAG_GROUP = range(1, 10)
REVIEW_POSITION_NAG_GROUP = range(10, 22)
# Colour of a move in the move list by its move annotation, on a light
# and on a dark background: red for bad moves (strong for ??, light for
# ?), orange for dubious, purple for interesting, blue for good moves
# (light for !, strong for !!). When a game gives a move several, the
# first of this order colours it.
REVIEW_NAG_COLORS = {
'light': {4: '#d50000', 2: '#f0605a', 6: '#e07b00', 5: '#9c27b0',
3: '#0057d9', 1: '#3d9be9'},
'dark': {4: '#ff4d4d', 2: '#ffa3a3', 6: '#ffb347', 5: '#d9a0f2',
3: '#5aa2ff', 1: '#a3d2ff'},
}
# Other colours of the move list, light and dark background: comments,
# and the background of the variation the current move is in.
REVIEW_COMMENT_COLOR = {'light': 'green', 'dark': '#7fcf7f'}
REVIEW_VAR_BLOCK_COLOR = {'light': '#e2f0d9', 'dark': '#34453a'}
# File name offered the first time a game is saved in Review mode.
REVIEW_SAVE_FILE = 'pecg_my_games.pgn'
# Output file for games annotated by the Review-mode auto-analyzer.
AUTO_ANALYSIS_OUTPUT_FILE = 'pecg_analyzed_games.pgn'
# How many recently opened review PGN paths to remember in the settings.
MAX_RECENT_PGN_FILES = 10
# Length of a line replayed engine vs engine (AutoAnalyzeGame.
# _replay_variation). Not used for now: the "Better is" variation is the
# full line (PV) of the engine's search. The saved setting is kept.
AUTO_ANALYSIS_REPLAY_PLIES = 5
AUTO_ANALYSIS_REPLAY_PLIES_MIN = 1
AUTO_ANALYSIS_REPLAY_PLIES_MAX = 20
# Number of engine lines (MultiPV) of every search of the auto-analyzer.
# With two lines the game move often is one of them, which saves the
# search of its own score; and an engine asked for one line only can
# answer with a line of a single move.
AUTO_ANALYSIS_MULTIPV = 2
AUTO_ANALYSIS_MULTIPV_MAX = 5
# The engine's line is added as a "Better is" variation when its score
# beats the game move by at least this many centipawns (mover POV)...
AUTO_ANALYSIS_BETTER_MIN_CP = 25
# ...or by this many when the engine's score is within
# AUTO_ANALYSIS_BETTER_CLOSE_ABS_CP of equal: in a level position a small
# edge matters.
AUTO_ANALYSIS_BETTER_CLOSE_MIN_CP = 10
AUTO_ANALYSIS_BETTER_CLOSE_ABS_CP = 50
# Further than this from equal (mover POV) the position is decided, and
# the rule above adds no variation...
AUTO_ANALYSIS_BETTER_MAX_ABS_CP = 1000
# ...but a win that was missed is shown: when the engine's score is above
# that limit and the game move is worse by at least MISSED_WIN_MIN_CP,
# the engine's line is added with a mark on its first move: !! for a
# mate in MISSED_MATE_MOVES or fewer, ! for any other win. (A gap of a
# few centipawns between two winning moves is not a missed win.)
AUTO_ANALYSIS_MISSED_WIN_MIN_CP = 200
AUTO_ANALYSIS_MISSED_MATE_MOVES = 10
# Marks of a bad move, by what it loses against the engine's best move
# and by what is left after it (centipawns, mover POV):
# ?! loses at least DUBIOUS_LOSS
# ? loses at least MISTAKE_LOSS, and the mover is not losing after it
# ?? loses at least MISTAKE_LOSS, and the mover is losing after it
# 'Losing' is a score of -DECIDED or lower, 'winning' +DECIDED or higher.
# No mark at all while the mover is still winning after the move, or was
# losing already before it: throwing a win away to a level game is a
# mistake (?), not a blunder (??), and +9 to +5 is neither.
AUTO_ANALYSIS_DUBIOUS_LOSS_CP = 100
AUTO_ANALYSIS_MISTAKE_LOSS_CP = 200
AUTO_ANALYSIS_DECIDED_CP = 300
# Praise marks (! and !!) for a best move that stands out from the second
# line. Off: an obvious recapture stands out just as much.
AUTO_ANALYSIS_PRAISE = False
# What the auto-analyzer writes after the last move of its variation,
# before the engine name: tells the lines of different engines apart.
AUTO_ANALYSIS_ENGINE_MARK = '—'
# The part of the game the auto-analyzer works on, as the move numbers
# its dialog starts with: from the start move (the opening moves before
# it are skipped) to the end move, both included, White's and Black's
# move of that number. The end move is far beyond any game, so the
# analysis goes to the last move unless the user lowers it.
AUTO_ANALYSIS_START_MOVE = 4
AUTO_ANALYSIS_END_MOVE = 1000
AUTO_ANALYSIS_MOVE_MAX = 1000
# Auto-analysis time per move, in milliseconds. UCI engines are fine with
# very short searches, so the floor is 100 ms; the value is handed to the
# engine as a seconds float via chess.engine.Limit.
AUTO_ANALYSIS_TIME_MS = 1000
AUTO_ANALYSIS_TIME_MS_MIN = 100
AUTO_ANALYSIS_TIME_MS_MAX = 60000
# Time caps (seconds) for Review-mode searches. Without a cap these run
# "go infinite" and peg the CPU until the user navigates away. Editable via
# Settings/Game and persisted in the settings file.
REVIEW_ANALYSIS_TIME_SEC = 60 # default analysis time cap
REVIEW_THREAT_TIME_SEC = 30 # default threat time cap
REVIEW_ANALYSIS_TIME_MIN = 1
REVIEW_ANALYSIS_TIME_MAX = 3600
platform = sys.platform
sys_os = sys_plat.system()
# Consolas ships with Windows but not with stock Linux. Without a real monospace
# font, Tk silently falls back to a proportional one, which breaks the
# character-based right-edge alignment of the info panels (every element is sized
# in character units). Pick a monospace font that exists on each platform.
def _default_mono_font():
try:
temp_root = tk.Tk()
temp_root.withdraw()
import tkinter.font as tkfont
available = tkfont.families(temp_root)
temp_root.destroy()
if platform == 'win32':
preferred = ['Consolas', 'Courier New', 'Courier']
elif platform == 'darwin':
preferred = ['Menlo', 'Monaco', 'Courier New', 'Courier']
else:
preferred = ['DejaVu Sans Mono', 'Liberation Mono', 'Ubuntu Mono', 'Courier New', 'Courier', 'monospace']
for f in preferred:
if f in available:
return f
except Exception:
pass
if platform == 'win32':
return 'Consolas'
if platform == 'darwin':
return 'Menlo'
return 'DejaVu Sans Mono' # present on essentially every Linux desktop
FONT_NAME = _default_mono_font()
if platform == 'win32':
FONT_BASE = (FONT_NAME, 10)
FONT_SMALL = (FONT_NAME, 9)
elif platform == 'darwin':
FONT_BASE = (FONT_NAME, 10)
FONT_SMALL = (FONT_NAME, 9)
else:
FONT_BASE = (FONT_NAME, 9)
FONT_SMALL = (FONT_NAME, 8)
# Title bar of a panel.
FONT_PANEL_TITLE = (FONT_NAME, FONT_BASE[1], 'bold')
FONT_NAV_ICON = (FONT_NAME, FONT_BASE[1] + 4, 'bold') # Review nav bar
# Small font for the board coordinate labels drawn on the canvas.
# Board edge coordinate labels use FONT_NAME at a size scaled with the
# board (see paint_square).
# The top menu BAR font can't be set through FreeSimpleGUI (its font= only styles
# the drop-down submenus). The native Windows menubar uses Segoe UI 9; on Linux
# Tk draws the menubar itself with its own default (DejaVu Sans 10), so it looks
# bigger and a different family. Match Windows' size/class on Linux; leave the
# native menubar untouched elsewhere (None -> no change).
def _default_menu_font():
if platform == 'win32':
return None
if platform == 'darwin':
return None
return ('DejaVu Sans', 9)
MENU_FONT = _default_menu_font()
ico_path = {
'win32': {'pecg': 'Icon/pecg.ico', 'enemy': 'Icon/enemy.ico', 'adviser': 'Icon/adviser.ico'},
'linux': {'pecg': 'Icon/pecg.png', 'enemy': 'Icon/enemy.png', 'adviser': 'Icon/adviser.png'},
'darwin': {'pecg': 'Icon/pecg.png', 'enemy': 'Icon/enemy.png', 'adviser': 'Icon/adviser.png'}
}
MIN_DEPTH = 1
MAX_DEPTH = 1000
# Numbers in the setup dialogs are picked from drop-down lists or up/down
# arrows, never typed, so a dialog cannot be handed an invalid value. These
# are the choices offered. (Engine UCI options are the exception: their
# ranges are too wide for a list, so they stay typed and are validated.)
TC_BASE_MAX_MIN = 180 # base time: 0..180 minutes plus 0..59 seconds
TC_INC_MAX_SEC = 60 # increment: 0..60 seconds
MAX_BOOK_PLY = 32 # opponent book: 1..32 plies
DEPTH_CHOICE_MAX = 100 # Set Depth: 1..100, or no limit (MAX_DEPTH)
DEPTH_NO_LIMIT = 'No limit'
# Seconds offered for the review analysis/threat and adviser move times.
TIME_CHOICES_SEC = [1, 2, 3, 5, 10, 15, 20, 30, 45, 60, 90, 120, 180, 300,
600, 900, 1800, 3600]
# Milliseconds per move offered by the Auto-Analyze dialog.
AUTO_ANALYSIS_TIME_CHOICES_MS = [100, 200, 300, 500, 1000, 2000, 3000, 5000,
10000, 15000, 30000, 60000]
def choices_with(choices, current):
"""Return ``choices`` as a sorted list that also offers ``current``.
Keeps a previously saved value selectable when it is not one of the
standard choices.
"""
return sorted(set(choices) | {current})
# PGN files are written as UTF-8 on every platform. Without an explicit
# encoding Windows uses its legacy code page, which cannot store most
# non-English names and does not match what Review reads.
PGN_ENCODING = 'utf-8'
def pgn_file_encoding(path):
"""Return the encoding to read (and rewrite) an existing PGN file with.
UTF-8 when the whole file decodes as UTF-8. Otherwise None, the system
default: older versions of this app, and some other tools, wrote PGN
in the system code page, and such a file must be rewritten the same
way to keep its names intact.
"""
try:
with open(path, encoding=PGN_ENCODING) as f:
for _ in f:
pass
except UnicodeDecodeError:
return None
return PGN_ENCODING
MANAGED_UCI_OPTIONS = ['ponder', 'uci_chess960', 'multipv', 'uci_analysemode', 'ownbook']
# Engine role -> (active id-name attr, file attr, path attr, icon key, title).
ROLE_META = {
'opponent': ('opp_id_name', 'opp_file', 'opp_path_and_file', 'enemy', 'Opponent'),
'adviser': ('adviser_id_name', 'adviser_file', 'adviser_path_and_file', 'adviser', 'Adviser'),
'analysis': ('analysis_id_name', 'analysis_file', 'analysis_path_and_file', 'pecg', 'Analysis'),
'threat': ('threat_id_name', 'threat_file', 'threat_path_and_file', 'pecg', 'Threat'),
}
GUI_THEME = [
'Green', 'GreenTan', 'LightGreen', 'BluePurple', 'Purple', 'BlueMono', 'GreenMono', 'BrownBlue',
'BrightColors', 'NeutralBlue', 'Kayak', 'SandyBeach', 'TealMono', 'Topanga', 'Dark', 'Black', 'DarkAmber'
]
IMAGE_DIR = 'Images' # one folder of piece images per square size
IMAGE_PATH = 'Images/60' # the original set; also the fallback
BASE_SQUARE_PX = 60 # square size of the original set
# Board -> Size menu: label to square size in px (labels show the board
# width; the board is 8 squares wide). Each size has its own ready-made
# piece images in Images/<square size>, so no image library is needed at
# run time. Resizing a window picks the largest of these sizes that fits.
BOARD_SIZE_LABELS = {
'Small (360)': 45,
'Medium (480)': 60,
'Large (600)': 75,
'X-Large (720)': 90,
'XX-Large (840)': 105,
'Huge (960)': 120,
}
BOARD_SQUARE_SIZES = sorted(BOARD_SIZE_LABELS.values())
BOARD_SQUARE_MIN_PX = BOARD_SQUARE_SIZES[0]
BOARD_SQUARE_MAX_PX = BOARD_SQUARE_SIZES[-1]
def fit_square_px(square_px, min_px=BOARD_SQUARE_MIN_PX):
"""Return the largest available square size not above ``square_px``.
The result is never below ``min_px`` (rounded up to an available
size), even if that is more than ``square_px``.
"""
lowest = min((s for s in BOARD_SQUARE_SIZES if s >= min_px),
default=BOARD_SQUARE_MAX_PX)
fitting = [s for s in BOARD_SQUARE_SIZES if lowest <= s <= square_px]
return fitting[-1] if fitting else lowest
# A narrow strip on the right of the board canvas holds the turn marker:
# one dot level with each player's back rank, green for the side to move.
TURN_MARKER_PX = 16
TURN_MARKER_ON = '#2e9e3f'
TURN_MARKER_OFF = '#9aa0a6'
# Panels of the Play window, in their default order in the right zone.
PLAY_PANEL_KEYS = ('play_players_panel_k', 'play_moves_panel_k',
'play_comment_panel_k', 'play_books_panel_k',
'play_engine_panel_k')
# Panel key -> name shown in its title bar and in the View menu.
PLAY_PANEL_TITLES = {
'play_players_panel_k': 'Players',
'play_moves_panel_k': 'Move list',
'play_comment_panel_k': 'Comment',
'play_books_panel_k': 'Opening books',
'play_engine_panel_k': 'Engine',
}
# Ready-made arrangements offered in the View menu: name -> where the
# panels go around the board. 'Board Left' is the default.
PLAY_ARRANGEMENTS = {
'Board Left': {'right': list(PLAY_PANEL_KEYS)},
'Board Centre': {'left': ['play_players_panel_k', 'play_engine_panel_k'],
'right': ['play_moves_panel_k', 'play_comment_panel_k',
'play_books_panel_k']},
'Board Right': {'left': list(PLAY_PANEL_KEYS)},
'Engine Below Board': {'right': ['play_players_panel_k',
'play_moves_panel_k',
'play_comment_panel_k',
'play_books_panel_k'],
'bottom': ['play_engine_panel_k']},
}
# Panels of the Review window, in their default order.
REVIEW_PANEL_KEYS = ('review_gamelist_panel_k', 'review_game_panel_k',
'review_books_panel_k', 'review_moves_panel_k',
'review_threat_panel_k', 'review_analysis_panel_k')
REVIEW_PANEL_TITLES = {
'review_gamelist_panel_k': 'Game list',
'review_game_panel_k': 'Game details',
'review_books_panel_k': 'Book moves',
'review_moves_panel_k': 'Move list',
'review_threat_panel_k': 'Threat',
'review_analysis_panel_k': 'Analysis',
}
REVIEW_ARRANGEMENTS = {
'Board Left': {'right': list(REVIEW_PANEL_KEYS)},
'Board Centre': {'left': ['review_gamelist_panel_k',
'review_game_panel_k', 'review_books_panel_k',
'review_threat_panel_k'],
'right': ['review_moves_panel_k',
'review_analysis_panel_k']},
'Board Right': {'left': list(REVIEW_PANEL_KEYS)},
'Analysis Below Board': {'right': ['review_gamelist_panel_k',
'review_game_panel_k',
'review_books_panel_k',
'review_moves_panel_k',
'review_threat_panel_k'],
'bottom': ['review_analysis_panel_k']},
}
# What differs between the panel layouts of the two windows: the key of
# the board box, what is fixed under the board inside that box (None:
# nothing), the panels, the ready-made arrangements, the panels that take
# the spare height of their zone, and the name the layout is saved under
# in the settings file.
PANEL_LAYOUTS = {
'play': {'board': 'play_board_box_k', 'below_board': None,
'panels': PLAY_PANEL_KEYS,
'titles': PLAY_PANEL_TITLES, 'arrangements': PLAY_ARRANGEMENTS,
'stretch': ('play_moves_panel_k',), 'setting': 'play_layout'},
'review': {'board': 'review_board_box_k',
'below_board': 'review_nav_bar_k',
'panels': REVIEW_PANEL_KEYS,
'titles': REVIEW_PANEL_TITLES,
'arrangements': REVIEW_ARRANGEMENTS,
'stretch': ('review_moves_panel_k',),
'setting': 'review_layout'},
}
# Buttons of the bar under the Review board: (event key, icon, tooltip).
REVIEW_NAV_BUTTONS = (
('First', '|\u25c4', 'First position (Home)'),
('Previous', '\u25c4', 'Previous move (Left arrow)'),
('Next', '\u25ba', 'Next move (Right arrow)'),
('Last', '\u25ba|', 'Last position (End)'),
('Flip', '\u21c5', 'Flip the board'),
)
# Name of the arrangement a window starts with (in every mode).
DEFAULT_ARRANGEMENT = 'Board Left'
PANEL_ZONE_LABELS = {'Left of Board': 'left', 'Right of Board': 'right',
'Below Board': 'bottom'}
def build_view_menu(mode):
"""The View menu of the 'play' or 'review' window: panel arrangement.
Every item carries '::layout_k:<action>:...' so the event loops can
pass it to handle_layout_event(). Usable at any time, like Board ->
Flip.
"""
spec = PANEL_LAYOUTS[mode]
move_items = []
for key in spec['panels']:
move_items += [spec['titles'][key],
['{}::layout_k:move:{}:{}'.format(label, zone, key)
for label, zone in PANEL_ZONE_LABELS.items()]]
return ['&View', ['{}::layout_k:preset:{}'.format(name, name)
for name in spec['arrangements']]
+ ['---', 'Move Panel', move_items,
'---', 'Reset Layout::layout_k:reset']]
PANEL_BORDER_COLOR = '#9aa0a6'
BLANK = 0 # piece names
PAWNB = 1
KNIGHTB = 2
BISHOPB = 3
ROOKB = 4
KINGB = 5
QUEENB = 6
PAWNW = 7
KNIGHTW = 8
BISHOPW = 9
ROOKW = 10
KINGW = 11
QUEENW = 12
# Absolute rank based on real chess board, white at bottom, black at the top.
# This is also the rank mapping used by python-chess modules.
RANK_8 = 7
RANK_7 = 6
RANK_6 = 5
RANK_5 = 4
RANK_4 = 3
RANK_3 = 2
RANK_2 = 1
RANK_1 = 0
initial_board = [[ROOKB, KNIGHTB, BISHOPB, QUEENB, KINGB, BISHOPB, KNIGHTB, ROOKB],
[PAWNB, ] * 8,
[BLANK, ] * 8,
[BLANK, ] * 8,
[BLANK, ] * 8,
[BLANK, ] * 8,
[PAWNW, ] * 8,
[ROOKW, KNIGHTW, BISHOPW, QUEENW, KINGW, BISHOPW, KNIGHTW, ROOKW]]
white_init_promote_board = [[QUEENW, ROOKW, BISHOPW, KNIGHTW]]
black_init_promote_board = [[QUEENB, ROOKB, BISHOPB, KNIGHTB]]
# ---------------------------------------------------------------------------
# Help system
# ---------------------------------------------------------------------------
# Brief, topic-focused help shown in small popups from the Help menu. The full
# reference lives in the project README (its section D.10 lists this menu).
# Each dict key doubles as the "::key" suffix of its Help menu item.
HELP_TOPICS = {
'help_start': (
'Getting Started',
'Python Easy Chess GUI opens in Play mode, ready to play.\n\n'
'1. Install a UCI engine: Engine -> Manage -> Install.\n'
' (A few engines are installed already.)\n'
'2. Choose your opponent: Engine -> Set Engine Opponent.\n'
'3. Move a piece to start the game, or press Engine -> Go\n'
' to play as Black.\n\n'
'Setup menus are disabled while a game is running; press\n'
'Game -> New to end it and set up again.\n'
'Games auto-save to pecg_auto_save_games.pgn.\n\n'
'To replay and analyse a game: Mode -> Review.\n\n'
'Each Help topic is short. The full manual is the README on the\n'
'project page; Help -> About shows its address.'),
'help_shortcuts': (
'Mouse and Keyboard',
'PLAY\n'
' Move a piece click it, then its square; or drag it\n'
' Adviser right-click Adviser -> Start / Stop\n'
' Search info right-click Opponent Search Info\n'
' Book moves right-click BOOK 1 or BOOK 2\n\n'
'REVIEW\n'
' Move a piece enter a move: click it, then its square;\n'
' or drag it\n'
' Left / Right previous / next move\n'
' Home / End first / last position\n'
' Alt+A Analysis on / off\n'
' Alt+T Threat on / off\n'
' Ctrl+S save the game\n'
' Up / Down previous / next game (in the Game list)\n'
' Click a move jump to that position\n'
' Right-click a move comment, annotate, promote, delete\n'
' Click a heading sort the Game list by that column\n\n'
'BOTH MODES\n'
' Drag a title bar move that panel\n'
' Drag a divider resize panels or the board'),
'help_eng_install': (
'Install / Manage Engines',
'Available before a game starts. Only UCI engines are supported.\n\n'
'Install:\n'
' 1. Engine -> Manage -> Install, press Add.\n'
' 2. Press Browse and pick the engine file.\n'
' 3. Press Get Id Name (or type a name), then OK.\n'
' On Linux first allow the file to run: chmod +x engine\n\n'
'Options: Engine -> Manage -> Edit -> pick the engine -> Modify\n'
' (Hash, Threads and its other options).\n'
'Remove: Engine -> Manage -> Delete.\n\n'
'After installing, choose what the engine is used for: see\n'
'Help -> Engine -> Engine for Each Job.'),
'help_eng_roles': (
'Engine for Each Job',
'There are four jobs, each with its own engine. Choose them in\n'
'the Engine menu (Play mode, before a game starts):\n\n'
' Set Engine Opponent the engine you play against\n'
' Set Engine Adviser suggests a move during a game\n'
' Set Engine Analysis the Analysis button in Review\n'
' Set Engine Threat the Threat button in Review\n\n'
'In the manager that opens:\n'
' Use Selected make the selected engine do this job\n'
' Configure give it other options for this job only,\n'
' for example more Hash for analysis\n'
' Delete Config remove those options again\n'
'An engine with its own options for the job is marked\n'
'(configured).'),
'help_eng_opponent': (
'Set Engine Opponent',
'Engine -> Set Engine Opponent (before a game starts).\n\n'
'This is the engine you play against. Select one of the\n'
'installed engines and press Use Selected.\n\n'
'Its clock: Settings -> Time -> Engine.\n'
'Its book: Settings -> Set Book.\n'
'Its depth: Engine -> Set Depth.'),
'help_eng_adviser': (
'Engine Adviser',
'Select it with Engine -> Set Engine Adviser. How long it\n'
'thinks (Movetime) is set in the same window.\n\n'
'During a game (Play mode) right-click the Adviser label in the\n'
'Engine panel and press Start to get a suggested move and score\n'
'for the current position.'),
'help_eng_analysis': (
'Review Analysis Engine',
'Select it with Engine -> Set Engine Analysis.\n\n'
'In Review mode press the Analysis button to evaluate the current\n'
'position. Hash, Threads and the number of lines (MultiPV) are\n'
'set in the Analysis panel. The search stops after the analysis\n'
'time in Settings -> General (default 60s).'),
'help_eng_threat': (
'Review Threat Engine',
'Select it with Engine -> Set Engine Threat.\n\n'
'In Review mode press the Threat button to see what the opponent\n'
'would play if the side to move passed (null move). Unavailable\n'
'while in check. Hash and Threads are set in the Threat panel.\n'
'Time limit: Settings -> General (default 30s).'),
'help_eng_depth': (
'Search Depth',
'Engine -> Set Depth caps the search depth of the playing and\n'
'adviser engines. Pick "No limit" to remove the cap.\n'
'Review analysis/threat are limited by time, not depth.'),
'help_game_play': (
'Play a Game',
'Click the piece and its destination square (or drag it).\n'
'Your first move starts the game and the clocks.\n\n'
'Engine -> Move Now the engine moves at once\n'
'Game -> New start a new game\n'
'Game -> Resign, User Wins, User Draws end the game\n\n'
'The two dots beside the board show whose turn it is: the green\n'
'one is the side to move. The Players panel shows the time left\n'
'and the time spent on the current move.'),
'help_game_black': (
'Play as Black',
'Press Engine -> Go before making a move: the engine takes\n'
'White and moves first, and the board flips so Black is at\n'
'the bottom. Game -> New returns you to White.'),
'help_game_fen': (
'Paste a FEN',
'Game -> Paste FEN sets up a position from the clipboard (only\n'
'before a game starts). If the side to move is not yours,\n'
'press Engine -> Go.'),
'help_game_assist': (
'Adviser and Book Moves',
'These help you during a game. Right-click the label:\n\n'
'Adviser (Engine panel) -> Start: a suggested move and score\n'
'from the adviser engine. Stop ends it.\n\n'
'BOOK 1 / BOOK 2 (Opening books panel) -> Show: the opening\n'
'book moves of the position, from computer games and from human\n'
'games. Hide removes them.\n\n'
'Opponent Search Info (Engine panel) -> Show / Hide: what the\n'
'opponent engine thinks.'),
'help_game_save': (
'Save Games and Repertoire',
'Every game auto-saves to pecg_auto_save_games.pgn.\n\n'
'During a game Game -> Save also offers Save to My Games and\n'
'Save to White / Black Repertoire.\n\n'
'Open any of these files in Review mode to replay the games.\n'
'Review mode saves a game to the PGN file you choose: see\n'
'Help -> Review -> Save a Game.'),
'help_game_time': (
'Time Control',
'Settings -> Time -> User sets your clock; Settings -> Time ->\n'
'Engine sets the opponent clock. Adjudication on flag-fall is\n'
'toggled in Settings -> General.'),
'help_settings': (
'Settings',
'The Settings menu is in Play mode, before a game starts.\n\n'
'General:\n'
' Save time left in game notation adds [%clk] comments\n'
' Adjudicate game on time forfeit a flag-fall ends the game\n'
' Review analysis time (sec) default 60\n'
' Review threat time (sec) default 30\n'
'Time -> User / Engine the clock of each side\n'
'Set Book the opponent book: use it or not, up\n'
' to which ply, best or random move\n'
'User Name your name in the games\n'
'PGN -> Delete Player delete the games of a player from a\n'
' PGN file\n\n'
'Everything is saved and restored at the next start.'),
'help_files': (
'Files the App Writes',
'All in the folder the app is started from:\n\n'
'pecg_auto_save_games.pgn every game played\n'
'pecg_analyzed_games.pgn games annotated by Auto-Analyze\n'
'pecg_engines.json installed engines and options\n'
'pecg_settings.json settings, engine jobs, layouts\n'
'pecg_user.json user names\n'
'pecg_log.txt log, new on every start; look here\n'
' first when something goes wrong'),
'help_review_open': (
'Open a Game to Review',
'Mode -> Review, then Game -> Select Game: choose a PGN file (or\n'
'pick one from Recent), select a game and press OK or\n'
'double-click it. The file is opened again the next time.\n\n'
'The Game list panel shows the games of that file: click one to\n'
'put it on the board, or use the Up / Down keys in the list.\n'
'Click a column heading to sort. Analysis and Threat, if they\n'
'are on, follow the board to the new game.'),
'help_review_nav': (
'Navigate Moves',
'Use the arrow buttons under the board (first, previous, next,\n'
'last; the fifth button flips the board),\n'
'the Left / Right arrow keys (Home / End for first / last), or\n'
'click a move in the move list to jump to that position.'),
'help_review_edit': (
'Enter Moves and Variations',
'Move a piece on the Review board, as in Play mode: click it,\n'
'then its square, or drag it.\n\n'
' At the end of a line the move is added to the line\n'
' A move the game has you go to that move\n'
' Any other move starts a variation there\n\n'
'A variation can have variations of its own. For a game from\n'
'the start position use Game -> New Game.\n\n'
'Right-click a move in the move list (or the list itself, for\n'
'the current move):\n'
' Promote Variation one place up; from the first place it\n'
' becomes the line it left\n'
' Demote Variation one place down\n'
' Make Main Line the move becomes main line of the game\n'
' Delete Variation the whole variation of the move\n'
' Delete This Move and the Rest\n'
' Delete the Moves After\n\n'
'The main line is bold. The game cannot be changed while\n'
'Auto-Analyze is running.'),
'help_review_annotate': (
'Comments and Annotations',
'Right-click a move in the move list.\n\n'
'Comment... text after the move. The first move of a\n'
' variation can also have text before it.\n'
' At Start Position: text before move one.\n'
'Move Annotation ! ? !! ?? !? ?! or only move\n'
'Position Annotation = unclear += =+ +/- -/+ +- -+\n'
'None takes the annotation away.\n\n'
'A move with a move annotation is coloured in the move list:\n'
' ?? blunder red\n'
' ? mistake light red\n'
' ?! dubious orange\n'
' !? interesting purple\n'
' ! good light blue\n'
' !! brilliant blue'),
'help_review_save': (
'Save a Game (Review)',
'Game -> Save Game (Ctrl+S) asks for the folder and the name of\n'
'a PGN file. The game is added at the end of that file: the\n'
'games already in it are kept. A new name makes a new file.\n\n'
'Game -> Game Details sets the players, event, date and result\n'
'saved with the game.\n\n'
'The status bar shows "changed, not saved" until the game is\n'
'saved. You are asked before a changed game is replaced by\n'
'another one, and before you leave Review mode.'),
'help_review_engine': (
'Analysis and Threat (Review)',
'Analysis button (Alt+A): evaluate the position with the\n'
'analysis engine.\n'
'Threat button (Alt+T): show the opponent threat (null move).\n'
'Both stop after their time limits in Settings -> General\n'
'(analysis 60s, threat 30s) and restart automatically when you\n'
'change move.\n\n'
'Each box shows the search figures (depth, time, nodes, nodes\n'
'per second), then the score and the line of moves. The score\n'
'is for the side to move; #3 means that side mates in 3, -#3\n'
'that it is mated in 3. For Threat the side to move is the\n'
'opponent. The line is as long as the panel is wide: widen the\n'
'panel to see more.\n\n'
'Hash, Threads and MultiPV (number of lines) are set in the\n'
'panel and saved; a running search restarts with the new value.'),
'help_review_auto': (
'Auto-Analyze Game',
'Game -> Auto-Analyze Game annotates every move of the main\n'
'line with the engine and time per move that you choose.\n\n'
'Each move gets its evaluation as a comment, from the side that\n'
'played it (positive is good for that side). A mate is counted\n'
'after the move: "Mate" when the move mates, "Mate in 1" when\n'
'one more move does.\n\n'
'A bad move is marked by what it loses against the best move:\n'
' ?! 1.00 pawn or more\n'
' ? 2.00 or more, and the side is not losing after it\n'
' ?? 2.00 or more, and the side is losing after it\n'
'Losing is -3.00 or worse. No mark while the side is still\n'
'winning (+3.00) after the move, or was losing before it.\n\n'
'A "Better is" variation is added when the engine move is\n'
'better by 0.25 or more (by 0.10 when its score is within 0.50\n'
'of equal) and its score is within 10.00 of equal. It is the\n'
'line of the engine: its score after the first move, and a\n'
'dash and the engine name after the last move.\n'
'A missed win (engine score above 10.00, game move worse by\n'
'2.00 or more) is shown too, its first move marked !! for a\n'
'mate in 10 or less and ! otherwise.\n\n'
'Comments, annotations and variations the game already has are\n'
'kept; the dialog lets you remove them first. Start move and\n'
'End move in the dialog pick the moves to analyse, by move\n'
'number (4 to the end unless changed). Analysing again\n'
'replaces the scores and the lines of the same engine, and\n'
'adds the lines of another engine beside them.\n\n'
'The result is appended to pecg_analyzed_games.pgn and replaces\n'
'the game on the board. Game -> Cancel Analysis stops early.'),
'help_board_flip': (
'Flip Board',
'Board -> Flip swaps the side shown at the bottom. It works at\n'
'any time: before, during and after a game, and in Review mode.\n'
'The game itself is not affected.'),
'help_board_size': (
'Board Size',
'Board -> Size picks a board size: Small (360), Medium (480),\n'
'Large (600), X-Large (720), XX-Large (840) or Huge (960)\n'
'pixels. On first start the largest board that fits the screen\n'
'is chosen automatically, and the size is saved for the next\n'
'session. The windows are also resizable: maximize or\n'
'drag-resize them and the board switches to the largest of\n'
'these sizes that fits, while the side panels absorb the\n'
'leftover space. Like Flip, resizing works at any time.'),
'help_board_layout': (
'Panels and Layout',
'The Play and Review windows are made of panels around the\n'
'board.\n\n'
'Move a panel: drag its title bar to the left of the board, to\n'
'the right or below it (a green bar shows where it will land),\n'
'or use View -> Move Panel. Under the board, drop it on the top\n'
'or bottom edge of another panel to stack them, or on its middle\n'
'to put them side by side.\n'
'Resize: drag the divider between two panels, or between the\n'
'board and the panels.\n'
'View also has ready-made arrangements and Reset Layout.\n\n'
'Each mode keeps its own arrangement; it is saved and restored\n'
'at the next start.'),
'help_board_color': (
'Board Colors and Themes',
'Board -> Color changes the square colors and Board -> Theme\n'
'changes the overall GUI theme (before a game starts).'),
}
# The full manual: the project README (Help -> About shows this address).
ONLINE_HELP_URL = 'https://github.com/fsmosca/Python-Easy-Chess-GUI#readme'
# Help submenu fragments, one per subject; each mode's Help menu is made
# of the ones that apply to it. Note: a literal '&' marks a keyboard
# accelerator in menu labels, so plain words are used instead.
HELP_ENGINE_MENU = ['Engine', ['Install / Manage::help_eng_install',
'Engine for Each Job::help_eng_roles',
'Set Opponent::help_eng_opponent',
'Adviser::help_eng_adviser',
'Analysis::help_eng_analysis',
'Threat::help_eng_threat',
'Search Depth::help_eng_depth']]
HELP_GAME_MENU = ['Play', ['Play a Game::help_game_play',
'Play as Black::help_game_black',
'Paste FEN::help_game_fen',
'Adviser and Book Moves::help_game_assist',
'Save and Repertoire::help_game_save',
'Time Control::help_game_time']]
HELP_REVIEW_MENU = ['Review', ['Open a Game::help_review_open',
'Navigate Moves::help_review_nav',
'Enter Moves and Variations::help_review_edit',
'Comments and Annotations'
'::help_review_annotate',
'Save a Game::help_review_save',
'Analysis and Threat::help_review_engine',
'Auto-Analyze Game::help_review_auto']]
HELP_BOARD_MENU = ['Board and Layout', [
'Flip::help_board_flip',
'Size::help_board_size',
'Panels and Layout::help_board_layout',
'Colors and Themes::help_board_color']]
def make_help_menu(*sections):
"""Return a fresh Help menu definition for a mode.
``sections`` are submenu fragments of the form ``['Label', [items]]``.
They are flattened into the parent so the label string and its item list
become siblings (the format FreeSimpleGUI expects: a cascade is a string
immediately followed by a list). A deep copy is returned so FreeSimpleGUI
cannot mutate the shared fragment lists across the three menu definitions.
"""
items = ['Getting Started::help_start',
'Mouse and Keyboard::help_shortcuts', '---']
for section in sections:
items.extend(section) # 'Label', [subitems] as two sibling elements
items.extend(['---', 'Settings::help_settings',
'Files the App Writes::help_files'])
# 'Online Help' is disabled (leading '!') so it shows but is not clickable.
items.extend(['---', '!Online Help::help_online', 'About::help_about'])
return ['&Help', copy.deepcopy(items)]
# Images/60
blank = os.path.join(IMAGE_PATH, 'blank.png')
bishopB = os.path.join(IMAGE_PATH, 'bB.png')
bishopW = os.path.join(IMAGE_PATH, 'wB.png')
pawnB = os.path.join(IMAGE_PATH, 'bP.png')
pawnW = os.path.join(IMAGE_PATH, 'wP.png')
knightB = os.path.join(IMAGE_PATH, 'bN.png')
knightW = os.path.join(IMAGE_PATH, 'wN.png')
rookB = os.path.join(IMAGE_PATH, 'bR.png')
rookW = os.path.join(IMAGE_PATH, 'wR.png')
queenB = os.path.join(IMAGE_PATH, 'bQ.png')
queenW = os.path.join(IMAGE_PATH, 'wQ.png')
kingB = os.path.join(IMAGE_PATH, 'bK.png')
kingW = os.path.join(IMAGE_PATH, 'wK.png')
images = {
BISHOPB: bishopB, BISHOPW: bishopW, PAWNB: pawnB, PAWNW: pawnW,
KNIGHTB: knightB, KNIGHTW: knightW, ROOKB: rookB, ROOKW: rookW,
KINGB: kingB, KINGW: kingW, QUEENB: queenB, QUEENW: queenW, BLANK: blank
}
# Promote piece from psg (pysimplegui) to pyc (python-chess)
promote_psg_to_pyc = {
KNIGHTB: chess.KNIGHT, BISHOPB: chess.BISHOP,
ROOKB: chess.ROOK, QUEENB: chess.QUEEN,
KNIGHTW: chess.KNIGHT, BISHOPW: chess.BISHOP,
ROOKW: chess.ROOK, QUEENW: chess.QUEEN
}
INIT_PGN_TAG = {
'Event': 'Human vs computer',
'White': 'Human',
'Black': 'Computer'
}
# (1) Mode: Play. The GUI opens directly in Play mode with a single menubar.
# Items that change the game/engine setup are usable only before a game
# starts (idle), while game actions need a started game. A leading '!'
# renders an item or submenu label disabled (grayed and unclickable).
def build_play_menu(in_game=False):
"""Return the Play-mode menubar definition for the given state.
:param in_game: True once a game has started (first user move made or
Engine->Go pressed) until it ends (game over or Game->New).
"""
def g(enabled, label):
return label if enabled else '!' + label
idle = not in_game
return [
['&Mode', [g(idle, 'Review')]],
['&Game', ['&New::new_game_k',
'---',
g(idle, 'Paste FEN'),
'---',
g(in_game, 'Resign::resign_game_k'),
g(in_game, 'User Wins::user_wins_k'),
g(in_game, 'User Draws::user_draws_k'),
'---',
g(in_game, 'Save'), ['Save to My Games::save_game_k',
'Save to White Repertoire',
'Save to Black Repertoire']]],
['&Engine', [g(idle, 'Go'), g(in_game, 'Move Now'),
'---',
g(idle, 'Set Engine Opponent'),
g(idle, 'Set Engine Adviser'),
g(idle, 'Set Engine Analysis'),
g(idle, 'Set Engine Threat'),
'---',
g(idle, 'Set Depth'),
g(idle, 'Manage'), ['Install', 'Edit', 'Delete']]],
['Boar&d', ['Flip',
'Size', ['{}::board_size_k'.format(label)
for label in BOARD_SIZE_LABELS],
g(idle, 'Color'), ['Brown::board_color_k',
'Blue::board_color_k',