-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathpython_easy_chess_gui.py
More file actions
5932 lines (5153 loc) · 251 KB
/
Copy pathpython_easy_chess_gui.py
File metadata and controls
5932 lines (5153 loc) · 251 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.7.3 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 pyperclip
import chess
import chess.pgn
import chess.engine
import chess.polyglot
import logging
import webbrowser
import tkinter as tk
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 = 'v2.13.0'
BOX_TITLE = f'{APP_NAME} {APP_VERSION}'
REVIEW_MAX_DISPLAY_GAMES = 10000
REVIEW_ANALYSIS_MULTIPV_LINES = 3
REVIEW_ANALYSIS_PV_MOVES = 7
REVIEW_NAV_DEBOUNCE_SEC = 0.3
REVIEW_MOVE_LIST_HEIGHT = 8 # reduced from 11 to make room for the threat panel
REVIEW_ANALYSIS_BOX_HEIGHT = 3
REVIEW_THREAT_BOX_HEIGHT = 1
REVIEW_THREAT_PV_PLIES = 5
# 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)
# 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
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_PATH = 'Images/60' # path to the chess pieces
SQUARE_PX = 60 # piece images are 60x60, so the board is 8 * 60 wide
BOARD_PX = 8 * SQUARE_PX
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, opened via Help -> Online Help.
# Each dict key doubles as the "::key" suffix of its Help menu item.
HELP_TOPICS = {
'help_start': (
'Getting Started',
'Python Easy Chess GUI has 3 modes: Neutral, Play and Review.\n'
'You start in Neutral; switch using the Mode menu.\n\n'
'1. Install a UCI engine: Engine -> Manage -> Install.\n'
'2. Choose your opponent: Engine -> Set Engine Opponent.\n'
'3. Play: Mode -> Play, then move on the board.\n\n'
'Games auto-save to pecg_auto_save_games.pgn.\n'
'For the full manual use Help -> Online Help.'),
'help_eng_install': (
'Install / Manage Engines',
'Neutral mode only. Only UCI engines are supported.\n\n'
'Install: Engine -> Manage -> Install -> Add.\n'
'Configure: Engine -> Manage -> Edit -> pick engine -> Modify\n'
' (Hash, Threads and other options).\n'
'Remove: Engine -> Manage -> Delete.'),
'help_eng_opponent': (
'Set Engine Opponent',
'Neutral mode: Engine -> Set Engine Opponent.\n\n'
'This is the engine you play against; the list shows the engines\n'
'you have installed. Set its clock under Time -> Engine.'),
'help_eng_adviser': (
'Engine Adviser',
'Select it with Engine -> Set Engine Adviser.\n\n'
'During a game (Play mode) right-click the Adviser label and press\n'
'Start to get a suggested move and score 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 (multiple lines). The search stops after the analysis\n'
'time in Settings -> Game (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. Time limit: Settings -> Game (default 30s).'),
'help_eng_depth': (
'Search Depth',
'Engine -> Set Depth caps the search depth of the playing and\n'
'adviser engines. Leave at the default for no depth limit.\n'
'Review analysis/threat are limited by time, not depth.'),
'help_game_play': (
'Play a Game',
'Mode -> Play, then click the piece and its destination square\n'
'(or drag it). Engine -> Move Now forces the engine to move;\n'
'Game -> New starts a new game.'),
'help_game_black': (
'Play as Black',
'In Neutral mode: Board -> Flip (black at the bottom), then\n'
'Mode -> Play and Engine -> Go so the engine moves first.\n'
'(If already in Play, switch to Neutral first.)'),
'help_game_fen': (
'Paste a FEN',
'In Play mode: FEN -> Paste to set up a position from the\n'
'clipboard. If it is Black to move, use Engine -> Go.'),
'help_game_save': (
'Save Games and Repertoire',
'Every game auto-saves to pecg_auto_save_games.pgn.\n\n'
'In Play mode the Game menu also offers Save to My Games and\n'
'Save to White / Black Repertoire.'),
'help_game_time': (
'Time Control',
'Time -> User sets your clock; Time -> Engine sets the opponent\n'
'clock. Adjudication on flag-fall is toggled in Settings -> Game.'),
'help_review_open': (
'Open a Game to Review',
'Mode -> Review, choose a PGN file, select a game and press OK.\n'
'Use Game -> Load PGN / Select Game to change games later.'),
'help_review_nav': (
'Navigate Moves',
'Use the First, Previous, Next and Last buttons below the board,\n'
'or click a move in the move list to jump to that position.'),
'help_review_engine': (
'Analysis and Threat (Review)',
'Analysis button: evaluate the position with the analysis engine.\n'
'Threat button: show the opponent threat (null move).\n'
'Both stop after their time limits in Settings -> Game (analysis\n'
'60s, threat 30s) and restart automatically when you change move.'),
'help_board_flip': (
'Flip Board',
'Board -> Flip swaps the side shown at the bottom. Use it in\n'
'Neutral mode, or in Review mode via its Board menu.'),
'help_board_color': (
'Board Colors and Themes',
'Neutral mode: Board -> Color changes the square colors and\n'
'Board -> Theme changes the overall GUI theme.'),
}
# Online (detailed) help target for Help -> Online Help.
ONLINE_HELP_URL = 'https://github.com/fsmosca/Python-Easy-Chess-GUI#readme'
# Help submenu fragments. 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',
'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 = ['Game', ['Play a Game::help_game_play',
'Play as Black::help_game_black',
'Paste FEN::help_game_fen',
'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',
'Analysis and Threat::help_review_engine']]
HELP_BOARD_MENU = ['Board', ['Flip::help_board_flip',
'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']
for section in sections:
items.extend(section) # 'Label', [subitems] as two sibling elements
# '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: Neutral
menu_def_neutral = [
['&Mode', ['Play', 'Review']],
['Boar&d', ['Flip', 'Color', ['Brown::board_color_k',
'Blue::board_color_k',
'Green::board_color_k',
'Gray::board_color_k'],
'Theme', GUI_THEME]],
['&Engine', ['Set Engine Adviser', 'Set Engine Analysis',
'Set Engine Threat', 'Set Engine Opponent', 'Set Depth',
'Manage', ['Install', 'Edit', 'Delete']]],
['&Time', ['User::tc_k', 'Engine::tc_k']],
['&Book', ['Set Book::book_set_k']],
['&User', ['Set Name::user_name_k']],
['Tools', ['PGN', ['Delete Player::delete_player_k']]],
['&Settings', ['Game::settings_game_k']],
make_help_menu(HELP_ENGINE_MENU, HELP_GAME_MENU,
HELP_REVIEW_MENU, HELP_BOARD_MENU),
]
# (2) Mode: Play, info: hide
menu_def_play = [
['&Mode', ['Neutral']],
['&Game', ['&New::new_game_k',
'Save to My Games::save_game_k',
'Save to White Repertoire',
'Save to Black Repertoire',
'Resign::resign_game_k',
'User Wins::user_wins_k',
'User Draws::user_draws_k']],
['FEN', ['Paste']],
['&Engine', ['Go', 'Move Now']],
make_help_menu(HELP_GAME_MENU, HELP_ENGINE_MENU),
]
# (3) Mode: Review
menu_def_review = [
['&Mode', ['Neutral']],
['&Game', ['Load PGN::review_load_pgn_k',
'Select Game::review_select_game_k']],
['Boar&d', ['Flip']],
make_help_menu(HELP_REVIEW_MENU, HELP_ENGINE_MENU, HELP_BOARD_MENU),
]
class Timer:
def __init__(self, tc_type: str = 'fischer', base: int = 300000, inc: int = 10000, period_moves: int = 40) -> None:
"""Manages time control.
Args:
tc_type: time control type ['fischer, delay, classical']
base: base time in ms
inc: increment time in ms can be negative and 0
period_moves: number of moves in a period
"""
self.tc_type = tc_type # ['fischer', 'delay', 'timepermove']
self.base = base
self.inc = inc
self.period_moves = period_moves
self.elapse = 0
self.init_base_time = self.base
def update_base(self) -> None:
"""Updates base time after every move."""
if self.tc_type == 'delay':
self.base += min(0, self.inc - self.elapse)
elif self.tc_type == 'fischer':
self.base += self.inc - self.elapse
elif self.tc_type == 'timepermove':
self.base = self.init_base_time
else:
self.base -= self.elapse
self.base = max(0, self.base)
self.elapse = 0
class GuiBook:
def __init__(self, book_file: str, board, is_random: bool = True) -> None:
"""Handles gui polyglot book for engine opponent.
Args:
book_file: polgylot book filename
board: given board position
is_random: randomly select move from book
"""
self.book_file = book_file
self.board = board
self.is_random = is_random
self.__book_move = None
def get_book_move(self) -> None:
"""Gets book move either random or best move."""
reader = chess.polyglot.open_reader(self.book_file)
try:
if self.is_random:
entry = reader.weighted_choice(self.board)
else:
entry = reader.find(self.board)
self.__book_move = entry.move
except IndexError:
logging.warning('No more book move.')
except Exception:
logging.exception('Failed to get book move.')
finally:
reader.close()
return self.__book_move
def get_all_moves(self):
"""
Read polyglot book and get all legal moves from a given positions.
:return: move string
"""
is_found = False
total_score = 0
book_data = {}
cnt = 0
if os.path.isfile(self.book_file):
moves = '{:4s} {:<5s} {}\n'.format('move', 'score', 'weight')
with chess.polyglot.open_reader(self.book_file) as reader:
for entry in reader.find_all(self.board):
is_found = True
san_move = self.board.san(entry.move)
score = entry.weight
total_score += score
bd = {cnt: {'move': san_move, 'score': score}}
book_data.update(bd)
cnt += 1
else:
moves = '{:4s} {:<}\n'.format('move', 'score')
# Get weight for each move
if is_found:
for _, v in book_data.items():
move = v['move']
score = v['score']
weight = score/total_score
moves += '{:4s} {:<5d} {:<2.1f}%\n'.format(move, score, 100*weight)
return moves, is_found
class RunEngine(threading.Thread):
pv_length = 9
move_delay_sec = 3.0
def __init__(self, eng_queue, engine_config_file, engine_path_and_file,
engine_id_name, max_depth=MAX_DEPTH,
base_ms=300000, inc_ms=1000, tc_type='fischer',
period_moves=0, is_stream_search_info=True,
existing_engine=None, multipv=1, option_overrides=None):
"""
Run engine as opponent or as adviser.
:param eng_queue:
:param engine_config_file: pecg_engines.json
:param engine_path_and_file:
:param engine_id_name:
:param max_depth:
:param existing_engine: An existing chess.engine.SimpleEngine instance
to reuse instead of spawning a new process.
"""
threading.Thread.__init__(self)
self._kill = threading.Event()
self._analysis_ref = None # Reference to running analysis context
self._analysis_lock = threading.Lock()
self.engine_config_file = engine_config_file
self.engine_path_and_file = engine_path_and_file
self.engine_id_name = engine_id_name
self.own_book = False
self.bm = None
self.pv = None
self.score = None
self.depth = None
self.time = None
self.nps = 0
self.max_depth = max_depth
self.eng_queue = eng_queue
self.engine = existing_engine
self.board = None
self.analysis = is_stream_search_info
self.is_nomove_number_in_variation = True
self.base_ms = base_ms
self.inc_ms = inc_ms
self.tc_type = tc_type
self.period_moves = period_moves
self.is_ownbook = False
self.is_move_delay = True
# Per-role UCI option overrides applied on top of the engine config.
self.option_overrides = option_overrides or {}
try:
self.multipv = max(1, int(multipv))
except (TypeError, ValueError):
self.multipv = 1
def stop(self):
"""Interrupt engine search.
Sets the kill flag and, if an analysis is in progress, sends
the UCI ``stop`` command to the engine so that the iterator
unblocks immediately instead of waiting for the next info line.
"""
self._kill.set()
with self._analysis_lock:
if self._analysis_ref is not None:
try:
self._analysis_ref.stop()
except Exception:
logging.debug('Analysis ref stop failed (already finished).')
def get_board(self, board):
"""Get the current board position."""
self.board = board
def configure_engine(self):
"""Configures the engine internal settings.
Read the engine config file pecg_engines.json and set the engine to
use the user_value of the value key. Our option name has 2 values,
default_value and user_value.
Example for hash option
'name': Hash
'default': default_value
'value': user_value
If default_value and user_value are not the same, we will set the
engine to use the user_value by the command,
setoption name Hash value user_value
However if default_value and user_value are the same, we will not send
commands to set the option value because the value is default already.
"""
with open(self.engine_config_file, 'r') as json_file:
data = json.load(json_file)
managed_uci_options = {name.lower() for name in MANAGED_UCI_OPTIONS}
for p in data:
if p['name'] == self.engine_id_name:
for n in p['options']:
option_name = n['name'].lower()
if option_name == 'ownbook':
self.is_ownbook = True
# Analysis-managed options are applied at runtime.
if self.analysis and option_name in managed_uci_options:
continue
# Ignore button type for a moment.
if n['type'] == 'button':
continue
if n['type'] == 'spin':
user_value = int(n['value'])
default_value = int(n['default'])
else:
user_value = n['value']
default_value = n['default']
if user_value != default_value:
try:
self.engine.configure({n['name']: user_value})
logging.info('Set ' + n['name'] + ' to ' + str(user_value))
except Exception:
logging.exception('Failed to configure engine.')
def configure_runtime_analysis_options(self):
"""Configure transient analysis-specific engine options."""
if not self.analysis:
return
try:
option_names = {name.lower(): name for name in self.engine.options}
except Exception:
logging.exception('Failed to read engine options.')
return
if 'uci_analysemode' in option_names:
try:
self.engine.configure({option_names['uci_analysemode']: True})
except Exception:
logging.exception('Failed to enable analyse mode.')
# NOTE: MultiPV must NOT be set with engine.configure(). python-chess
# treats it as an automatically-managed option (chess.engine.
# MANAGED_OPTIONS) and raises EngineError "cannot set MultiPV which is
# automatically managed". It is applied instead by passing
# multipv=self.multipv to engine.analysis() in run().
def apply_option_overrides(self):
"""Apply per-role UCI option overrides on top of the base config."""
if not self.option_overrides:
return
try:
option_names = {name.lower(): name for name in self.engine.options}
except Exception:
logging.exception('Failed to read engine options for overrides.')
return
managed = {m.lower() for m in chess.engine.MANAGED_OPTIONS}
for name, value in self.option_overrides.items():
lname = name.lower()
if lname in managed or lname not in option_names:
continue
real = option_names[lname]
try:
opt = self.engine.options[real]
if opt.type == 'spin':
value = int(value)
elif opt.type == 'check':
value = value if isinstance(value, bool) else \
str(value).strip().lower() in ('true', '1', 'yes')
self.engine.configure({real: value})
logging.info('Override %s = %s', real, value)
except Exception:
logging.exception('Failed to apply override %s.', name)
def run(self):
"""Run engine to get search info and bestmove.
If there is error we still send bestmove None.
"""
# Reuse existing engine if provided
if self.engine is None:
folder = Path(self.engine_path_and_file)
folder = folder.parents[0]
try:
if sys_os == 'Windows':
self.engine = chess.engine.SimpleEngine.popen_uci(
self.engine_path_and_file, cwd=folder,
creationflags=subprocess.CREATE_NO_WINDOW)
else:
self.engine = chess.engine.SimpleEngine.popen_uci(
self.engine_path_and_file, cwd=folder)
except chess.engine.EngineTerminatedError:
logging.warning('Failed to start {}.'.format(self.engine_path_and_file))
self.eng_queue.put('bestmove {}'.format(self.bm))
return
except Exception:
logging.exception('Failed to start {}.'.format(
self.engine_path_and_file))
self.eng_queue.put('bestmove {}'.format(self.bm))
return
# Set engine option values
try:
self.configure_engine()
except Exception:
logging.exception('Failed to configure engine.')
try:
self.configure_runtime_analysis_options()
except Exception:
logging.exception('Failed to configure runtime analysis options.')
try:
self.apply_option_overrides()
except Exception:
logging.exception('Failed to apply option overrides.')
# Set search limits.
# For infinite analysis pass limit=None so that python-chess sends
# "go infinite" to the engine (Limit() is truthy and would produce
# a bare "go" without the infinite token).
if self.tc_type == 'infinite':
limit = (chess.engine.Limit(depth=self.max_depth)
if self.max_depth != MAX_DEPTH else None)
elif self.tc_type == 'delay':
limit = chess.engine.Limit(
depth=self.max_depth if self.max_depth != MAX_DEPTH else None,
white_clock=self.base_ms/1000,
black_clock=self.base_ms/1000,
white_inc=self.inc_ms/1000,
black_inc=self.inc_ms/1000)
elif self.tc_type == 'timepermove':
limit = chess.engine.Limit(time=self.base_ms/1000,
depth=self.max_depth if
self.max_depth != MAX_DEPTH else None)
else:
limit = chess.engine.Limit(
depth=self.max_depth if self.max_depth != MAX_DEPTH else None,
white_clock=self.base_ms/1000,
black_clock=self.base_ms/1000,
white_inc=self.inc_ms/1000,
black_inc=self.inc_ms/1000)
start_time = time.perf_counter()
if self.analysis:
is_time_check = False
with self.engine.analysis(self.board, limit, multipv=self.multipv) as analysis:
with self._analysis_lock:
self._analysis_ref = analysis
# Check kill flag after storing the reference in case
# stop() was called between thread start and here.
if not self._kill.is_set():
for info in analysis:
if self._kill.is_set():
break
try:
line_number = int(info.get('multipv', 1))
depth = int(info['depth']) if 'depth' in info else self.depth
score = self.score
if 'score' in info:
score = int(
info['score'].relative.score(mate_score=32000)
) / 100
elapsed = info['time'] if 'time' in info else \
time.perf_counter() - start_time
pv = None
if 'pv' in info and not ('upperbound' in info or
'lowerbound' in info):
self.pv = info['pv'][0:self.pv_length]
if self.is_nomove_number_in_variation:
pv = self.short_variation_san()
else:
pv = self.board.variation_san(self.pv)
if line_number == 1:
self.bm = info['pv'][0]
if line_number == 1 and depth is not None:
self.depth = depth
if line_number == 1 and score is not None:
self.score = score
if line_number == 1:
self.time = elapsed
if pv is not None:
self.pv = pv
if score is not None and pv is not None and depth is not None:
if self.multipv > 1:
info_to_send = \
'{} | {:+5.2f} | {} | {:0.1f}s | {} multipv_info'.format(
line_number, score, depth, elapsed, pv)
else:
info_to_send = \
'{:+5.2f} | {} | {:0.1f}s | {} info_all'.format(
score, depth, elapsed, pv)
self.eng_queue.put('{}'.format(info_to_send))
# Send stop if movetime is exceeded
if not is_time_check \
and self.tc_type not in ('fischer', 'delay', 'infinite') \
and time.perf_counter() - start_time >= \
self.base_ms/1000:
logging.info('Max time limit is reached.')
is_time_check = True
break
# Send stop if max depth is exceeded
if 'depth' in info:
if int(info['depth']) >= self.max_depth \
and self.max_depth != MAX_DEPTH:
logging.info('Max depth limit is reached.')
break
except Exception:
logging.exception('Failed to parse search info.')
with self._analysis_lock:
self._analysis_ref = None
else:
result = self.engine.play(self.board, limit, info=chess.engine.INFO_ALL)
logging.info('result: {}'.format(result))
try:
self.depth = result.info['depth']
except KeyError:
self.depth = 1
logging.exception('depth is missing.')
try:
self.score = int(result.info['score'].relative.score(
mate_score=32000)) / 100
except KeyError:
self.score = 0
logging.exception('score is missing.')
try:
self.time = result.info['time'] if 'time' in result.info \
else time.perf_counter() - start_time
except KeyError:
self.time = 0
logging.exception('time is missing.')
try:
if 'pv' in result.info:
self.pv = result.info['pv'][0:self.pv_length]
if self.is_nomove_number_in_variation:
spv = self.short_variation_san()
self.pv = spv
else:
self.pv = self.board.variation_san(self.pv)
except Exception:
self.pv = None
logging.exception('pv is missing.')
if self.pv is not None:
info_to_send = '{:+5.2f} | {} | {:0.1f}s | {} info_all'.format(
self.score, self.depth, self.time, self.pv)
self.eng_queue.put('{}'.format(info_to_send))
self.bm = result.move
# Apply engine move delay if movetime is small
if self.is_move_delay:
while True:
if (self._kill.is_set()
or time.perf_counter() - start_time
>= self.move_delay_sec):
break
logging.info('Delay sending of best move {}'.format(self.bm))
time.sleep(1.0)
# If bm is None, we will use engine.play()
# Skip this fallback when the search was explicitly interrupted
# to avoid blocking the thread with an unconstrained engine call.
# Also skip when limit is None (infinite analysis) since
# engine.play() requires a concrete Limit object.
if self.bm is None and not self._kill.is_set() and limit is not None:
logging.info('bm is none, we will try engine,play().')
try:
result = self.engine.play(self.board, limit)
self.bm = result.move
except Exception:
logging.exception('Failed to get engine bestmove.')
self.eng_queue.put(f'bestmove {self.bm}')
logging.info(f'bestmove {self.bm}')
def quit_engine(self):
"""Quit engine.
Safe to call multiple times; subsequent calls are no-ops.
"""
if self.engine is None:
return
logging.info('quit engine')
try:
self.engine.quit()
except Exception:
logging.exception('Failed to quit engine.')
self.engine = None
def get_engine(self):
"""Return the engine instance without quitting it.
This allows the engine process to be reused across moves.
"""
return self.engine
def short_variation_san(self):
"""Returns variation in san but without move numbers."""
if self.pv is None:
return None
short_san_pv = []
tmp_board = self.board.copy()
for pc_move in self.pv:
san_move = tmp_board.san(pc_move)
short_san_pv.append(san_move)
tmp_board.push(pc_move)
return ' '.join(short_san_pv)
class EasyChessGui:
queue = queue.Queue()
is_user_white = True # White is at the bottom in board layout
def __init__(self, theme, engine_config_file, user_config_file,
gui_book_file, computer_book_file, human_book_file,
is_use_gui_book, is_random_book, max_book_ply,
max_depth=MAX_DEPTH):
self.theme = theme
self.user_config_file = user_config_file
self.engine_config_file = engine_config_file
self.gui_book_file = gui_book_file
self.computer_book_file = computer_book_file
self.human_book_file = human_book_file
self.max_depth = max_depth
self.is_use_gui_book = is_use_gui_book
self.is_random_book = is_random_book
self.max_book_ply = max_book_ply
self.opp_path_and_file = None
self.opp_file = None
self.opp_id_name = None
self.adviser_file = None
self.adviser_path_and_file = None
self.adviser_id_name = None
self.adviser_hash = 128
self.adviser_threads = 1
self.adviser_movetime_sec = 10
self.pecg_auto_save_game = 'pecg_auto_save_games.pgn'
self.settings_file = 'pecg_settings.json'
self.my_games = 'pecg_my_games.pgn'