uct_pass_is_safe: only require us to capture dead opponents
[pachi/t.git] / gtp.c
bloba8e2d668861163b45b04d2787e74d500b62b05f0
1 #define DEBUG
2 #include <assert.h>
3 #include <ctype.h>
4 #include <math.h>
5 #include <stdarg.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <unistd.h>
11 #include "board.h"
12 #include "debug.h"
13 #include "engine.h"
14 #include "fbook.h"
15 #include "gtp.h"
16 #include "mq.h"
17 #include "uct/uct.h"
18 #include "version.h"
19 #include "timeinfo.h"
21 #define NO_REPLY (-2)
23 /* Sleep 5 seconds after a game ends to give time to kill the program. */
24 #define GAME_OVER_SLEEP 5
26 void
27 gtp_prefix(char prefix, int id)
29 if (id == NO_REPLY) return;
30 if (id >= 0)
31 printf("%c%d ", prefix, id);
32 else
33 printf("%c ", prefix);
36 void
37 gtp_flush(void)
39 putchar('\n');
40 fflush(stdout);
43 void
44 gtp_output(char prefix, int id, va_list params)
46 if (id == NO_REPLY) return;
47 gtp_prefix(prefix, id);
48 char *s;
49 while ((s = va_arg(params, char *))) {
50 fputs(s, stdout);
52 putchar('\n');
53 gtp_flush();
56 void
57 gtp_reply(int id, ...)
59 va_list params;
60 va_start(params, id);
61 gtp_output('=', id, params);
62 va_end(params);
65 void
66 gtp_error(int id, ...)
68 va_list params;
69 va_start(params, id);
70 gtp_output('?', id, params);
71 va_end(params);
74 /* List of known gtp commands. The internal command pachi-genmoves is not exported,
75 * it should only be used between master and slaves of the distributed engine. */
76 static char *known_commands =
77 "protocol_version\n"
78 "echo\n"
79 "name\n"
80 "version\n"
81 "list_commands\n"
82 "known_command\n"
83 "quit\n"
84 "boardsize\n"
85 "clear_board\n"
86 "kgs-game_over\n"
87 "komi\n"
88 "kgs-rules\n"
89 "play\n"
90 "genmove\n"
91 "kgs-genmove_cleanup\n"
92 "set_free_handicap\n"
93 "place_free_handicap\n"
94 "fixed_handicap\n"
95 "final_score\n"
96 "final_status_list\n"
97 "undo\n"
98 "pachi-evaluate\n"
99 "pachi-result\n"
100 "pachi-gentbook\n"
101 "pachi-dumptbook\n"
102 "kgs-chat\n"
103 "time_left\n"
104 "time_settings\n"
105 "kgs-time_settings";
108 /* Return true if cmd is a valid gtp command. */
109 bool
110 gtp_is_valid(char *cmd)
112 if (!cmd || !*cmd) return false;
113 char *s = strcasestr(known_commands, cmd);
114 if (!s) return false;
115 if (s != known_commands && s[-1] != '\n') return false;
117 int len = strlen(cmd);
118 return s[len] == '\0' || s[len] == '\n';
121 /* XXX: THIS IS TOTALLY INSECURE!!!!
122 * Even basic input checking is missing. */
124 enum parse_code
125 gtp_parse(struct board *board, struct engine *engine, struct time_info *ti, char *buf)
127 #define next_tok(to_) \
128 to_ = next; \
129 next = next + strcspn(next, " \t\r\n"); \
130 if (*next) { \
131 *next = 0; next++; \
132 next += strspn(next, " \t\r\n"); \
135 if (strchr(buf, '#'))
136 *strchr(buf, '#') = 0;
138 char *cmd, *next = buf;
139 next_tok(cmd);
141 int id = -1;
142 if (isdigit(*cmd)) {
143 id = atoi(cmd);
144 next_tok(cmd);
147 if (!*cmd)
148 return P_OK;
150 if (!strcasecmp(cmd, "protocol_version")) {
151 gtp_reply(id, "2", NULL);
152 return P_OK;
154 } else if (!strcasecmp(cmd, "name")) {
155 /* KGS hack */
156 gtp_reply(id, "Pachi ", engine->name, NULL);
157 return P_OK;
159 } else if (!strcasecmp(cmd, "echo")) {
160 gtp_reply(id, next, NULL);
161 return P_OK;
163 } else if (!strcasecmp(cmd, "version")) {
164 gtp_reply(id, PACHI_VERSION, ": ", engine->comment, " Have a nice game!", NULL);
165 return P_OK;
167 } else if (!strcasecmp(cmd, "list_commands")) {
168 gtp_reply(id, known_commands, NULL);
169 return P_OK;
171 } else if (!strcasecmp(cmd, "known_command")) {
172 char *arg;
173 next_tok(arg);
174 if (gtp_is_valid(arg)) {
175 gtp_reply(id, "true", NULL);
176 } else {
177 gtp_reply(id, "false", NULL);
179 return P_OK;
182 if (engine->notify && gtp_is_valid(cmd)) {
183 char *reply;
184 enum parse_code c = engine->notify(engine, board, id, cmd, next, &reply);
185 if (c == P_NOREPLY) {
186 id = NO_REPLY;
187 } else if (c == P_DONE_OK) {
188 gtp_reply(id, reply, NULL);
189 return P_OK;
190 } else if (c == P_DONE_ERROR) {
191 gtp_error(id, reply, NULL);
192 /* This is an internal error for the engine, but
193 * it is still OK from main's point of view. */
194 return P_OK;
195 } else if (c != P_OK) {
196 return c;
200 if (!strcasecmp(cmd, "quit")) {
201 gtp_reply(id, NULL);
202 exit(0);
204 } else if (!strcasecmp(cmd, "boardsize")) {
205 char *arg;
206 next_tok(arg);
207 int size = atoi(arg);
208 if (size < 1 || size > BOARD_MAX_SIZE) {
209 gtp_error(id, "illegal board size", NULL);
210 return P_OK;
212 board_resize(board, size);
213 board_clear(board);
214 gtp_reply(id, NULL);
215 return P_ENGINE_RESET;
217 } else if (!strcasecmp(cmd, "clear_board")) {
218 board_clear(board);
219 if (DEBUGL(3) && debug_boardprint)
220 board_print(board, stderr);
221 gtp_reply(id, NULL);
222 return P_ENGINE_RESET;
224 } else if (!strcasecmp(cmd, "kgs-game_over")) {
225 /* The game may not be really over, just adjourned.
226 * Do not clear the board to avoid illegal moves
227 * if the game is resumed immediately after. KGS
228 * may start directly with genmove on resumption. */
229 if (DEBUGL(1)) {
230 fprintf(stderr, "game is over\n");
231 fflush(stderr);
233 /* Sleep before replying, so that kgs doesn't
234 * start another game immediately. */
235 sleep(GAME_OVER_SLEEP);
236 gtp_reply(id, NULL);
238 } else if (!strcasecmp(cmd, "komi")) {
239 char *arg;
240 next_tok(arg);
241 sscanf(arg, PRIfloating, &board->komi);
243 if (DEBUGL(3) && debug_boardprint)
244 board_print(board, stderr);
245 gtp_reply(id, NULL);
247 } else if (!strcasecmp(cmd, "kgs-rules")) {
248 char *arg;
249 next_tok(arg);
250 if (!strcasecmp(arg, "japanese")) {
251 board->rules = RULES_JAPANESE;
252 } else if (!strcasecmp(arg, "chinese")) {
253 board->rules = RULES_CHINESE;
254 } else if (!strcasecmp(arg, "aga")) {
255 board->rules = RULES_AGA;
256 } else if (!strcasecmp(arg, "new_zealand")) {
257 board->rules = RULES_NEW_ZEALAND;
258 } else {
259 gtp_error(id, "unknown rules", NULL);
260 return P_OK;
262 gtp_reply(id, NULL);
264 } else if (!strcasecmp(cmd, "play")) {
265 struct move m;
267 char *arg;
268 next_tok(arg);
269 m.color = str2stone(arg);
270 next_tok(arg);
271 coord_t *c = str2coord(arg, board_size(board));
272 m.coord = *c; coord_done(c);
273 next_tok(arg);
274 char *enginearg = arg;
275 char *reply = NULL;
277 if (DEBUGL(5))
278 fprintf(stderr, "got move %d,%d,%d\n", m.color, coord_x(m.coord, board), coord_y(m.coord, board));
280 // This is where kgs starts the timer, not at genmove!
281 time_start_timer(&ti[stone_other(m.color)]);
283 if (engine->notify_play)
284 reply = engine->notify_play(engine, board, &m, enginearg);
285 if (board_play(board, &m) < 0) {
286 if (DEBUGL(0)) {
287 fprintf(stderr, "! ILLEGAL MOVE %d,%d,%d\n", m.color, coord_x(m.coord, board), coord_y(m.coord, board));
288 board_print(board, stderr);
290 gtp_error(id, "illegal move", NULL);
291 } else {
292 if (DEBUGL(4) && debug_boardprint)
293 board_print_custom(board, stderr, engine->printhook);
294 gtp_reply(id, reply, NULL);
297 } else if (!strcasecmp(cmd, "genmove") || !strcasecmp(cmd, "kgs-genmove_cleanup")) {
298 char *arg;
299 next_tok(arg);
300 enum stone color = str2stone(arg);
301 coord_t *c = NULL;
302 if (DEBUGL(2) && debug_boardprint)
303 board_print_custom(board, stderr, engine->printhook);
305 if (!ti[color].len.t.timer_start) {
306 /* First game move. */
307 time_start_timer(&ti[color]);
310 coord_t cf = pass;
311 if (board->fbook)
312 cf = fbook_check(board);
313 if (!is_pass(cf)) {
314 c = coord_copy(cf);
315 } else {
316 c = engine->genmove(engine, board, &ti[color], color, !strcasecmp(cmd, "kgs-genmove_cleanup"));
318 struct move m = { *c, color };
319 if (board_play(board, &m) < 0) {
320 fprintf(stderr, "Attempted to generate an illegal move: [%s, %s]\n", coord2sstr(m.coord, board), stone2str(m.color));
321 abort();
323 char *str = coord2str(*c, board);
324 if (DEBUGL(4))
325 fprintf(stderr, "playing move %s\n", str);
326 if (DEBUGL(1) && debug_boardprint) {
327 board_print_custom(board, stderr, engine->printhook);
329 gtp_reply(id, str, NULL);
330 free(str); coord_done(c);
332 /* Account for spent time. If our GTP peer keeps our clock, this will
333 * be overriden by next time_left GTP command properly. */
334 /* (XXX: Except if we pass to byoyomi and the peer doesn't, but that
335 * should be absolutely rare situation and we will just spend a little
336 * less time than we could on next few moves.) */
337 if (ti[color].period != TT_NULL && ti[color].dim == TD_WALLTIME)
338 time_sub(&ti[color], time_now() - ti[color].len.t.timer_start, true);
340 } else if (!strcasecmp(cmd, "pachi-genmoves") || !strcasecmp(cmd, "pachi-genmoves_cleanup")) {
341 char *arg;
342 next_tok(arg);
343 enum stone color = str2stone(arg);
344 void *stats;
345 int stats_size;
347 char *reply = engine->genmoves(engine, board, &ti[color], color, next,
348 !strcasecmp(cmd, "pachi-genmoves_cleanup"),
349 &stats, &stats_size);
350 if (!reply) {
351 gtp_error(id, "genmoves error", NULL);
352 return P_OK;
354 if (DEBUGL(3))
355 fprintf(stderr, "proposing moves %s\n", reply);
356 if (DEBUGL(4) && debug_boardprint)
357 board_print_custom(board, stderr, engine->printhook);
358 gtp_reply(id, reply, NULL);
359 if (stats_size > 0) {
360 double start = time_now();
361 fwrite(stats, 1, stats_size, stdout);
362 fflush(stdout);
363 if (DEBUGVV(2))
364 fprintf(stderr, "sent reply %d bytes in %.4fms\n",
365 stats_size, (time_now() - start)*1000);
368 } else if (!strcasecmp(cmd, "set_free_handicap")) {
369 struct move m;
370 m.color = S_BLACK;
372 char *arg;
373 next_tok(arg);
374 do {
375 coord_t *c = str2coord(arg, board_size(board));
376 m.coord = *c; coord_done(c);
377 if (DEBUGL(4))
378 fprintf(stderr, "setting handicap %d,%d\n", coord_x(m.coord, board), coord_y(m.coord, board));
380 if (board_play(board, &m) < 0) {
381 if (DEBUGL(0))
382 fprintf(stderr, "! ILLEGAL MOVE %d,%d,%d\n", m.color, coord_x(m.coord, board), coord_y(m.coord, board));
383 gtp_error(id, "illegal move", NULL);
385 board->handicap++;
386 next_tok(arg);
387 } while (*arg);
388 if (DEBUGL(1) && debug_boardprint)
389 board_print(board, stderr);
390 gtp_reply(id, NULL);
392 /* TODO: Engine should choose free handicap; however, it tends to take
393 * overly long to think it all out, and unless it's clever its
394 * handicap stones won't be of much help. ;-) */
395 } else if (!strcasecmp(cmd, "place_free_handicap")
396 || !strcasecmp(cmd, "fixed_handicap")) {
397 char *arg;
398 next_tok(arg);
399 int stones = atoi(arg);
401 gtp_prefix('=', id);
402 board_handicap(board, stones, id == NO_REPLY ? NULL : stdout);
403 if (DEBUGL(1) && debug_boardprint)
404 board_print(board, stderr);
405 if (id == NO_REPLY) return P_OK;
406 putchar('\n');
407 gtp_flush();
409 } else if (!strcasecmp(cmd, "final_score")) {
410 struct move_queue q = { .moves = 0 };
411 if (engine->dead_group_list)
412 engine->dead_group_list(engine, board, &q);
413 floating_t score = board_official_score(board, &q);
414 char str[64];
415 if (DEBUGL(1))
416 fprintf(stderr, "counted score %.1f\n", score);
417 if (score == 0) {
418 gtp_reply(id, "0", NULL);
419 } else if (score > 0) {
420 snprintf(str, 64, "W+%.1f", score);
421 gtp_reply(id, str, NULL);
422 } else {
423 snprintf(str, 64, "B+%.1f", -score);
424 gtp_reply(id, str, NULL);
427 /* XXX: This is a huge hack. */
428 } else if (!strcasecmp(cmd, "final_status_list")) {
429 if (id == NO_REPLY) return P_OK;
430 char *arg;
431 next_tok(arg);
432 struct move_queue q = { .moves = 0 };
433 if (engine->dead_group_list)
434 engine->dead_group_list(engine, board, &q);
435 /* else we return empty list - i.e. engine not supporting
436 * this assumes all stones alive at the game end. */
437 if (!strcasecmp(arg, "dead")) {
438 gtp_prefix('=', id);
439 for (unsigned int i = 0; i < q.moves; i++) {
440 foreach_in_group(board, q.move[i]) {
441 printf("%s ", coord2sstr(c, board));
442 } foreach_in_group_end;
443 putchar('\n');
445 if (!q.moves)
446 putchar('\n');
447 gtp_flush();
448 } else if (!strcasecmp(arg, "seki") || !strcasecmp(arg, "alive")) {
449 gtp_prefix('=', id);
450 bool printed_group = false;
451 foreach_point(board) { // foreach_group, effectively
452 group_t g = group_at(board, c);
453 if (!g || g != c) continue;
455 for (unsigned int i = 0; i < q.moves; i++) {
456 if (q.move[i] == g)
457 goto next_group;
459 foreach_in_group(board, g) {
460 printf("%s ", coord2sstr(c, board));
461 } foreach_in_group_end;
462 putchar('\n');
463 printed_group = true;
464 next_group:;
465 } foreach_point_end;
466 if (!printed_group)
467 putchar('\n');
468 gtp_flush();
469 } else {
470 gtp_error(id, "illegal status specifier", NULL);
473 } else if (!strcasecmp(cmd, "undo")) {
474 if (board_undo(board) < 0) {
475 if (DEBUGL(1)) {
476 fprintf(stderr, "undo on non-pass move %s\n", coord2sstr(board->last_move.coord, board));
477 board_print(board, stderr);
479 gtp_error(id, "cannot undo", NULL);
480 return P_OK;
482 char *reply = NULL;
483 if (engine->undo)
484 reply = engine->undo(engine, board);
485 if (DEBUGL(3) && debug_boardprint)
486 board_print(board, stderr);
487 gtp_reply(id, reply, NULL);
489 /* Custom commands for handling the tree opening tbook */
490 } else if (!strcasecmp(cmd, "pachi-gentbook")) {
491 /* Board must be initialized properly, as if for genmove;
492 * makes sense only as 'uct_gentbook b'. */
493 char *arg;
494 next_tok(arg);
495 enum stone color = str2stone(arg);
496 if (uct_gentbook(engine, board, &ti[color], color))
497 gtp_reply(id, NULL);
498 else
499 gtp_error(id, "error generating tbook", NULL);
501 } else if (!strcasecmp(cmd, "pachi-dumptbook")) {
502 char *arg;
503 next_tok(arg);
504 enum stone color = str2stone(arg);
505 uct_dumptbook(engine, board, color);
506 gtp_reply(id, NULL);
508 } else if (!strcasecmp(cmd, "pachi-evaluate")) {
509 char *arg;
510 next_tok(arg);
511 enum stone color = str2stone(arg);
513 if (!engine->evaluate) {
514 gtp_error(id, "pachi-evaluate not supported by engine", NULL);
515 } else {
516 gtp_prefix('=', id);
517 floating_t vals[board->flen];
518 engine->evaluate(engine, board, &ti[color], vals, color);
519 for (int i = 0; i < board->flen; i++) {
520 if (!board_coord_in_symmetry(board, board->f[i])
521 || isnan(vals[i]) || vals[i] < 0.001)
522 continue;
523 printf("%s %.3f\n", coord2sstr(board->f[i], board), (double) vals[i]);
525 gtp_flush();
528 } else if (!strcasecmp(cmd, "pachi-result")) {
529 /* More detailed result of the last genmove. */
530 /* For UCT, the output format is: = color move playouts winrate dynkomi */
531 char *reply = NULL;
532 if (engine->result)
533 reply = engine->result(engine, board);
534 if (reply)
535 gtp_reply(id, reply, NULL);
536 else
537 gtp_error(id, "unknown pachi-result command", NULL);
539 } else if (!strcasecmp(cmd, "kgs-chat")) {
540 char *loc;
541 next_tok(loc);
542 char *src;
543 next_tok(src);
544 char *msg;
545 next_tok(msg);
546 char *reply = NULL;
547 if (engine->chat)
548 reply = engine->chat(engine, board, msg);
549 if (reply)
550 gtp_reply(id, reply, NULL);
551 else
552 gtp_error(id, "unknown kgs-chat command", NULL);
554 } else if (!strcasecmp(cmd, "time_left")) {
555 char *arg;
556 next_tok(arg);
557 enum stone color = str2stone(arg);
558 next_tok(arg);
559 int time = atoi(arg);
560 next_tok(arg);
561 int stones = atoi(arg);
562 if (!ti[color].ignore_gtp) {
563 time_left(&ti[color], time, stones);
564 } else {
565 if (DEBUGL(2)) fprintf(stderr, "ignored time info\n");
568 gtp_reply(id, NULL);
570 } else if (!strcasecmp(cmd, "time_settings") || !strcasecmp(cmd, "kgs-time_settings")) {
571 char *time_system;
572 char *arg;
573 if (!strcasecmp(cmd, "kgs-time_settings")) {
574 next_tok(time_system);
575 } else {
576 time_system = "canadian";
579 int main_time = 0, byoyomi_time = 0, byoyomi_stones = 0, byoyomi_periods = 0;
580 if (!strcasecmp(time_system, "none")) {
581 main_time = -1;
582 } else if (!strcasecmp(time_system, "absolute")) {
583 next_tok(arg);
584 main_time = atoi(arg);
585 } else if (!strcasecmp(time_system, "byoyomi")) {
586 next_tok(arg);
587 main_time = atoi(arg);
588 next_tok(arg);
589 byoyomi_time = atoi(arg);
590 next_tok(arg);
591 byoyomi_periods = atoi(arg);
592 } else if (!strcasecmp(time_system, "canadian")) {
593 next_tok(arg);
594 main_time = atoi(arg);
595 next_tok(arg);
596 byoyomi_time = atoi(arg);
597 next_tok(arg);
598 byoyomi_stones = atoi(arg);
601 if (DEBUGL(1))
602 fprintf(stderr, "time_settings %d %d/%d*%d\n",
603 main_time, byoyomi_time, byoyomi_stones, byoyomi_periods);
604 if (!ti[S_BLACK].ignore_gtp) {
605 time_settings(&ti[S_BLACK], main_time, byoyomi_time, byoyomi_stones, byoyomi_periods);
606 ti[S_WHITE] = ti[S_BLACK];
607 } else {
608 if (DEBUGL(1)) fprintf(stderr, "ignored time info\n");
611 gtp_reply(id, NULL);
613 } else {
614 gtp_error(id, "unknown command", NULL);
615 return P_UNKNOWN_COMMAND;
617 return P_OK;
619 #undef next_tok