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