-
Notifications
You must be signed in to change notification settings - Fork 0
/
engine_wrapper.py
1284 lines (1084 loc) · 56.1 KB
/
engine_wrapper.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
"""Provides communication with the engine."""
from __future__ import annotations
import os
import chess.engine
import chess.polyglot
import chess.syzygy
import chess.gaviota
import subprocess
import logging
import time
import random
from collections import Counter
from contextlib import contextmanager
import config
import model
import lichess
from config import Configuration
from typing import Dict, Any, List, Optional, Union, Tuple, Generator, Callable, Type
OPTIONS_TYPE = Dict[str, Any]
MOVE_INFO_TYPE = Dict[str, Any]
COMMANDS_TYPE = List[str]
LICHESS_EGTB_MOVE = Dict[str, Any]
CHESSDB_EGTB_MOVE = Dict[str, Any]
MOVE = Union[chess.engine.PlayResult, List[chess.Move]]
logger = logging.getLogger(__name__)
out_of_online_opening_book_moves: Counter[str] = Counter()
@contextmanager
def create_engine(engine_config: config.Configuration) -> Generator[EngineWrapper, None, None]:
"""
Create the engine.
Use in a with-block to automatically close the engine when exiting the game.
:param engine_config: The options for the engine.
:return: An engine. Either UCI, XBoard, or Homemade.
"""
cfg = engine_config.engine
engine_path = os.path.join(cfg.dir, cfg.name)
engine_type = cfg.protocol
commands = [engine_path]
if cfg.engine_options:
for k, v in cfg.engine_options.items():
commands.append(f"--{k}={v}")
stderr = None if cfg.silence_stderr else subprocess.DEVNULL
Engine: Union[Type[UCIEngine], Type[XBoardEngine], Type[MinimalEngine]]
if engine_type == "xboard":
Engine = XBoardEngine
elif engine_type == "uci":
Engine = UCIEngine
elif engine_type == "homemade":
Engine = getHomemadeEngine(cfg.name)
else:
raise ValueError(
f" Invalid engine type: {engine_type}. Expected xboard, uci, or homemade.")
options = remove_managed_options(cfg.lookup(f"{engine_type}_options") or config.Configuration({}))
logger.debug(f"Starting engine: {commands}")
engine = Engine(commands, options, stderr, cfg.draw_or_resign, cwd=cfg.working_dir)
try:
yield engine
finally:
engine.stop()
engine.ping()
engine.quit()
def remove_managed_options(config: config.Configuration) -> OPTIONS_TYPE:
"""Remove the options managed by python-chess."""
def is_managed(key: str) -> bool:
return chess.engine.Option(key, "", None, None, None, None).is_managed()
return {name: value for (name, value) in config.items() if not is_managed(name)}
def translate_termination(game: model.Game, board: chess.Board) -> str:
"""Get a human-readable string with the result of the game."""
winner_color = game.state.get("winner", "")
termination: Optional[str] = game.state.get("status")
if termination == model.Termination.MATE:
return f"{winner_color.title()} mates"
elif termination == model.Termination.TIMEOUT:
return "Time forfeiture" if winner_color else "Timeout with insufficient material"
elif termination == model.Termination.RESIGN:
resigner = "black" if winner_color == "white" else "white"
return f"{resigner.title()} resigns"
elif termination == model.Termination.ABORT:
return "Game aborted"
elif termination == model.Termination.DRAW:
if board.is_fifty_moves():
return "50-move rule"
elif board.is_repetition():
return "Threefold repetition"
elif board.is_insufficient_material():
return "Insufficient material"
else:
return "Draw by agreement"
elif termination:
return termination
else:
return ""
PONDERPV_CHARACTERS = 6 # The length of ", PV: ".
class EngineWrapper:
"""A wrapper used by all engines (UCI, XBoard, Homemade)."""
def __init__(self, options: OPTIONS_TYPE, draw_or_resign: config.Configuration) -> None:
"""
Initialize the values of the wrapper used by all engines (UCI, XBoard, Homemade).
:param options: The options to send to the engine.
:param draw_or_resign: Options on whether the bot should resign or offer draws.
"""
self.engine: Union[chess.engine.SimpleEngine, FillerEngine]
self.scores: List[chess.engine.PovScore] = []
self.draw_or_resign = draw_or_resign
self.go_commands = config.Configuration(options.pop("go_commands", {}) or {})
self.move_commentary: List[MOVE_INFO_TYPE] = []
self.comment_start_index = -1
def play_move(self,
board: chess.Board,
game: model.Game,
li: lichess.Lichess,
start_time: int,
move_overhead: int,
can_ponder: bool,
is_correspondence: bool,
correspondence_move_time: int,
engine_cfg: config.Configuration) -> None:
"""
Play a move.
:param board: The current position.
:param game: The game that the bot is playing.
:param li: Provides communication with lichess.org.
:param start_time: The time that the bot received the move.
:param move_overhead: The time it takes to communicate between the engine and lichess.org.
:param can_ponder: Whether the engine is allowed to ponder.
:param is_correspondence: Whether this is a correspondence or unlimited game.
:param correspondence_move_time: The time the engine will think if `is_correspondence` is true.
:param engine_cfg: Options for external moves (e.g. from an opening book), and for engine resignation and draw offers.
:return: The move to play.
"""
polyglot_cfg = engine_cfg.polyglot
online_moves_cfg = engine_cfg.online_moves
draw_or_resign_cfg = engine_cfg.draw_or_resign
lichess_bot_tbs = engine_cfg.lichess_bot_tbs
best_move: MOVE
best_move = get_book_move(board, game, polyglot_cfg)
if best_move.move is None:
best_move = get_egtb_move(board,
game,
lichess_bot_tbs,
draw_or_resign_cfg)
if not isinstance(best_move, list) and best_move.move is None:
best_move = get_online_move(li,
board,
game,
online_moves_cfg,
draw_or_resign_cfg)
if isinstance(best_move, list) or best_move.move is None:
draw_offered = check_for_draw_offer(game)
if len(board.move_stack) < 2:
time_limit = first_move_time(game)
can_ponder = False # No pondering after the first move since a new clock starts afterwards.
elif is_correspondence:
time_limit = single_move_time(board, game, correspondence_move_time, start_time, move_overhead)
else:
time_limit = game_clock_time(board, game, start_time, move_overhead)
best_move = self.search(board, time_limit, can_ponder, draw_offered, best_move)
else:
self.stop()
self.add_comment(best_move, board)
self.print_stats()
if best_move.resigned and len(board.move_stack) >= 2:
li.resign(game.id)
else:
li.make_move(game.id, best_move)
def add_go_commands(self, time_limit: chess.engine.Limit) -> chess.engine.Limit:
"""Add extra commands to send to the engine. For example, to search for 1000 nodes or up to depth 10."""
movetime = self.go_commands.movetime
if movetime is not None:
movetime_sec = float(movetime) / 1000
if time_limit.time is None or time_limit.time > movetime_sec:
time_limit.time = movetime_sec
time_limit.depth = self.go_commands.depth
time_limit.nodes = self.go_commands.nodes
return time_limit
def offer_draw_or_resign(self, result: chess.engine.PlayResult, board: chess.Board) -> chess.engine.PlayResult:
"""Offer draw or resign depending on the score of the engine."""
def actual(score: chess.engine.PovScore) -> int:
return score.relative.score(mate_score=40000)
can_offer_draw = self.draw_or_resign.offer_draw_enabled
draw_offer_moves = self.draw_or_resign.offer_draw_moves
draw_score_range: int = self.draw_or_resign.offer_draw_score
draw_max_piece_count = self.draw_or_resign.offer_draw_pieces
pieces_on_board = chess.popcount(board.occupied)
enough_pieces_captured = pieces_on_board <= draw_max_piece_count
if can_offer_draw and len(self.scores) >= draw_offer_moves and enough_pieces_captured:
scores = self.scores[-draw_offer_moves:]
def score_near_draw(score: chess.engine.PovScore) -> bool:
return abs(actual(score)) <= draw_score_range
if len(scores) == len(list(filter(score_near_draw, scores))):
result.draw_offered = True
resign_enabled = self.draw_or_resign.resign_enabled
min_moves_for_resign = self.draw_or_resign.resign_moves
resign_score: int = self.draw_or_resign.resign_score
if resign_enabled and len(self.scores) >= min_moves_for_resign:
scores = self.scores[-min_moves_for_resign:]
def score_near_loss(score: chess.engine.PovScore) -> bool:
return actual(score) <= resign_score
if len(scores) == len(list(filter(score_near_loss, scores))):
result.resigned = True
return result
def search(self, board: chess.Board, time_limit: chess.engine.Limit, ponder: bool, draw_offered: bool,
root_moves: MOVE) -> chess.engine.PlayResult:
"""
Tell the engine to search.
:param board: The current position.
:param time_limit: Conditions for how long the engine can search (e.g. we have 10 seconds and search up to depth 10).
:param ponder: Whether the engine can ponder.
:param draw_offered: Whether the bot was offered a draw.
:param root_moves: If it is a list, the engine will only play a move that is in `root_moves`.
:return: The move to play.
"""
time_limit = self.add_go_commands(time_limit)
result = self.engine.play(board,
time_limit,
info=chess.engine.INFO_ALL,
ponder=ponder,
draw_offered=draw_offered,
root_moves=root_moves if isinstance(root_moves, list) else None)
# Use null_score to have no effect on draw/resign decisions
null_score = chess.engine.PovScore(chess.engine.Mate(1), board.turn)
self.scores.append(result.info.get("score", null_score))
result = self.offer_draw_or_resign(result, board)
return result
def comment_index(self, move_stack_index: int) -> int:
"""
Get the index of a move for use in `comment_for_board_index`.
:param move_stack_index: The move number.
:return: The index of the move in `self.move_commentary`.
"""
if self.comment_start_index < 0:
return -1
else:
return move_stack_index - self.comment_start_index
def comment_for_board_index(self, index: int) -> MOVE_INFO_TYPE:
"""
Get the engine comments for a specific move.
:param index: The move number.
:return: The move comments.
"""
no_info: MOVE_INFO_TYPE = {}
comment_index = self.comment_index(index)
if comment_index < 0 or comment_index % 2 != 0:
return no_info
try:
return self.move_commentary[comment_index // 2]
except IndexError:
return no_info
def add_comment(self, move: chess.engine.PlayResult, board: chess.Board) -> None:
"""
Store the move's comments.
:param move: The move. Contains the comments in `move.info`.
:param board: The current position.
"""
if self.comment_start_index < 0:
self.comment_start_index = len(board.move_stack)
move_info: MOVE_INFO_TYPE = dict(move.info.copy()) if move.info else {}
if "pv" in move_info:
move_info["ponderpv"] = board.variation_san(move.info["pv"])
if "refutation" in move_info:
move_info["refutation"] = board.variation_san(move.info["refutation"])
if "currmove" in move_info:
move_info["currmove"] = board.san(move.info["currmove"])
self.move_commentary.append(move_info)
def print_stats(self) -> None:
"""Print the engine stats."""
for line in self.get_stats():
logger.info(line)
def readable_score(self, relative_score: chess.engine.PovScore) -> str:
"""Convert the score to a more human-readable format."""
score = relative_score.relative
cp_score = score.score()
if cp_score is None:
str_score = f"#{score.mate()}"
else:
str_score = str(round(cp_score / 100, 2))
return str_score
def readable_wdl(self, wdl: chess.engine.PovWdl) -> str:
"""Convert the WDL score to a percentage, so it is more human-readable."""
wdl_percentage = round(wdl.relative.expectation() * 100, 1)
return f"{wdl_percentage}%"
def readable_number(self, number: int) -> str:
"""Convert number to a more human-readable format. e.g. 123456789 -> 123M."""
if number >= 1e9:
return f"{round(number / 1e9, 1)}B"
elif number >= 1e6:
return f"{round(number / 1e6, 1)}M"
elif number >= 1e3:
return f"{round(number / 1e3, 1)}K"
return str(number)
def get_stats(self, for_chat: bool = False) -> List[str]:
"""
Get the stats returned by the engine.
:param for_chat: Whether the stats will be sent to the game chat, which has a 140 character limit.
"""
can_index = self.move_commentary and self.move_commentary[-1]
info: MOVE_INFO_TYPE = self.move_commentary[-1].copy() if can_index else {}
def to_readable_value(stat: str, info: MOVE_INFO_TYPE) -> str:
readable: Dict[str, Callable[[Any], str]] = {"score": self.readable_score, "wdl": self.readable_wdl,
"hashfull": lambda x: f"{round(x / 10, 1)}%",
"nodes": self.readable_number,
"nps": lambda x: f"{self.readable_number(x)}nps",
"tbhits": self.readable_number,
"cpuload": lambda x: f"{round(x / 10, 1)}%"}
def identity(x: Any) -> str:
return str(x)
return str(readable.get(stat, identity)(info[stat]))
def to_readable_key(stat: str) -> str:
readable = {"wdl": "winrate", "ponderpv": "PV", "nps": "speed", "score": "evaluation"}
stat = readable.get(stat, stat)
return stat.title()
stats = ["score", "wdl", "depth", "nodes", "nps", "ponderpv"]
if for_chat and "ponderpv" in info:
bot_stats = [f"{to_readable_key(stat)}: {to_readable_value(stat, info)}"
for stat in stats if stat in info and stat != "ponderpv"]
len_bot_stats = len(", ".join(bot_stats)) + PONDERPV_CHARACTERS
ponder_pv = info["ponderpv"].split()
try:
while len(" ".join(ponder_pv)) + len_bot_stats > lichess.MAX_CHAT_MESSAGE_LEN:
ponder_pv.pop()
if ponder_pv[-1].endswith("."):
ponder_pv.pop()
info["ponderpv"] = " ".join(ponder_pv)
except IndexError:
pass
if not info["ponderpv"]:
info.pop("ponderpv")
return [f"{to_readable_key(stat)}: {to_readable_value(stat, info)}" for stat in stats if stat in info]
def get_opponent_info(self, game: model.Game) -> None:
"""Get the opponent's information and sends it to the engine. Depends on the protocol."""
pass
def name(self) -> str:
"""Get the name of the engine."""
engine_info: Dict[str, str] = dict(self.engine.id)
name: str = engine_info["name"]
return name
def report_game_result(self, game: model.Game, board: chess.Board) -> None:
"""Report the game result to the engine. Depends on the protocol."""
pass
def stop(self) -> None:
"""Stop the engine. Depends on the protocol."""
pass
def get_pid(self) -> str:
"""Get the pid of the engine."""
pid = "?"
if self.engine.transport is not None:
pid = str(self.engine.transport.get_pid())
return pid
def ping(self) -> None:
"""Ping the engine."""
self.engine.ping()
def quit(self) -> None:
"""Close the engine."""
self.engine.quit()
self.engine.close()
class UCIEngine(EngineWrapper):
"""The class used to communicate with UCI engines."""
def __init__(self, commands: COMMANDS_TYPE, options: OPTIONS_TYPE, stderr: Optional[int],
draw_or_resign: config.Configuration, **popen_args: str) -> None:
"""
Communicate with UCI engines.
:param commands: The engine path and commands to send to the engine. e.g. ["engines/engine.exe", "--option1=value1"]
:param options: The options to send to the engine.
:param stderr: Whether we should silence the stderr.
:param draw_or_resign: Options on whether the bot should resign or offer draws.
:param popen_args: The cwd of the engine.
"""
super().__init__(options, draw_or_resign)
self.engine = chess.engine.SimpleEngine.popen_uci(commands, timeout=10., debug=False, setpgrp=False, stderr=stderr,
**popen_args)
self.engine.configure(options)
def stop(self) -> None:
"""Tell the engine to stop searching."""
self.engine.protocol.send_line("stop")
def get_opponent_info(self, game: model.Game) -> None:
"""Get the opponent's info and send it to the engine."""
name = game.opponent.name
if (name and isinstance(self.engine.protocol, chess.engine.UciProtocol)
and "UCI_Opponent" in self.engine.protocol.config):
rating = game.opponent.rating or "none"
title = game.opponent.title or "none"
player_type = "computer" if title == "BOT" else "human"
self.engine.configure({"UCI_Opponent": f"{title} {rating} {player_type} {name}"})
def report_game_result(self, game: model.Game, board: chess.Board) -> None:
"""Send the game result to the engine."""
if isinstance(self.engine.protocol, chess.engine.UciProtocol):
self.engine.protocol._position(board)
class XBoardEngine(EngineWrapper):
"""The class used to communicate with XBoard engines."""
def __init__(self, commands: COMMANDS_TYPE, options: OPTIONS_TYPE, stderr: Optional[int],
draw_or_resign: config.Configuration, **popen_args: str) -> None:
"""
Communicate with XBoard engines.
:param commands: The engine path and commands to send to the engine. e.g. ["engines/engine.exe", "--option1=value1"]
:param options: The options to send to the engine.
:param stderr: Whether we should silence the stderr.
:param draw_or_resign: Options on whether the bot should resign or offer draws.
:param popen_args: The cwd of the engine.
"""
super().__init__(options, draw_or_resign)
self.engine = chess.engine.SimpleEngine.popen_xboard(commands, timeout=10., debug=False, setpgrp=False,
stderr=stderr, **popen_args)
egt_paths = options.pop("egtpath", {}) or {}
features = self.engine.protocol.features if isinstance(self.engine.protocol, chess.engine.XBoardProtocol) else {}
egt_features = features.get("egt", "")
if isinstance(egt_features, str):
egt_types_from_engine = egt_features.split(",")
egt_type: str
for egt_type in filter(None, egt_types_from_engine):
if egt_type in egt_paths:
options[f"egtpath {egt_type}"] = egt_paths[egt_type]
else:
logger.debug(f"No paths found for egt type: {egt_type}.")
self.engine.configure(options)
def report_game_result(self, game: model.Game, board: chess.Board) -> None:
"""Send the game result to the engine."""
# Send final moves, if any, to engine.
if isinstance(self.engine.protocol, chess.engine.XBoardProtocol):
self.engine.protocol._new(board, None, {})
endgame_message = translate_termination(game, board)
if endgame_message:
endgame_message = " {" + endgame_message + "}"
self.engine.protocol.send_line(f"result {game.result()}{endgame_message}")
def stop(self) -> None:
"""Tell the engine to stop searching."""
self.engine.protocol.send_line("?")
def get_opponent_info(self, game: model.Game) -> None:
"""Get the opponent's info and send it to the engine."""
if (game.opponent.name and isinstance(self.engine.protocol, chess.engine.XBoardProtocol)
and self.engine.protocol.features.get("name", True)):
title = f"{game.opponent.title} " if game.opponent.title else ""
self.engine.protocol.send_line(f"name {title}{game.opponent.name}")
if game.me.rating and game.opponent.rating:
self.engine.protocol.send_line(f"rating {game.me.rating} {game.opponent.rating}")
if game.opponent.title == "BOT":
self.engine.protocol.send_line("computer")
class MinimalEngine(EngineWrapper):
"""
Subclass this to prevent a few random errors.
Even though MinimalEngine extends EngineWrapper,
you don't have to actually wrap an engine.
At minimum, just implement `search`,
however you can also change other methods like
`notify`, etc.
"""
def __init__(self, commands: COMMANDS_TYPE, options: OPTIONS_TYPE, stderr: Optional[int],
draw_or_resign: Configuration, name: Optional[str] = None, **popen_args: str) -> None:
"""
Initialize the values of the engine that all homemade engines inherit.
:param options: The options to send to the engine.
:param draw_or_resign: Options on whether the bot should resign or offer draws.
"""
super().__init__(options, draw_or_resign)
self.engine_name = self.__class__.__name__ if name is None else name
self.engine = FillerEngine(self, name=self.engine_name)
def get_pid(self) -> str:
"""Homemade engines don't have a pid, so we return a question mark."""
return "?"
def search(self, board: chess.Board, time_limit: chess.engine.Limit, ponder: bool, draw_offered: bool,
root_moves: MOVE) -> chess.engine.PlayResult:
"""
Choose a move.
The method to be implemented in your homemade engine.
NOTE: This method must return an instance of "chess.engine.PlayResult"
"""
raise NotImplementedError("The search method is not implemented")
def notify(self, method_name: str, *args: Any, **kwargs: Any) -> None:
"""
Enable the use of `self.engine.option1`.
The EngineWrapper class sometimes calls methods on "self.engine".
"self.engine" is a filler property that notifies <self>
whenever an attribute is called.
Nothing happens unless the main engine does something.
Simply put, the following code is equivalent
self.engine.<method_name>(<*args>, <**kwargs>)
self.notify(<method_name>, <*args>, <**kwargs>)
"""
pass
class FillerEngine:
"""
Not meant to be an actual engine.
This is only used to provide the property "self.engine"
in "MinimalEngine" which extends "EngineWrapper"
"""
def __init__(self, main_engine: MinimalEngine, name: str = "") -> None:
""":param name: The name to send to the chat."""
self.id: Dict[str, str] = {
"name": name
}
self.name = name
self.main_engine = main_engine
def __getattr__(self, method_name: str) -> Any:
"""Provide the property `self.engine`."""
main_engine = self.main_engine
def method(*args: Any, **kwargs: Any) -> Any:
nonlocal main_engine
nonlocal method_name
return main_engine.notify(method_name, *args, **kwargs)
return method
def getHomemadeEngine(name: str) -> Type[MinimalEngine]:
"""
Get the homemade engine with name `name`. e.g. If `name` is `RandomMove` then we will return `strategies.RandomMove`.
:param name: The name of the homemade engine.
:return: The engine with this name.
"""
import strategies
engine: Type[MinimalEngine] = getattr(strategies, name)
return engine
def single_move_time(board: chess.Board, game: model.Game, search_time: int,
start_time: int, move_overhead: int) -> chess.engine.Limit:
"""
Calculate time to search in correspondence games.
:param board: The current positions.
:param game: The game that the bot is playing.
:param search_time: How long the engine should search.
:param start_time: The time we have left.
:param move_overhead: The time it takes to communicate between the engine and lichess-bot.
:return: The time to choose a move.
"""
pre_move_time = int((time.perf_counter_ns() - start_time) / 1e6)
overhead = pre_move_time + move_overhead
wb = "w" if board.turn == chess.WHITE else "b"
clock_time = max(0, game.state[f"{wb}time"] - overhead)
search_time = min(search_time, clock_time)
logger.info(f"Searching for time {search_time} for game {game.id}")
return chess.engine.Limit(time=search_time / 1000)
def first_move_time(game: model.Game) -> chess.engine.Limit:
"""
Determine time limit for the first move in the game.
:param game: The game that the bot is playing.
:return: The time to choose the first move.
"""
# Need to hardcode first movetime (10000 ms) since Lichess has 30 sec limit.
search_time = 10000
logger.info(f"Searching for time {search_time} for game {game.id}")
return chess.engine.Limit(time=search_time / 1000)
def game_clock_time(board: chess.Board, game: model.Game, start_time: int, move_overhead: int) -> chess.engine.Limit:
"""
Get the time to play by the engine in realtime games.
:param board: The current positions.
:param game: The game that the bot is playing.
:param start_time: The time we have left.
:param move_overhead: The time it takes to communicate between the engine and lichess-bot.
:return: The time to play a move.
"""
pre_move_time = int((time.perf_counter_ns() - start_time) / 1e6)
overhead = pre_move_time + move_overhead
wb = "w" if board.turn == chess.WHITE else "b"
game.state[f"{wb}time"] = max(0, game.state[f"{wb}time"] - overhead)
logger.info("Searching for wtime {wtime} btime {btime}".format_map(game.state) + f" for game {game.id}")
return chess.engine.Limit(white_clock=game.state["wtime"] / 1000,
black_clock=game.state["btime"] / 1000,
white_inc=game.state["winc"] / 1000,
black_inc=game.state["binc"] / 1000)
def check_for_draw_offer(game: model.Game) -> bool:
"""Check if the bot was offered a draw."""
return game.state.get(f"{game.opponent_color[0]}draw", False)
def get_book_move(board: chess.Board, game: model.Game,
polyglot_cfg: config.Configuration) -> chess.engine.PlayResult:
"""Get a move from an opening book."""
no_book_move = chess.engine.PlayResult(None, None)
use_book = polyglot_cfg.enabled
max_game_length = polyglot_cfg.max_depth * 2 - 1
if not use_book or len(board.move_stack) > max_game_length:
return no_book_move
variant = "standard" if board.uci_variant == "chess" else str(board.uci_variant)
config.change_value_to_list(polyglot_cfg.config, "book", key=variant)
books = polyglot_cfg.book.lookup(variant)
for book in books:
with chess.polyglot.open_reader(book) as reader:
try:
selection = polyglot_cfg.selection
min_weight = polyglot_cfg.min_weight
if selection == "weighted_random":
move = reader.weighted_choice(board).move
elif selection == "uniform_random":
move = reader.choice(board, minimum_weight=min_weight).move
elif selection == "best_move":
move = reader.find(board, minimum_weight=min_weight).move
except IndexError:
# python-chess raises "IndexError" if no entries found.
move = None
if move is not None:
logger.info(f"Got move {move} from book {book} for game {game.id}")
return chess.engine.PlayResult(move, None)
return no_book_move
def get_online_move(li: lichess.Lichess, board: chess.Board, game: model.Game, online_moves_cfg: config.Configuration,
draw_or_resign_cfg: config.Configuration) -> Union[chess.engine.PlayResult, List[chess.Move]]:
"""
Get a move from an online source.
If `move_quality` is `suggest`, then it will return a list of moves for the engine to choose from.
"""
online_egtb_cfg = online_moves_cfg.online_egtb
chessdb_cfg = online_moves_cfg.chessdb_book
lichess_cloud_cfg = online_moves_cfg.lichess_cloud_analysis
max_out_of_book_moves = online_moves_cfg.max_out_of_book_moves
offer_draw = False
resign = False
comment: Optional[chess.engine.InfoDict] = None
best_move, wdl = get_online_egtb_move(li, board, game, online_egtb_cfg)
if best_move is not None:
can_offer_draw = draw_or_resign_cfg.offer_draw_enabled
offer_draw_for_zero = draw_or_resign_cfg.offer_draw_for_egtb_zero
if can_offer_draw and offer_draw_for_zero and wdl == 0:
offer_draw = True
can_resign = draw_or_resign_cfg.resign_enabled
resign_on_egtb_loss = draw_or_resign_cfg.resign_for_egtb_minus_two
if can_resign and resign_on_egtb_loss and wdl == -2:
resign = True
wdl_to_score = {2: 9900, 1: 500, 0: 0, -1: -500, -2: -9900}
comment = {"score": chess.engine.PovScore(chess.engine.Cp(wdl_to_score[wdl]), board.turn)}
elif out_of_online_opening_book_moves[game.id] < max_out_of_book_moves:
best_move, comment = get_chessdb_move(li, board, game, chessdb_cfg)
if best_move is None and out_of_online_opening_book_moves[game.id] < max_out_of_book_moves:
best_move, comment = get_lichess_cloud_move(li, board, game, lichess_cloud_cfg)
if best_move:
if isinstance(best_move, str):
return chess.engine.PlayResult(chess.Move.from_uci(best_move),
None,
comment,
draw_offered=offer_draw,
resigned=resign)
return [chess.Move.from_uci(move) for move in best_move]
out_of_online_opening_book_moves[game.id] += 1
used_opening_books = chessdb_cfg.enabled or lichess_cloud_cfg.enabled
if out_of_online_opening_book_moves[game.id] == max_out_of_book_moves and used_opening_books:
logger.info(f"Will stop using online opening books for game {game.id}.")
return chess.engine.PlayResult(None, None)
def get_chessdb_move(li: lichess.Lichess, board: chess.Board, game: model.Game,
chessdb_cfg: config.Configuration) -> Tuple[Optional[str], Optional[chess.engine.InfoDict]]:
"""Get a move from chessdb.cn's opening book."""
wb = "w" if board.turn == chess.WHITE else "b"
use_chessdb = chessdb_cfg.enabled
time_left = game.state[f"{wb}time"]
min_time = chessdb_cfg.min_time * 1000
if not use_chessdb or time_left < min_time or board.uci_variant != "chess":
return None, None
move = None
comment: chess.engine.InfoDict = {}
site = "https://www.chessdb.cn/cdb.php"
quality = chessdb_cfg.move_quality
action = {"best": "querypv",
"good": "querybest",
"all": "query"}
try:
params = {"action": action[quality],
"board": board.fen(),
"json": 1}
data = li.online_book_get(site, params=params)
if data["status"] == "ok":
if quality == "best":
depth = data["depth"]
if depth >= chessdb_cfg.min_depth:
score = data["score"]
move = data["pv"][0]
comment["score"] = chess.engine.PovScore(chess.engine.Cp(score), board.turn)
comment["depth"] = data["depth"]
comment["pv"] = list(map(chess.Move.from_uci, data["pv"]))
logger.info(f"Got move {move} from chessdb.cn (depth: {depth}, score: {score}) for game {game.id}")
else:
move = data["move"]
logger.info(f"Got move {move} from chessdb.cn for game {game.id}")
if chessdb_cfg.contribute:
params["action"] = "queue"
li.online_book_get(site, params=params)
except Exception:
pass
return move, comment
def get_lichess_cloud_move(li: lichess.Lichess, board: chess.Board, game: model.Game,
lichess_cloud_cfg: config.Configuration) -> Tuple[Optional[str], Optional[chess.engine.InfoDict]]:
"""Get the move from the lichess's cloud analysis."""
wb = "w" if board.turn == chess.WHITE else "b"
time_left = game.state[f"{wb}time"]
min_time = lichess_cloud_cfg.min_time * 1000
use_lichess_cloud = lichess_cloud_cfg.enabled
if not use_lichess_cloud or time_left < min_time:
return None, None
move = None
comment: chess.engine.InfoDict = {}
quality = lichess_cloud_cfg.move_quality
multipv = 1 if quality == "best" else 5
variant = "standard" if board.uci_variant == "chess" else board.uci_variant
try:
data = li.online_book_get("https://lichess.org/api/cloud-eval",
params={"fen": board.fen(),
"multiPv": multipv,
"variant": variant})
if "error" not in data:
depth = data["depth"]
knodes = data["knodes"]
min_depth = lichess_cloud_cfg.min_depth
min_knodes = lichess_cloud_cfg.min_knodes
if depth >= min_depth and knodes >= min_knodes:
if quality == "best":
pv = data["pvs"][0]
else:
best_eval = data["pvs"][0]["cp"]
pvs = data["pvs"]
max_difference = lichess_cloud_cfg.max_score_difference
if wb == "w":
pvs = list(filter(lambda pv: pv["cp"] >= best_eval - max_difference, pvs))
else:
pvs = list(filter(lambda pv: pv["cp"] <= best_eval + max_difference, pvs))
pv = random.choice(pvs)
move = pv["moves"].split()[0]
score = pv["cp"] if wb == "w" else -pv["cp"]
comment["score"] = chess.engine.PovScore(chess.engine.Cp(score), board.turn)
comment["depth"] = data["depth"]
comment["nodes"] = data["knodes"] * 1000
comment["pv"] = list(map(chess.Move.from_uci, pv["moves"].split()))
logger.info(f"Got move {move} from lichess cloud analysis (depth: {depth}, score: {score}, knodes: {knodes})"
f" for game {game.id}")
except Exception:
pass
return move, comment
def get_online_egtb_move(li: lichess.Lichess, board: chess.Board, game: model.Game,
online_egtb_cfg: config.Configuration) -> Tuple[Union[str, List[str], None], int]:
"""
Get a move from an online egtb (either by lichess or chessdb).
If `move_quality` is `suggest`, then it will return a list of moves for the engine to choose from.
"""
use_online_egtb = online_egtb_cfg.enabled
wb = "w" if board.turn == chess.WHITE else "b"
pieces = chess.popcount(board.occupied)
source = online_egtb_cfg.source
minimum_time = online_egtb_cfg.min_time * 1000
if (not use_online_egtb
or game.state[f"{wb}time"] < minimum_time
or board.uci_variant not in ["chess", "antichess", "atomic"]
and source == "lichess"
or board.uci_variant != "chess"
and source == "chessdb"
or pieces > online_egtb_cfg.max_pieces
or board.castling_rights):
return None, -3
quality = online_egtb_cfg.move_quality
variant = "standard" if board.uci_variant == "chess" else str(board.uci_variant)
try:
if source == "lichess":
return get_lichess_egtb_move(li, game, board, quality, variant)
elif source == "chessdb":
return get_chessdb_egtb_move(li, game, board, quality)
except Exception:
pass
return None, -3
def get_egtb_move(board: chess.Board, game: model.Game, lichess_bot_tbs: config.Configuration,
draw_or_resign_cfg: config.Configuration) -> Union[chess.engine.PlayResult, List[chess.Move]]:
"""
Get a move from a local egtb.
If `move_quality` is `suggest`, then it will return a list of moves for the engine to choose from.
"""
best_move, wdl = get_syzygy(board, game, lichess_bot_tbs.syzygy)
if best_move is None:
best_move, wdl = get_gaviota(board, game, lichess_bot_tbs.gaviota)
if best_move:
can_offer_draw = draw_or_resign_cfg.offer_draw_enabled
offer_draw_for_zero = draw_or_resign_cfg.offer_draw_for_egtb_zero
offer_draw = bool(can_offer_draw and offer_draw_for_zero and wdl == 0)
can_resign = draw_or_resign_cfg.resign_enabled
resign_on_egtb_loss = draw_or_resign_cfg.resign_for_egtb_minus_two
resign = bool(can_resign and resign_on_egtb_loss and wdl == -2)
wdl_to_score = {2: 9900, 1: 500, 0: 0, -1: -500, -2: -9900}
comment: chess.engine.InfoDict = {"score": chess.engine.PovScore(chess.engine.Cp(wdl_to_score[wdl]), board.turn)}
if isinstance(best_move, chess.Move):
return chess.engine.PlayResult(best_move, None, comment, draw_offered=offer_draw, resigned=resign)
return best_move
return chess.engine.PlayResult(None, None)
def get_lichess_egtb_move(li: lichess.Lichess, game: model.Game, board: chess.Board, quality: str,
variant: str) -> Tuple[Union[str, List[str], None], int]:
"""
Get a move from lichess's egtb.
If `move_quality` is `suggest`, then it will return a list of moves for the engine to choose from.
"""
name_to_wld = {"loss": -2,
"maybe-loss": -1,
"blessed-loss": -1,
"draw": 0,
"cursed-win": 1,
"maybe-win": 1,
"win": 2}
pieces = chess.popcount(board.occupied)
max_pieces = 7 if board.uci_variant == "chess" else 6
if pieces <= max_pieces:
data = li.online_book_get(f"http://tablebase.lichess.ovh/{variant}",
params={"fen": board.fen()})
if quality == "best":
move = data["moves"][0]["uci"]
wdl = name_to_wld[data["moves"][0]["category"]] * -1
dtz = data["moves"][0]["dtz"] * -1
dtm = data["moves"][0]["dtm"]
if dtm:
dtm *= -1
logger.info(f"Got move {move} from tablebase.lichess.ovh (wdl: {wdl}, dtz: {dtz}, dtm: {dtm}) for game {game.id}")
elif quality == "suggest":
best_wdl = name_to_wld[data["moves"][0]["category"]]
def good_enough(possible_move: LICHESS_EGTB_MOVE) -> bool:
return name_to_wld[possible_move["category"]] == best_wdl
possible_moves = list(filter(good_enough, data["moves"]))
if len(possible_moves) > 1:
move = [move["uci"] for move in possible_moves]
wdl = best_wdl * -1
logger.info(f"Suggesting moves from tablebase.lichess.ovh (wdl: {wdl}) for game {game.id}")
else:
best_move = possible_moves[0]
move = best_move["uci"]
wdl = name_to_wld[best_move["category"]] * -1
dtz = best_move["dtz"] * -1
dtm = best_move["dtm"]
if dtm:
dtm *= -1
logger.info(f"Got move {move} from tablebase.lichess.ovh (wdl: {wdl}, dtz: {dtz}, dtm: {dtm})"
f" for game {game.id}")
else:
best_wdl = name_to_wld[data["moves"][0]["category"]]
def good_enough(possible_move: LICHESS_EGTB_MOVE) -> bool:
return name_to_wld[possible_move["category"]] == best_wdl
possible_moves = list(filter(good_enough, data["moves"]))
random_move = random.choice(possible_moves)
move = random_move["uci"]
wdl = name_to_wld[random_move["category"]] * -1
dtz = random_move["dtz"] * -1
dtm = random_move["dtm"]
if dtm:
dtm *= -1
logger.info(f"Got move {move} from tablebase.lichess.ovh (wdl: {wdl}, dtz: {dtz}, dtm: {dtm}) for game {game.id}")
return move, wdl
return None, -3
def get_chessdb_egtb_move(li: lichess.Lichess, game: model.Game, board: chess.Board,
quality: str) -> Tuple[Union[str, List[str], None], int]:
"""
Get a move from chessdb's egtb.
If `move_quality` is `suggest`, then it will return a list of moves for the engine to choose from.
"""
def score_to_wdl(score: int) -> int:
return piecewise_function([(-20001, 2),
(-1, -1),
(0, 0),
(20000, 1)], 2, score)
def score_to_dtz(score: int) -> int: