-
Notifications
You must be signed in to change notification settings - Fork 56
/
python_easy_chess_gui.py
3626 lines (3067 loc) · 147 KB
/
python_easy_chess_gui.py
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 PySimpleGUI 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 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.DEBUG,
format=log_format
)
APP_NAME = 'Python Easy Chess GUI'
APP_VERSION = 'v1.19.0'
BOX_TITLE = f'{APP_NAME} {APP_VERSION}'
platform = sys.platform
sys_os = sys_plat.system()
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']
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
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_MSG = """The GUI has 2 modes, Play and Neutral. After startup
you are in Neutral mode. You can go to mode Play through Mode menu.
All games are auto-saved in pecg_auto_save_games.pgn.
Visit Game menu in Play mode to see other options to save the game.
It has to be noted you need to setup an engine to make the GUI works.
You can view which engines are ready for use via:
Engine->Set Engine Opponent.
(A) To setup an engine, you should be in Neutral mode.
1. Engine->Manage->Install, press the add button.
2. After engine setup, you can configure the engine options with:
a. Engine->Manage-Edit
b. Select the engine you want to edit and press Modify.
Before playing a game, you should select an engine opponent via
Engine->Set Engine Opponent.
You can also set an engine Adviser in the Engine menu.
During a game you can ask help from Adviser by right-clicking
the Adviser label and press show.
(B) To play a game
You should be in Play mode.
1. Mode->Play
2. Make move on the board
(C) To play as black
You should be in Neutral mode
1. Board->Flip
2. Mode->Play
3. Engine->Go
If you are already in Play mode, go back to
Neutral mode via Mode->Neutral
(D) To flip board
You should be in Neutral mode
1. Board->Flip
(E) To paste FEN
You should be in Play mode
1. Mode->Play
2. FEN->Paste
(F) To show engine search info after the move
1. Right-click on the Opponent Search Info and press Show
(G) To Show book 1 and 2
1. Right-click on Book 1 or 2 press Show
(H) To change board color
1. You should be in Neutral mode.
2. Board->Color.
(I) To change board theme
1. You should be in Neutral mode.
2. Board->Theme.
"""
# 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']],
['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 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']],
['&Help', ['GUI']],
]
# (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']],
['&Help', ['GUI']],
]
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):
"""
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:
"""
threading.Thread.__init__(self)
self._kill = threading.Event()
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 = None
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
def stop(self):
"""Interrupt engine search."""
self._kill.set()
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)
for p in data:
if p['name'] == self.engine_id_name:
for n in p['options']:
if n['name'].lower() == 'ownbook':
self.is_ownbook = True
# 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 run(self):
"""Run engine to get search info and bestmove.
If there is error we still send bestmove 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.')
# Set search limits
if 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) as analysis:
for info in analysis:
if self._kill.wait(0.1):
break
try:
if 'depth' in info:
self.depth = int(info['depth'])
if 'score' in info:
self.score = int(info['score'].relative.score(mate_score=32000))/100
self.time = info['time'] if 'time' in info else time.perf_counter() - start_time
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:
spv = self.short_variation_san()
self.pv = spv
else:
self.pv = self.board.variation_san(self.pv)
self.eng_queue.put('{} pv'.format(self.pv))
self.bm = info['pv'][0]
# score, depth, time, pv
if self.score is not None and \
self.pv is not None and self.depth 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))
# Send stop if movetime is exceeded
if not is_time_check and self.tc_type != 'fischer' \
and self.tc_type != 'delay' 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.')
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 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()
if self.bm is 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."""
logging.info('quit engine')
try:
self.engine.quit()
except AttributeError:
logging.info('AttributeError, self.engine is already None')
except Exception:
logging.exception('Failed to quit 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.my_games = 'pecg_my_games.pgn'
self.repertoire_file = {
'white': 'pecg_white_repertoire.pgn',
'black': 'pecg_black_repertoire.pgn'
}
self.init_game()
self.fen = None
self.psg_board = None
self.menu_elem = None
self.engine_id_name_list = []
self.engine_file_list = []
self.username = 'Human'
self.human_base_time_ms = 5 * 60 * 1000 # 5 minutes
self.human_inc_time_ms = 10 * 1000 # 10 seconds
self.human_period_moves = 0
self.human_tc_type = 'fischer'
self.engine_base_time_ms = 3 * 60 * 1000 # 5 minutes
self.engine_inc_time_ms = 2 * 1000 # 10 seconds
self.engine_period_moves = 0
self.engine_tc_type = 'fischer'
# Default board color is brown
self.sq_light_color = '#F0D9B5'
self.sq_dark_color = '#B58863'
# Move highlight, for brown board
self.move_sq_light_color = '#E8E18E'
self.move_sq_dark_color = '#B8AF4E'
self.gui_theme = 'Reddit'
self.is_save_time_left = False
self.is_save_user_comment = True
def update_game(self, mc: int, user_move: str, time_left: int, user_comment: str):
"""Saves moves in the game.
Args:
mc: move count
user_move: user's move
time_left: time left
user_comment: Can be a 'book' from the engine
"""
# Save user comment
if self.is_save_user_comment:
# If comment is empty
if not (user_comment and user_comment.strip()):
if mc == 1:
self.node = self.game.add_variation(user_move)
else:
self.node = self.node.add_variation(user_move)
# Save clock (time left after a move) as move comment
if self.is_save_time_left:
rem_time = self.get_time_h_mm_ss(time_left, False)
self.node.comment = '[%clk {}]'.format(rem_time)
else:
if mc == 1:
self.node = self.game.add_variation(user_move)
else:
self.node = self.node.add_variation(user_move)
# Save clock, add clock as comment after a move
if self.is_save_time_left:
rem_time = self.get_time_h_mm_ss(time_left, False)
self.node.comment = '[%clk {}] {}'.format(rem_time, user_comment)
else:
self.node.comment = user_comment
# Do not save user comment
else:
if mc == 1:
self.node = self.game.add_variation(user_move)
else:
self.node = self.node.add_variation(user_move)
# Save clock, add clock as comment after a move
if self.is_save_time_left:
rem_time = self.get_time_h_mm_ss(time_left, False)
self.node.comment = '[%clk {}]'.format(rem_time)
def create_new_window(self, window, flip=False):
"""Hide current window and creates a new window."""
loc = window.CurrentLocation()
window.Hide()
if flip:
self.is_user_white = not self.is_user_white
layout = self.build_main_layout(self.is_user_white)
w = sg.Window(
'{} {}'.format(APP_NAME, APP_VERSION),
layout,
default_button_element_size=(12, 1),
auto_size_buttons=False,
location=(loc[0], loc[1]),
icon=ico_path[platform]['pecg']
)
# Initialize White and black boxes
while True:
button, value = w.Read(timeout=50)
self.update_labels_and_game_tags(w, human=self.username)
break
window.Close()
return w
def delete_player(self, name, pgn, que):
"""
Delete games of player name in pgn.
:param name:
:param pgn:
:param que:
:return:
"""
logging.info('Enters delete_player()')
pgn_path = Path(pgn)
folder_path = pgn_path.parents[0]
file = PurePath(pgn)
pgn_file = file.name
# Create backup of orig
backup = pgn_file + '.backup'
backup_path = Path(folder_path, backup)
backup_path.touch()
origfile_text = Path(pgn).read_text()
backup_path.write_text(origfile_text)
logging.info(f'backup copy {backup_path} is successfully created.')
# Define output file
output = 'out_' + pgn_file
output_path = Path(folder_path, output)
logging.info(f'output {output_path} is successfully created.')
logging.info(f'Deleting player {name}.')
gcnt = 0
# read pgn and save each game if player name to be deleted is not in
# the game, either white or black.
with open(output_path, 'a') as f:
with open(pgn_path) as h:
game = chess.pgn.read_game(h)
while game:
gcnt += 1
que.put('Delete, {}, processing game {}'.format(
name, gcnt))
wp = game.headers['White']
bp = game.headers['Black']
# If this game has no player with name to be deleted
if wp != name and bp != name:
f.write('{}\n\n'.format(game))
game = chess.pgn.read_game(h)
if output_path.exists():
logging.info(f'Deleting player {name} is successful.')
# Delete the orig file and rename the current output to orig file
pgn_path.unlink()
logging.info('Delete orig pgn file')
output_path.rename(pgn_path)
logging.info('Rename output to orig pgn file')
que.put('Done')
def get_players(self, pgn, q):
logging.info('Enters get_players()')
players = []
games = 0
with open(pgn) as h:
while True:
headers = chess.pgn.read_headers(h)
if headers is None:
break
wp = headers['White']
bp = headers['Black']
players.append(wp)
players.append(bp)
games += 1
p = list(set(players))
ret = [p, games]
q.put(ret)
def get_engine_id_name(self, path_and_file, q):
""" Returns id name of uci engine """
id_name = None
folder = Path(path_and_file)
folder = folder.parents[0]
try:
if sys_os == 'Windows':
engine = chess.engine.SimpleEngine.popen_uci(
path_and_file, cwd=folder,
creationflags=subprocess.CREATE_NO_WINDOW)
else:
engine = chess.engine.SimpleEngine.popen_uci(
path_and_file, cwd=folder)
id_name = engine.id['name']
engine.quit()
except Exception:
logging.exception('Failed to get id name.')
q.put(['Done', id_name])
def get_engine_hash(self, eng_id_name):
""" Returns hash value from engine config file """
eng_hash = None
with open(self.engine_config_file, 'r') as json_file:
data = json.load(json_file)
for p in data:
if p['name'] == eng_id_name:
# There engines without options
try:
for n in p['options']:
if n['name'].lower() == 'hash':
return n['value']
except KeyError:
logging.info(f'This engine {eng_id_name} has no option.')
break
except Exception:
logging.exception('Failed to get engine hash.')
return eng_hash
def get_engine_threads(self, eng_id_name):
"""
Returns number of threads of eng_id_name from pecg_engines.json.
:param eng_id_name: the engine id name
:return: number of threads
"""
eng_threads = None
with open(self.engine_config_file, 'r') as json_file:
data = json.load(json_file)
for p in data:
if p['name'] == eng_id_name:
try:
for n in p['options']:
if n['name'].lower() == 'threads':
return n['value']
except KeyError:
logging.info(f'This engine {eng_id_name} has no options.')
break
except Exception:
logging.exception('Failed to get engine threads.')
return eng_threads
def get_engine_file(self, eng_id_name):
"""
Returns eng_id_name's filename and path from pecg_engines.json file.
:param eng_id_name: engine id name
:return: engine file and its path
"""
eng_file, eng_path_and_file = None, None
with open(self.engine_config_file, 'r') as json_file:
data = json.load(json_file)
for p in data:
if p['name'] == eng_id_name:
eng_file = p['command']
eng_path_and_file = Path(p['workingDirectory'],
eng_file).as_posix()
break
return eng_file, eng_path_and_file
def get_engine_id_name_list(self):
"""
Read engine config file.
:return: list of engine id names
"""
eng_id_name_list = []
with open(self.engine_config_file, 'r') as json_file:
data = json.load(json_file)
for p in data:
if p['protocol'] == 'uci':
eng_id_name_list.append(p['name'])
eng_id_name_list = sorted(eng_id_name_list)
return eng_id_name_list
def update_user_config_file(self, username):
"""
Update user config file. If username does not exist, save it.
:param username:
:return:
"""
with open(self.user_config_file, 'r') as json_file:
data = json.load(json_file)
# Add the new entry if it does not exist
is_name = False
for i in range(len(data)):
if data[i]['username'] == username:
is_name = True
break
if not is_name:
data.append({'username': username})
# Save
with open(self.user_config_file, 'w') as h:
json.dump(data, h, indent=4)
def check_user_config_file(self):