is_middle_ladder(): Factor out middle_ladder_walk()
[pachi.git] / gtp.c
blob804c943dd8caf79e782d49532fdc4bebbf281987
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 "quit\n"
83 "boardsize\n"
84 "clear_board\n"
85 "kgs-game_over\n"
86 "komi\n"
87 "kgs-rules\n"
88 "play\n"
89 "genmove\n"
90 "kgs-genmove_cleanup\n"
91 "set_free_handicap\n"
92 "place_free_handicap\n"
93 "final_status_list\n"
94 "undo\n"
95 "pachi-result\n"
96 "kgs-chat\n"
97 "time_left\n"
98 "time_settings\n"
99 "kgs-time_settings";
102 /* Return true if cmd is a valid gtp command. */
103 bool
104 gtp_is_valid(char *cmd)
106 if (!cmd || !*cmd) return false;
107 char *s = strcasestr(known_commands, cmd);
108 if (!s) return false;
110 int len = strlen(cmd);
111 return s[len] == '\0' || s[len] == '\n';
114 /* XXX: THIS IS TOTALLY INSECURE!!!!
115 * Even basic input checking is missing. */
117 enum parse_code
118 gtp_parse(struct board *board, struct engine *engine, struct time_info *ti, char *buf)
120 #define next_tok(to_) \
121 to_ = next; \
122 next = next + strcspn(next, " \t\r\n"); \
123 if (*next) { \
124 *next = 0; next++; \
125 next += strspn(next, " \t\r\n"); \
128 if (strchr(buf, '#'))
129 *strchr(buf, '#') = 0;
131 char *cmd, *next = buf;
132 next_tok(cmd);
134 int id = -1;
135 if (isdigit(*cmd)) {
136 id = atoi(cmd);
137 next_tok(cmd);
140 if (!*cmd)
141 return P_OK;
143 if (!strcasecmp(cmd, "protocol_version")) {
144 gtp_reply(id, "2", NULL);
145 return P_OK;
147 } else if (!strcasecmp(cmd, "name")) {
148 /* KGS hack */
149 gtp_reply(id, "Pachi ", engine->name, NULL);
150 return P_OK;
152 } else if (!strcasecmp(cmd, "echo")) {
153 gtp_reply(id, next, NULL);
154 return P_OK;
156 } else if (!strcasecmp(cmd, "version")) {
157 gtp_reply(id, PACHI_VERSION, ": ", engine->comment, NULL);
158 return P_OK;
160 } else if (!strcasecmp(cmd, "list_commands")) {
161 gtp_reply(id, known_commands, NULL);
162 return P_OK;
165 if (engine->notify && gtp_is_valid(cmd)) {
166 char *reply;
167 enum parse_code c = engine->notify(engine, board, id, cmd, next, &reply);
168 if (c == P_NOREPLY) {
169 id = NO_REPLY;
170 } else if (c == P_DONE_OK) {
171 gtp_reply(id, reply, NULL);
172 return P_OK;
173 } else if (c == P_DONE_ERROR) {
174 gtp_error(id, reply, NULL);
175 /* This is an internal error for the engine, but
176 * it is still OK from main's point of view. */
177 return P_OK;
178 } else if (c != P_OK) {
179 return c;
183 if (!strcasecmp(cmd, "quit")) {
184 gtp_reply(id, NULL);
185 exit(0);
187 } else if (!strcasecmp(cmd, "boardsize")) {
188 char *arg;
189 next_tok(arg);
190 int size = atoi(arg);
191 if (size < 1 || size > BOARD_MAX_SIZE) {
192 gtp_error(id, "illegal board size", NULL);
193 return P_OK;
195 board_resize(board, size);
196 gtp_reply(id, NULL);
198 } else if (!strcasecmp(cmd, "clear_board")) {
199 board_clear(board);
200 if (DEBUGL(1) && debug_boardprint)
201 board_print(board, stderr);
202 gtp_reply(id, NULL);
203 return P_ENGINE_RESET;
205 } else if (!strcasecmp(cmd, "kgs-game_over")) {
206 /* The game may not be really over, just adjourned.
207 * Do not clear the board to avoid illegal moves
208 * if the game is resumed immediately after. KGS
209 * may start directly with genmove on resumption. */
210 if (DEBUGL(1)) {
211 fprintf(stderr, "game is over\n");
212 fflush(stderr);
214 /* Sleep before replying, so that kgs doesn't
215 * start another game immediately. */
216 sleep(GAME_OVER_SLEEP);
217 gtp_reply(id, NULL);
219 } else if (!strcasecmp(cmd, "komi")) {
220 char *arg;
221 next_tok(arg);
222 sscanf(arg, PRIfloating, &board->komi);
224 if (DEBUGL(1 && debug_boardprint))
225 board_print(board, stderr);
226 gtp_reply(id, NULL);
228 } else if (!strcasecmp(cmd, "kgs-rules")) {
229 char *arg;
230 next_tok(arg);
231 if (!strcasecmp(arg, "japanese")) {
232 board->rules = RULES_JAPANESE;
233 } else if (!strcasecmp(arg, "chinese")) {
234 board->rules = RULES_CHINESE;
235 } else if (!strcasecmp(arg, "aga")) {
236 board->rules = RULES_AGA;
237 } else if (!strcasecmp(arg, "new_zealand")) {
238 board->rules = RULES_NEW_ZEALAND;
239 } else {
240 gtp_error(id, "unknown rules", NULL);
241 return P_OK;
243 gtp_reply(id, NULL);
245 } else if (!strcasecmp(cmd, "play")) {
246 struct move m;
248 char *arg;
249 next_tok(arg);
250 m.color = str2stone(arg);
251 next_tok(arg);
252 coord_t *c = str2coord(arg, board_size(board));
253 m.coord = *c; coord_done(c);
254 char *reply = NULL;
256 if (DEBUGL(1))
257 fprintf(stderr, "got move %d,%d,%d\n", m.color, coord_x(m.coord, board), coord_y(m.coord, board));
259 // This is where kgs starts the timer, not at genmove!
260 time_start_timer(&ti[stone_other(m.color)]);
262 if (engine->notify_play)
263 reply = engine->notify_play(engine, board, &m);
264 if (board_play(board, &m) < 0) {
265 if (DEBUGL(0)) {
266 fprintf(stderr, "! ILLEGAL MOVE %d,%d,%d\n", m.color, coord_x(m.coord, board), coord_y(m.coord, board));
267 board_print(board, stderr);
269 gtp_error(id, "illegal move", NULL);
270 } else {
271 if (DEBUGL(1) && debug_boardprint)
272 board_print_custom(board, stderr, engine->printhook);
273 gtp_reply(id, reply, NULL);
276 } else if (!strcasecmp(cmd, "genmove") || !strcasecmp(cmd, "kgs-genmove_cleanup")) {
277 char *arg;
278 next_tok(arg);
279 enum stone color = str2stone(arg);
280 coord_t *c = NULL;
282 if (!ti[color].len.t.timer_start) {
283 /* First game move. */
284 time_start_timer(&ti[color]);
287 coord_t cf = pass;
288 if (board->fbook)
289 cf = fbook_check(board);
290 if (!is_pass(cf)) {
291 c = coord_copy(cf);
292 } else {
293 c = engine->genmove(engine, board, &ti[color], color, !strcasecmp(cmd, "kgs-genmove_cleanup"));
295 struct move m = { *c, color };
296 if (board_play(board, &m) < 0) {
297 fprintf(stderr, "Attempted to generate an illegal move: [%s, %s]\n", coord2sstr(m.coord, board), stone2str(m.color));
298 abort();
300 char *str = coord2str(*c, board);
301 if (DEBUGL(1))
302 fprintf(stderr, "playing move %s\n", str);
303 if (DEBUGL(1) && debug_boardprint) {
304 board_print_custom(board, stderr, engine->printhook);
306 gtp_reply(id, str, NULL);
307 free(str); coord_done(c);
309 /* Account for spent time. If our GTP peer keeps our clock, this will
310 * be overriden by next time_left GTP command properly. */
311 /* (XXX: Except if we pass to byoyomi and the peer doesn't, but that
312 * should be absolutely rare situation and we will just spend a little
313 * less time than we could on next few moves.) */
314 if (ti[color].period != TT_NULL && ti[color].dim == TD_WALLTIME)
315 time_sub(&ti[color], time_now() - ti[color].len.t.timer_start, true);
317 } else if (!strcasecmp(cmd, "pachi-genmoves") || !strcasecmp(cmd, "pachi-genmoves_cleanup")) {
318 char *arg;
319 next_tok(arg);
320 enum stone color = str2stone(arg);
321 void *stats;
322 int stats_size;
324 char *reply = engine->genmoves(engine, board, &ti[color], color, next,
325 !strcasecmp(cmd, "pachi-genmoves_cleanup"),
326 &stats, &stats_size);
327 if (!reply) {
328 gtp_error(id, "genmoves error", NULL);
329 return P_OK;
331 if (DEBUGL(3))
332 fprintf(stderr, "proposing moves %s\n", reply);
333 if (DEBUGL(4) && debug_boardprint)
334 board_print_custom(board, stderr, engine->printhook);
335 gtp_reply(id, reply, NULL);
336 if (stats_size > 0) {
337 double start = time_now();
338 fwrite(stats, 1, stats_size, stdout);
339 fflush(stdout);
340 if (DEBUGVV(2))
341 fprintf(stderr, "sent reply %d bytes in %.4fms\n",
342 stats_size, (time_now() - start)*1000);
345 } else if (!strcasecmp(cmd, "set_free_handicap")) {
346 struct move m;
347 m.color = S_BLACK;
349 char *arg;
350 next_tok(arg);
351 do {
352 coord_t *c = str2coord(arg, board_size(board));
353 m.coord = *c; coord_done(c);
354 if (DEBUGL(1))
355 fprintf(stderr, "setting handicap %d,%d\n", coord_x(m.coord, board), coord_y(m.coord, board));
357 if (board_play(board, &m) < 0) {
358 if (DEBUGL(0))
359 fprintf(stderr, "! ILLEGAL MOVE %d,%d,%d\n", m.color, coord_x(m.coord, board), coord_y(m.coord, board));
360 gtp_error(id, "illegal move", NULL);
362 board->handicap++;
363 next_tok(arg);
364 } while (*arg);
365 if (DEBUGL(1) && debug_boardprint)
366 board_print(board, stderr);
367 gtp_reply(id, NULL);
369 /* TODO: Engine should choose free handicap; however, it tends to take
370 * overly long to think it all out, and unless it's clever its
371 * handicap stones won't be of much help. ;-) */
372 } else if (!strcasecmp(cmd, "place_free_handicap")
373 || !strcasecmp(cmd, "fixed_handicap")) {
374 char *arg;
375 next_tok(arg);
376 int stones = atoi(arg);
378 gtp_prefix('=', id);
379 board_handicap(board, stones, id == NO_REPLY ? NULL : stdout);
380 if (DEBUGL(1) && debug_boardprint)
381 board_print(board, stderr);
382 if (id == NO_REPLY) return P_OK;
383 putchar('\n');
384 gtp_flush();
386 } else if (!strcasecmp(cmd, "final_score")) {
387 struct move_queue q = { .moves = 0 };
388 if (engine->dead_group_list)
389 engine->dead_group_list(engine, board, &q);
390 floating_t score = board_official_score(board, &q);
391 char str[64];
392 if (DEBUGL(1))
393 fprintf(stderr, "counted score %.1f\n", score);
394 if (score == 0) {
395 gtp_reply(id, "0", NULL);
396 } else if (score > 0) {
397 snprintf(str, 64, "W+%.1f", score);
398 gtp_reply(id, str, NULL);
399 } else {
400 snprintf(str, 64, "B+%.1f", -score);
401 gtp_reply(id, str, NULL);
404 /* XXX: This is a huge hack. */
405 } else if (!strcasecmp(cmd, "final_status_list")) {
406 if (id == NO_REPLY) return P_OK;
407 char *arg;
408 next_tok(arg);
409 struct move_queue q = { .moves = 0 };
410 if (engine->dead_group_list)
411 engine->dead_group_list(engine, board, &q);
412 /* else we return empty list - i.e. engine not supporting
413 * this assumes all stones alive at the game end. */
414 if (!strcasecmp(arg, "dead")) {
415 gtp_prefix('=', id);
416 for (unsigned int i = 0; i < q.moves; i++) {
417 foreach_in_group(board, q.move[i]) {
418 printf("%s ", coord2sstr(c, board));
419 } foreach_in_group_end;
420 putchar('\n');
422 if (!q.moves)
423 putchar('\n');
424 gtp_flush();
425 } else if (!strcasecmp(arg, "seki") || !strcasecmp(arg, "alive")) {
426 gtp_prefix('=', id);
427 bool printed_group = false;
428 foreach_point(board) { // foreach_group, effectively
429 group_t g = group_at(board, c);
430 if (!g || g != c) continue;
432 for (unsigned int i = 0; i < q.moves; i++) {
433 if (q.move[i] == g)
434 goto next_group;
436 foreach_in_group(board, g) {
437 printf("%s ", coord2sstr(c, board));
438 } foreach_in_group_end;
439 putchar('\n');
440 printed_group = true;
441 next_group:;
442 } foreach_point_end;
443 if (!printed_group)
444 putchar('\n');
445 gtp_flush();
446 } else {
447 gtp_error(id, "illegal status specifier", NULL);
450 } else if (!strcasecmp(cmd, "undo")) {
451 if (board_undo(board) < 0) {
452 if (DEBUGL(1)) {
453 fprintf(stderr, "undo on non-pass move %s\n", coord2sstr(board->last_move.coord, board));
454 board_print(board, stderr);
456 gtp_error(id, "cannot undo", NULL);
457 return P_OK;
459 char *reply = NULL;
460 if (engine->undo)
461 reply = engine->undo(engine, board);
462 if (DEBUGL(1) && debug_boardprint)
463 board_print(board, stderr);
464 gtp_reply(id, reply, NULL);
466 /* Custom commands for handling UCT opening tbook */
467 } else if (!strcasecmp(cmd, "uct_gentbook")) {
468 /* Board must be initialized properly, as if for genmove;
469 * makes sense only as 'uct_gentbook b'. */
470 char *arg;
471 next_tok(arg);
472 enum stone color = str2stone(arg);
473 if (uct_gentbook(engine, board, &ti[color], color))
474 gtp_reply(id, NULL);
475 else
476 gtp_error(id, "error generating tbook", NULL);
478 } else if (!strcasecmp(cmd, "uct_dumptbook")) {
479 char *arg;
480 next_tok(arg);
481 enum stone color = str2stone(arg);
482 uct_dumptbook(engine, board, color);
483 gtp_reply(id, NULL);
485 } else if (!strcasecmp(cmd, "uct_evaluate")) {
486 char *arg;
487 next_tok(arg);
488 enum stone color = str2stone(arg);
490 gtp_prefix('=', id);
491 /* Iterate through the list of all free coordinates
492 * and call uct_evaluate() for each. uct_evaluate()
493 * will throw NAN in case of invalid moves and such. */
494 for (int i = 0; i < board->flen; i++) {
495 floating_t val = uct_evaluate(engine, board, &ti[color], board->f[i], color);
496 if (isnan(val))
497 continue;
498 printf("%s %1.3f\n", coord2sstr(board->f[i], board), (double) val);
500 gtp_flush();
502 } else if (!strcasecmp(cmd, "pachi-result")) {
503 /* More detailed result of the last genmove. */
504 /* For UCT, the output format is: = color move playouts winrate dynkomi */
505 char *reply = NULL;
506 if (engine->result)
507 reply = engine->result(engine, board);
508 if (reply)
509 gtp_reply(id, reply, NULL);
510 else
511 gtp_error(id, "unknown pachi-result command", NULL);
513 } else if (!strcasecmp(cmd, "kgs-chat")) {
514 char *loc;
515 next_tok(loc);
516 char *src;
517 next_tok(src);
518 char *msg;
519 next_tok(msg);
520 char *reply = NULL;
521 if (engine->chat)
522 reply = engine->chat(engine, board, msg);
523 if (reply)
524 gtp_reply(id, reply, NULL);
525 else
526 gtp_error(id, "unknown kgs-chat command", NULL);
528 } else if (!strcasecmp(cmd, "time_left")) {
529 char *arg;
530 next_tok(arg);
531 enum stone color = str2stone(arg);
532 next_tok(arg);
533 int time = atoi(arg);
534 next_tok(arg);
535 int stones = atoi(arg);
536 if (!ti[color].ignore_gtp) {
537 time_left(&ti[color], time, stones);
538 } else {
539 if (DEBUGL(2)) fprintf(stderr, "ignored time info\n");
542 gtp_reply(id, NULL);
544 } else if (!strcasecmp(cmd, "time_settings") || !strcasecmp(cmd, "kgs-time_settings")) {
545 char *time_system;
546 char *arg;
547 if (!strcasecmp(cmd, "kgs-time_settings")) {
548 next_tok(time_system);
549 } else {
550 time_system = "canadian";
553 int main_time = 0, byoyomi_time = 0, byoyomi_stones = 0, byoyomi_periods = 0;
554 if (!strcasecmp(time_system, "none")) {
555 main_time = -1;
556 } else if (!strcasecmp(time_system, "absolute")) {
557 next_tok(arg);
558 main_time = atoi(arg);
559 } else if (!strcasecmp(time_system, "byoyomi")) {
560 next_tok(arg);
561 main_time = atoi(arg);
562 next_tok(arg);
563 byoyomi_time = atoi(arg);
564 next_tok(arg);
565 byoyomi_periods = atoi(arg);
566 } else if (!strcasecmp(time_system, "canadian")) {
567 next_tok(arg);
568 main_time = atoi(arg);
569 next_tok(arg);
570 byoyomi_time = atoi(arg);
571 next_tok(arg);
572 byoyomi_stones = atoi(arg);
575 if (DEBUGL(1))
576 fprintf(stderr, "time_settings %d %d/%d*%d\n",
577 main_time, byoyomi_time, byoyomi_stones, byoyomi_periods);
578 if (!ti[S_BLACK].ignore_gtp) {
579 time_settings(&ti[S_BLACK], main_time, byoyomi_time, byoyomi_stones, byoyomi_periods);
580 ti[S_WHITE] = ti[S_BLACK];
581 } else {
582 if (DEBUGL(1)) fprintf(stderr, "ignored time info\n");
585 gtp_reply(id, NULL);
587 } else {
588 gtp_error(id, "unknown command", NULL);
589 return P_UNKNOWN_COMMAND;
591 return P_OK;
593 #undef next_tok