This repository has been archived by the owner on Jun 16, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgtp_relay.py
509 lines (368 loc) · 17.6 KB
/
gtp_relay.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
# The challenge of this is making a nice GUI while not having races where (e.g.) a new board
# is created while the engine is thinking. I use the simplest solution of disallowing all
# human action while we await the engine's next move.
import os, queue, subprocess, sys, threading
import tkinter, tkinter.filedialog, tkinter.messagebox
import gofish
from gofish import BLACK, WHITE
colour_lookup = {BLACK: "black", WHITE: "white"}
WIDTH, HEIGHT = 621, 621
GAP = 31
MOTD = """
Fohristiwhirl's GTP relay.
"""
# --------------------------------------------------------------------------------------
# Various utility functions...
def load_graphics():
directory = os.path.dirname(os.path.realpath(sys.argv[0]))
os.chdir(directory) # Set working dir to be same as infile.
# PhotoImages have a tendency to get garbage-collected even when they're needed.
# Avoid this by making them globals, so there's always a reference to them.
global spriteTexture
try:
spriteTexture = tkinter.PhotoImage(file = "gfx/texture_override.gif")
except:
spriteTexture = tkinter.PhotoImage(file = "gfx/texture.gif")
global spriteBlack; spriteBlack = tkinter.PhotoImage(file = "gfx/black.gif")
global spriteWhite; spriteWhite = tkinter.PhotoImage(file = "gfx/white.gif")
global spriteHoshi; spriteHoshi = tkinter.PhotoImage(file = "gfx/hoshi.gif")
global spriteMove; spriteMove = tkinter.PhotoImage(file = "gfx/move.gif")
global spriteVar; spriteVar = tkinter.PhotoImage(file = "gfx/var.gif")
global spriteTriangle; spriteTriangle = tkinter.PhotoImage(file = "gfx/triangle.gif")
global spriteCircle; spriteCircle = tkinter.PhotoImage(file = "gfx/circle.gif")
global spriteSquare; spriteSquare = tkinter.PhotoImage(file = "gfx/square.gif")
global spriteMark; spriteMark = tkinter.PhotoImage(file = "gfx/mark.gif")
global markup_dict; markup_dict = {"TR": spriteTriangle, "CR": spriteCircle, "SQ": spriteSquare, "MA": spriteMark}
# --------------------------------------------------------------------------------------
def screen_pos_from_board_pos(x, y, boardsize):
gridsize = GAP * (boardsize - 1) + 1
margin = (WIDTH - gridsize) // 2
ret_x = (x - 1) * GAP + margin
ret_y = (y - 1) * GAP + margin
return ret_x, ret_y
def board_pos_from_screen_pos(x, y, boardsize): # Inverse of the above
gridsize = GAP * (boardsize - 1) + 1
margin = (WIDTH - gridsize) // 2
ret_x = round((x - margin) / GAP + 1)
ret_y = round((y - margin) / GAP + 1)
return ret_x, ret_y
def title_bar_string(node):
wwtm = node.what_was_the_move()
mwp = node.move_was_pass()
if wwtm is None and not mwp:
if node.parent:
title = "Empty node"
else:
title = "Root node"
else:
title = "Move {}".format(node.moves_made)
if node.parent:
if len(node.parent.children) > 1:
index = node.parent.children.index(node)
title += " [{} of {} variations]".format(index + 1, len(node.parent.children))
if mwp:
title += " (pass)"
elif wwtm:
x, y = wwtm
title += " ({})".format(gofish.english_string_from_point(x, y, node.board.boardsize))
return title
# --------------------------------------------------------------------------------------
def send_command(command, verbose = True):
if len(command) == 0 or command[-1] != "\n":
command += "\n"
if verbose:
print(command, end="")
process.stdin.write(bytearray(command, encoding="ascii"))
process.stdin.flush()
def get_reply(verbose = True):
response = ""
while 1:
newlinebytes = process.stdout.readline()
newline = str(newlinebytes, encoding="ascii")
newline = newline.replace("\r\n", "\n") # is there a better way to deal with this Windows nonsense?
response += newline
if len(response) >= 2:
if response[-2:] == "\n\n":
response = response.strip()
if verbose:
print(response)
return response
def send_and_get(command):
send_command(command)
response = get_reply()
return response
# This will get run in a thread, communicating with the rest of the program via queues...
def relay():
while 1:
command = engine_in_queue.get()
send_command(command)
response = get_reply()
engine_out_queue.put(response)
# --------------------------------------------------------------------------------------
class GTP_GUI(tkinter.Canvas):
def __init__(self, owner, *args, **kwargs):
tkinter.Canvas.__init__(self, owner, *args, **kwargs)
self.owner = owner
self.bind("<Button-1>", self.mouseclick_handler)
self.bind("<Key>", self.call_keypress_handler)
self.bind("<Control-s>", self.saver)
self.awaiting_move = False
self.human_colour = BLACK
self.engine_colour = WHITE
self.reset(19)
self.engine_msg_poller()
def reset(self, size):
if self.awaiting_move:
return
self.node = gofish.new_tree(size)
for cmd in ["boardsize {}".format(self.node.board.boardsize), "clear_board", "komi 0"]:
send_command(cmd)
get_reply()
if self.human_colour == BLACK:
statusbar.config(text = "Your move ({})".format(colour_lookup[self.human_colour]))
else:
command = "genmove {}".format(colour_lookup[self.engine_colour])
engine_in_queue.put(command)
self.need_to_wait()
self.draw_node()
def handicap(self, h):
if self.awaiting_move:
return
self.node = gofish.new_tree(self.node.board.boardsize)
for cmd in ["boardsize {}".format(self.node.board.boardsize), "clear_board", "komi 0"]:
send_command(cmd)
get_reply()
send_command("fixed_handicap {}".format(h))
response = get_reply()
if response[0] == "?":
self.reset(self.node.board.boardsize)
return
self.node.set_value("HA", h)
english_points_list = response[1:].strip().split()
for p in english_points_list:
x, y = gofish.point_from_english_string(p, self.node.board.boardsize)
self.node.add_stone(BLACK, x, y)
if self.human_colour == WHITE: # The reverse of normal; white goes first
statusbar.config(text = "Your move ({})".format(colour_lookup[self.human_colour]))
else:
command = "genmove {}".format(colour_lookup[self.engine_colour])
engine_in_queue.put(command)
self.need_to_wait()
self.draw_node()
def mouseclick_handler(self, event):
if not self.awaiting_move:
x, y = board_pos_from_screen_pos(event.x, event.y, self.node.board.boardsize)
try:
self.node = self.node.make_move(x, y, colour = self.human_colour)
except gofish.IllegalMove:
return
command = "play {} {}".format(colour_lookup[self.human_colour], gofish.english_string_from_point(x, y, self.node.board.boardsize))
send_and_get(command)
command = "genmove {}".format(colour_lookup[self.engine_colour])
engine_in_queue.put(command)
self.need_to_wait()
self.draw_node()
def engine_msg_poller(self):
self.after(100, self.engine_msg_poller) # Add a callback here in 100 ms
self.engine_move_handler()
# We just use the poller to get engine moves. Everything else doesn't use the
# other thread to send and receive. Everything else will just block while
# waiting for a response.
def engine_move_handler(self):
try:
message = engine_out_queue.get(block = False)
except queue.Empty:
return
if message[0] != "=":
print("ERROR: {}".format(message))
return
if not self.awaiting_move:
print("ERROR: got '{}' while NOT expecting move".format(message))
return
resign_flag = False
message = message[1:].strip()
if len(message) in [2,3]:
point = gofish.point_from_english_string(message, self.node.board.boardsize)
if point is None:
print("ERROR: got '{}' while expecting move".format(message))
return
else:
x, y = point
try:
result = self.node.make_move(x, y, colour = self.engine_colour)
except gofish.IllegalMove:
print("ERROR: got illegal move {}".format(message))
return
elif message.upper() == "PASS":
result = self.node.make_pass()
elif message.upper() == "RESIGN":
result = self.node.make_pass()
resign_flag = True
else:
print("ERROR: got '{}' while expecting move".format(message))
return
self.done_waiting()
self.node = result
self.draw_node()
if resign_flag:
self.owner.wm_title("Engine resigned") # do this after the draw_node() so the title bar is set
statusbar.config(text = "Engine resigned")
else:
self.maybe_get_final_score() # likewise
def swap_colours(self):
if self.awaiting_move:
return
self.human_colour, self.engine_colour = self.engine_colour, self.human_colour
command = "genmove {}".format(colour_lookup[self.engine_colour])
engine_in_queue.put(command)
self.need_to_wait()
def need_to_wait(self): # Basically, prevent the user from doing anything
menubar.entryconfig("New", state = "disabled")
menubar.entryconfig("Handicap", state = "disabled")
menubar.entryconfig("Pass", state = "disabled")
menubar.entryconfig("Swap colours", state = "disabled")
menubar.entryconfig("Save SGF", state = "disabled")
statusbar.config(text = "Awaiting move from engine")
self.awaiting_move = True
def done_waiting(self):
menubar.entryconfig("New", state = "normal")
menubar.entryconfig("Handicap", state = "normal")
menubar.entryconfig("Pass", state = "normal")
menubar.entryconfig("Swap colours", state = "normal")
menubar.entryconfig("Save SGF", state = "normal")
statusbar.config(text = "Your move ({})".format(colour_lookup[self.human_colour]))
self.awaiting_move = False
def maybe_get_final_score(self):
if self.node.move_was_pass():
if self.node.parent:
if self.node.parent.move_was_pass():
statusbar.config(text = "Asking engine for score")
statusbar.update_idletasks()
msg = send_and_get("final_score")
self.owner.wm_title("Score: " + msg[1:].strip())
statusbar.config(text = "Score: " + msg[1:].strip())
def draw_node(self):
self.delete(tkinter.ALL) # DESTROY all!
board = self.node.board
boardsize = board.boardsize
# Set the title bar of the owning window
self.owner.wm_title(title_bar_string(self.node))
# Draw the texture...
self.create_image(0, 0, anchor = tkinter.NW, image = spriteTexture)
# Draw the hoshi points...
if boardsize > 13:
hoshi_points = gofish.handicap_points(boardsize, 9)
else:
hoshi_points = gofish.handicap_points(boardsize, 5)
for point in hoshi_points:
screen_x, screen_y = screen_pos_from_board_pos(point[0], point[1], boardsize)
self.create_image(screen_x, screen_y, image = spriteHoshi)
# Draw the lines...
for n in range(1, boardsize + 1):
start_a, start_b = screen_pos_from_board_pos(n, 1, boardsize)
end_a, end_b = screen_pos_from_board_pos(n, boardsize, boardsize)
end_b += 1
self.create_line(start_a, start_b, end_a, end_b)
self.create_line(start_b, start_a, end_b, end_a)
# Draw the stones...
for x in range(1, boardsize + 1):
for y in range(1, boardsize + 1):
screen_x, screen_y = screen_pos_from_board_pos(x, y, boardsize)
if board.state[x][y] == BLACK:
self.create_image(screen_x, screen_y, image = spriteBlack)
elif board.state[x][y] == WHITE:
self.create_image(screen_x, screen_y, image = spriteWhite)
# Draw a mark at the current move, if there is one...
move = self.node.what_was_the_move()
if move is not None:
screen_x, screen_y = screen_pos_from_board_pos(move[0], move[1], boardsize)
self.create_image(screen_x, screen_y, image = spriteMove)
# Draw a mark at variations, if there are any...
for sib_move in self.node.sibling_moves():
screen_x, screen_y = screen_pos_from_board_pos(sib_move[0], sib_move[1], boardsize)
self.create_image(screen_x, screen_y, image = spriteVar)
# Draw the commonly used marks...
for mark in markup_dict:
if mark in self.node.properties:
points = set()
for value in self.node.properties[mark]:
points |= gofish.points_from_points_string(value, boardsize)
for point in points:
screen_x, screen_y = screen_pos_from_board_pos(point[0], point[1], boardsize)
self.create_image(screen_x, screen_y, image = markup_dict[mark])
def saver(self, event = None):
outfilename = tkinter.filedialog.asksaveasfilename(defaultextension=".sgf")
if outfilename:
gofish.save_file(outfilename, self.node)
try:
print("---> Saved: {}\n".format(outfilename))
except:
print("---> Saved: --- Exception when trying to print filename ---")
self.draw_node()
def call_keypress_handler(self, event):
try:
function_call = "self.handle_key_{}()".format(event.keysym.upper())
eval(function_call)
except AttributeError:
pass
def handle_key_P(self):
if not self.awaiting_move:
self.node = self.node.make_pass()
colour_lookup = {BLACK: "black", WHITE: "white"}
command = "play {} pass".format(colour_lookup[self.human_colour])
send_and_get(command)
command = "genmove {}".format(colour_lookup[self.engine_colour])
engine_in_queue.put(command)
self.need_to_wait()
self.draw_node()
# ---------------------------------------------------------------------------------------
class Root(tkinter.Tk):
def __init__(self, *args, **kwargs):
tkinter.Tk.__init__(self, *args, **kwargs)
load_graphics()
self.resizable(width = False, height = False)
global statusbar
statusbar = tkinter.Label(self, text="test", bd = 0, anchor = tkinter.W)
statusbar.pack(side = tkinter.BOTTOM, fill = tkinter.X)
board = GTP_GUI(self, width = WIDTH, height = HEIGHT, bd = 0, highlightthickness = 0)
board.pack()
board.focus_set()
global menubar
menubar = tkinter.Menu(self)
new_board_menu = tkinter.Menu(menubar, tearoff = 0)
new_board_menu.add_command(label = "19x19", command = lambda : board.reset(19))
new_board_menu.add_command(label = "17x17", command = lambda : board.reset(17))
new_board_menu.add_command(label = "15x15", command = lambda : board.reset(15))
new_board_menu.add_command(label = "13x13", command = lambda : board.reset(13))
new_board_menu.add_command(label = "11x11", command = lambda : board.reset(11))
new_board_menu.add_command(label = "9x9" , command = lambda : board.reset( 9))
handicap_menu = tkinter.Menu(menubar, tearoff = 0)
handicap_menu.add_command(label = "9", command = lambda : board.handicap(9))
handicap_menu.add_command(label = "8", command = lambda : board.handicap(8))
handicap_menu.add_command(label = "7", command = lambda : board.handicap(7))
handicap_menu.add_command(label = "6", command = lambda : board.handicap(6))
handicap_menu.add_command(label = "5", command = lambda : board.handicap(5))
handicap_menu.add_command(label = "4", command = lambda : board.handicap(4))
handicap_menu.add_command(label = "3", command = lambda : board.handicap(3))
handicap_menu.add_command(label = "2", command = lambda : board.handicap(2))
menubar.add_cascade(label = "New", menu = new_board_menu)
menubar.add_cascade(label = "Handicap", menu = handicap_menu)
menubar.add_command(label = "Pass", command = board.handle_key_P)
menubar.add_command(label = "Swap colours", command = board.swap_colours)
menubar.add_command(label = "Save SGF", command = board.saver)
self.config(menu = menubar)
self.wm_title("Fohristiwhirl's GTP relay")
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Need an argument: the engine to run (it may also require more arguments)")
sys.exit(1)
global process
process = subprocess.Popen(args = sys.argv[1:], stdin = subprocess.PIPE, stdout = subprocess.PIPE) #, stderr = subprocess.DEVNULL)
global engine_in_queue
engine_in_queue = queue.Queue()
global engine_out_queue
engine_out_queue = queue.Queue()
print(MOTD)
threading.Thread(target = relay, daemon = True).start() # The relay actually talks to the engine
app = Root()
app.mainloop()