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