forked from TheYoBots/Lishogi-Bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
engine_ctrl.py
219 lines (190 loc) · 8.04 KB
/
engine_ctrl.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
import threading
import subprocess
import os
import signal
import logging
logger = logging.getLogger(__name__)
from util import *
class Engine:
def __init__(self, command):
self.proccess = self.open_process(command)
self.go_commands = None
def set_go_commands(self, go_comm):
self.go_commands = go_comm
logger.info(self.go_commands)
def open_process(self, command, shell=True, _popen_lock=threading.Lock()):
kwargs = {
"shell": shell,
"stdout": subprocess.PIPE,
"stderr": subprocess.STDOUT,
"stdin": subprocess.PIPE,
"bufsize": 1, # Line buffered
"universal_newlines": True,
}
# Prevent signal propagation from parent process
try:
# Windows
kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP
except AttributeError:
# Unix
kwargs["preexec_fn"] = os.setpgrp
with _popen_lock: # Work around Python 2 Popen race condition
return subprocess.Popen(command, **kwargs)
def kill_process(self):
try:
# Windows
self.proccess.send_signal(signal.CTRL_BREAK_EVENT)
except AttributeError:
# Unix
os.killpg(self.proccess.pid, signal.SIGKILL)
def send(self, line):
self.proccess.stdin.write(line + "\n")
self.proccess.stdin.flush()
def recv(self):
while True:
line = self.proccess.stdout.readline()
if line == "":
raise EOFError()
line = line.rstrip()
if line:
return line
def recv_usi(self):
command_and_args = self.recv().split(None, 1)
if len(command_and_args) == 1:
return command_and_args[0], ""
elif len(command_and_args) == 2:
return command_and_args
def usi(self):
self.send("usi")
engine_info = {}
while True:
command, arg = self.recv_usi()
if command == "usiok":
return engine_info
elif command == "id":
name_and_value = arg.split(None, 1)
if len(name_and_value) == 2:
engine_info[name_and_value[0]] = name_and_value[1]
elif command == "option" or command.startswith("Fairy-Stockfish"):
pass
else:
logger.error("Unexpected engine response to usi: %s %s" % (command, arg))
def isready(self):
self.send("isready")
while True:
command, arg = self.recv_usi()
if command == "readyok":
break
elif command == "info" and arg.startswith("string Error! "):
logger.error("Unexpected engine response to isready: %s %s" % (command, arg))
elif command == "info" and arg.startswith("string "):
pass
else:
logger.error("Unexpected engine response to isready: %s %s" % (command, arg))
def setoption(self, name, value):
if value is True:
value = "true"
elif value is False:
value = "false"
elif value is None:
value = "none"
self.send("setoption name %s value %s" % (name, value))
def go(self, position, moves, movetime=None, btime=None, wtime=None, binc=None, winc=None, byo=None, depth=None, nodes=None):
if position != "startpos":
position = "sfen " + position
self.send("position %s moves %s" % (position, " ".join(moves)))
logger.info("position %s moves %s" % (position, " ".join(moves)))
builder = []
builder.append("go")
if movetime is not None:
builder.append("movetime")
builder.append(str(movetime))
if depth is not None:
builder.append("depth")
builder.append(str(depth))
if nodes is not None:
builder.append("nodes")
builder.append(str(nodes))
# In Shogi and USI, black is the player to move first
if btime is not None:
builder.append("btime")
builder.append(str(btime))
if wtime is not None:
builder.append("wtime")
builder.append(str(wtime))
if byo is not None:
builder.append("byoyomi")
builder.append(str(byo))
if binc is not None:
builder.append("binc")
builder.append(str(binc))
if winc is not None:
builder.append("winc")
builder.append(str(winc))
self.send(" ".join(builder))
logger.info(" ".join(builder))
info = {}
info["bestmove"] = None
while True:
command, arg = self.recv_usi()
if command == "bestmove":
bestmove = arg.split()[0]
if bestmove and bestmove != "(none)":
info["bestmove"] = bestmove
return (info["bestmove"], None)
elif command == "info":
arg = arg or ""
# Parse all other parameters
score_kind, score_value, lowerbound, upperbound = None, None, False, False
current_parameter = None
for token in arg.split(" "):
if current_parameter == "string":
# Everything until the end of line is a string
if "string" in info:
info["string"] += " " + token
else:
info["string"] = token
elif token == "score":
current_parameter = "score"
elif token == "pv":
current_parameter = "pv"
if info.get("multipv", 1) == 1:
info.pop("pv", None)
elif token in ["depth", "seldepth", "time", "nodes", "multipv",
"currmove", "currmovenumber",
"hashfull", "nps", "tbhits", "cpuload",
"refutation", "currline", "string"]:
current_parameter = token
info.pop(current_parameter, None)
elif current_parameter in ["depth", "seldepth", "time",
"nodes", "currmovenumber",
"hashfull", "nps", "tbhits",
"cpuload", "multipv"]:
# Integer parameters
info[current_parameter] = int(token)
elif current_parameter == "score":
# Score
if token in ["cp", "mate"]:
score_kind = token
score_value = None
elif token == "lowerbound":
lowerbound = True
elif token == "upperbound":
upperbound = True
else:
score_value = int(token)
elif current_parameter != "pv" or info.get("multipv", 1) == 1:
# Strings
if current_parameter in info:
info[current_parameter] += " " + token
else:
info[current_parameter] = token
# Set score. Prefer scores that are not just a bound
if score_kind and score_value is not None and (not (lowerbound or upperbound) or "score" not in info or info["score"].get("lowerbound") or info["score"].get("upperbound")):
info["score"] = {score_kind: score_value}
if lowerbound:
info["score"]["lowerbound"] = lowerbound
if upperbound:
info["score"]["upperbound"] = upperbound
else:
logger.error("Unexpected engine response to go: %s %s" % (command, arg))