Moggy Patterns: Add block side cut
[pachi.git] / gtp.c
blobc6340fe8a722e49c230502e9c9fee0ca480df87e
1 #define DEBUG
2 #include <assert.h>
3 #include <ctype.h>
4 #include <stdarg.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <unistd.h>
10 #include "board.h"
11 #include "debug.h"
12 #include "engine.h"
13 #include "gtp.h"
14 #include "mq.h"
15 #include "uct/uct.h"
16 #include "version.h"
17 #include "timeinfo.h"
19 #define NO_REPLY (-2)
21 /* Sleep 5 seconds after a game ends to give time to kill the program. */
22 #define GAME_OVER_SLEEP 5
24 void
25 gtp_prefix(char prefix, int id)
27 if (id == NO_REPLY) return;
28 if (id >= 0)
29 printf("%c%d ", prefix, id);
30 else
31 printf("%c ", prefix);
34 void
35 gtp_flush(void)
37 putchar('\n');
38 fflush(stdout);
41 void
42 gtp_output(char prefix, int id, va_list params)
44 if (id == NO_REPLY) return;
45 gtp_prefix(prefix, id);
46 char *s;
47 while ((s = va_arg(params, char *))) {
48 fputs(s, stdout);
50 putchar('\n');
51 gtp_flush();
54 void
55 gtp_reply(int id, ...)
57 va_list params;
58 va_start(params, id);
59 gtp_output('=', id, params);
60 va_end(params);
63 void
64 gtp_error(int id, ...)
66 va_list params;
67 va_start(params, id);
68 gtp_output('?', id, params);
69 va_end(params);
72 /* List of known gtp commands. The internal command pachi-genmoves is not exported,
73 * it should only be used between master and slaves of the distributed engine. */
74 static char *known_commands =
75 "protocol_version\n"
76 "name\n"
77 "version\n"
78 "list_commands\n"
79 "quit\n"
80 "boardsize\n"
81 "clear_board\n"
82 "kgs-game_over\n"
83 "komi\n"
84 "kgs-rules\n"
85 "play\n"
86 "genmove\n"
87 "kgs-genmove_cleanup\n"
88 "set_free_handicap\n"
89 "place_free_handicap\n"
90 "final_status_list\n"
91 "kgs-chat\n"
92 "time_left\n"
93 "time_settings\n"
94 "kgs-time_settings";
97 /* Return true if cmd is a valid gtp command. */
98 bool
99 gtp_is_valid(char *cmd)
101 if (!cmd || !*cmd) return false;
102 char *s = strcasestr(known_commands, cmd);
103 if (!s) return false;
105 int len = strlen(cmd);
106 return s[len] == '\0' || s[len] == '\n';
109 /* XXX: THIS IS TOTALLY INSECURE!!!!
110 * Even basic input checking is missing. */
112 enum parse_code
113 gtp_parse(struct board *board, struct engine *engine, struct time_info *ti, char *buf)
115 #define next_tok(to_) \
116 to_ = next; \
117 next = next + strcspn(next, " \t\r\n"); \
118 if (*next) { \
119 *next = 0; next++; \
120 next += strspn(next, " \t\r\n"); \
123 if (strchr(buf, '#'))
124 *strchr(buf, '#') = 0;
126 char *cmd, *next = buf;
127 next_tok(cmd);
129 int id = -1;
130 if (isdigit(*cmd)) {
131 id = atoi(cmd);
132 next_tok(cmd);
135 if (!*cmd)
136 return P_OK;
138 if (!strcasecmp(cmd, "protocol_version")) {
139 gtp_reply(id, "2", NULL);
140 return P_OK;
142 } else if (!strcasecmp(cmd, "name")) {
143 /* KGS hack */
144 gtp_reply(id, "Pachi ", engine->name, NULL);
145 return P_OK;
147 } else if (!strcasecmp(cmd, "version")) {
148 gtp_reply(id, PACHI_VERSION, ": ", engine->comment, NULL);
149 return P_OK;
151 } else if (!strcasecmp(cmd, "list_commands")) {
152 gtp_reply(id, known_commands, NULL);
153 return P_OK;
156 if (engine->notify) {
157 char *reply;
158 enum parse_code c = engine->notify(engine, board, id, cmd, next, &reply);
159 if (c == P_NOREPLY) {
160 id = NO_REPLY;
161 } else if (c == P_DONE_OK) {
162 gtp_reply(id, reply, NULL);
163 return P_OK;
164 } else if (c == P_DONE_ERROR) {
165 gtp_error(id, reply, NULL);
166 /* This is an internal error for the engine, but
167 * it is still OK from main's point of view. */
168 return P_OK;
169 } else if (c != P_OK) {
170 return c;
174 if (!strcasecmp(cmd, "quit")) {
175 gtp_reply(id, NULL);
176 exit(0);
178 } else if (!strcasecmp(cmd, "boardsize")) {
179 char *arg;
180 next_tok(arg);
181 int size = atoi(arg);
182 if (size < 1 || size > BOARD_MAX_SIZE) {
183 gtp_error(id, "illegal board size", NULL);
184 return P_OK;
186 board_resize(board, size);
187 gtp_reply(id, NULL);
189 } else if (!strcasecmp(cmd, "clear_board") || !strcasecmp(cmd, "kgs-game_over")) {
190 board_clear(board);
191 if (DEBUGL(1))
192 board_print(board, stderr);
193 if (!strcasecmp(cmd, "kgs-game_over")) {
194 if (DEBUGL(0))
195 fprintf(stderr, "game is over\n");
196 /* Sleep before replying, so that kgs doesn't
197 * start another game immediately. */
198 sleep(GAME_OVER_SLEEP);
200 gtp_reply(id, NULL);
201 return P_ENGINE_RESET;
203 } else if (!strcasecmp(cmd, "komi")) {
204 char *arg;
205 next_tok(arg);
206 sscanf(arg, "%f", &board->komi);
208 if (DEBUGL(1))
209 board_print(board, stderr);
210 gtp_reply(id, NULL);
212 } else if (!strcasecmp(cmd, "kgs-rules")) {
213 char *arg;
214 next_tok(arg);
215 if (!strcasecmp(arg, "japanese")) {
216 board->rules = RULES_JAPANESE;
217 } else if (!strcasecmp(arg, "chinese")) {
218 board->rules = RULES_CHINESE;
219 } else if (!strcasecmp(arg, "aga")) {
220 board->rules = RULES_AGA;
221 } else if (!strcasecmp(arg, "new_zealand")) {
222 board->rules = RULES_NEW_ZEALAND;
223 } else {
224 gtp_error(id, "unknown rules", NULL);
225 return P_OK;
227 gtp_reply(id, NULL);
229 } else if (!strcasecmp(cmd, "play")) {
230 struct move m;
232 char *arg;
233 next_tok(arg);
234 m.color = str2stone(arg);
235 next_tok(arg);
236 coord_t *c = str2coord(arg, board_size(board));
237 m.coord = *c; coord_done(c);
238 char *reply = NULL;
240 if (DEBUGL(1))
241 fprintf(stderr, "got move %d,%d,%d\n", m.color, coord_x(m.coord, board), coord_y(m.coord, board));
243 // This is where kgs starts the timer, not at genmove!
244 time_start_timer(&ti[stone_other(m.color)]);
246 if (engine->notify_play)
247 reply = engine->notify_play(engine, board, &m);
248 if (board_play(board, &m) < 0) {
249 if (DEBUGL(0)) {
250 fprintf(stderr, "! ILLEGAL MOVE %d,%d,%d\n", m.color, coord_x(m.coord, board), coord_y(m.coord, board));
251 board_print(board, stderr);
253 gtp_error(id, "illegal move", NULL);
254 } else {
255 if (DEBUGL(1))
256 board_print_custom(board, stderr, engine->printhook);
257 gtp_reply(id, reply, NULL);
260 } else if (!strcasecmp(cmd, "genmove") || !strcasecmp(cmd, "kgs-genmove_cleanup")) {
261 char *arg;
262 next_tok(arg);
263 enum stone color = str2stone(arg);
265 coord_t *c = engine->genmove(engine, board, &ti[color], color, !strcasecmp(cmd, "kgs-genmove_cleanup"));
266 struct move m = { *c, color };
267 if (board_play(board, &m) < 0) {
268 fprintf(stderr, "Attempted to generate an illegal move: [%s, %s]\n", coord2sstr(m.coord, board), stone2str(m.color));
269 abort();
271 char *str = coord2str(*c, board);
272 if (DEBUGL(1))
273 fprintf(stderr, "playing move %s\n", str);
274 if (DEBUGL(1)) {
275 board_print_custom(board, stderr, engine->printhook);
277 gtp_reply(id, str, NULL);
278 free(str); coord_done(c);
280 /* Account for spent time. If our GTP peer keeps our clock, this will
281 * be overriden by next time_left GTP command properly. */
282 /* (XXX: Except if we pass to byoyomi and the peer doesn't, but that
283 * should be absolutely rare situation and we will just spend a little
284 * less time than we could on next few moves.) */
285 if (ti[color].period != TT_NULL && ti[color].dim == TD_WALLTIME)
286 time_sub(&ti[color], time_now() - ti[color].len.t.timer_start, true);
288 } else if (!strcasecmp(cmd, "pachi-genmoves") || !strcasecmp(cmd, "pachi-genmoves_cleanup")) {
289 char *arg;
290 next_tok(arg);
291 enum stone color = str2stone(arg);
292 void *stats;
293 int stats_size;
295 char *reply = engine->genmoves(engine, board, &ti[color], color, next,
296 !strcasecmp(cmd, "pachi-genmoves_cleanup"),
297 &stats, &stats_size);
298 if (!reply) {
299 gtp_error(id, "genmoves error", NULL);
300 return P_OK;
302 if (DEBUGL(3))
303 fprintf(stderr, "proposing moves %s\n", reply);
304 if (DEBUGL(4))
305 board_print_custom(board, stderr, engine->printhook);
306 gtp_reply(id, reply, NULL);
307 if (stats_size > 0) {
308 double start = time_now();
309 fwrite(stats, 1, stats_size, stdout);
310 fflush(stdout);
311 if (DEBUGVV(2))
312 fprintf(stderr, "sent reply %d bytes in %.4fms\n",
313 stats_size, (time_now() - start)*1000);
316 } else if (!strcasecmp(cmd, "set_free_handicap")) {
317 struct move m;
318 m.color = S_BLACK;
320 char *arg;
321 next_tok(arg);
322 do {
323 coord_t *c = str2coord(arg, board_size(board));
324 m.coord = *c; coord_done(c);
325 if (DEBUGL(1))
326 fprintf(stderr, "setting handicap %d,%d\n", coord_x(m.coord, board), coord_y(m.coord, board));
328 if (board_play(board, &m) < 0) {
329 if (DEBUGL(0))
330 fprintf(stderr, "! ILLEGAL MOVE %d,%d,%d\n", m.color, coord_x(m.coord, board), coord_y(m.coord, board));
331 gtp_error(id, "illegal move", NULL);
333 board->handicap++;
334 next_tok(arg);
335 } while (*arg);
336 if (DEBUGL(1))
337 board_print(board, stderr);
338 gtp_reply(id, NULL);
340 /* TODO: Engine should choose free handicap; however, it tends to take
341 * overly long to think it all out, and unless it's clever its
342 * handicap stones won't be of much help. ;-) */
343 } else if (!strcasecmp(cmd, "place_free_handicap")
344 || !strcasecmp(cmd, "fixed_handicap")) {
345 char *arg;
346 next_tok(arg);
347 int stones = atoi(arg);
349 gtp_prefix('=', id);
350 board_handicap(board, stones, id == NO_REPLY ? NULL : stdout);
351 if (DEBUGL(1))
352 board_print(board, stderr);
353 if (id == NO_REPLY) return P_OK;
354 putchar('\n');
355 gtp_flush();
357 } else if (!strcasecmp(cmd, "final_score")) {
358 struct move_queue q = { .moves = 0 };
359 if (engine->dead_group_list)
360 engine->dead_group_list(engine, board, &q);
361 float score = board_official_score(board, &q);
362 char str[64];
363 if (DEBUGL(1))
364 fprintf(stderr, "counted score %.1f\n", score);
365 if (score == 0) {
366 gtp_reply(id, "0", NULL);
367 } else if (score > 0) {
368 snprintf(str, 64, "W+%.1f", score);
369 gtp_reply(id, str, NULL);
370 } else {
371 snprintf(str, 64, "B+%.1f", -score);
372 gtp_reply(id, str, NULL);
375 /* XXX: This is a huge hack. */
376 } else if (!strcasecmp(cmd, "final_status_list")) {
377 if (id == NO_REPLY) return P_OK;
378 char *arg;
379 next_tok(arg);
380 struct move_queue q = { .moves = 0 };
381 if (engine->dead_group_list)
382 engine->dead_group_list(engine, board, &q);
383 /* else we return empty list - i.e. engine not supporting
384 * this assumes all stones alive at the game end. */
385 if (!strcasecmp(arg, "dead")) {
386 gtp_prefix('=', id);
387 for (unsigned int i = 0; i < q.moves; i++) {
388 foreach_in_group(board, q.move[i]) {
389 printf("%s ", coord2sstr(c, board));
390 } foreach_in_group_end;
391 putchar('\n');
393 if (!q.moves)
394 putchar('\n');
395 gtp_flush();
396 } else if (!strcasecmp(arg, "seki") || !strcasecmp(arg, "alive")) {
397 gtp_prefix('=', id);
398 bool printed_group = false;
399 foreach_point(board) { // foreach_group, effectively
400 group_t g = group_at(board, c);
401 if (!g || g != c) continue;
403 for (unsigned int i = 0; i < q.moves; i++) {
404 if (q.move[i] == g)
405 goto next_group;
407 foreach_in_group(board, g) {
408 printf("%s ", coord2sstr(c, board));
409 } foreach_in_group_end;
410 putchar('\n');
411 printed_group = true;
412 next_group:;
413 } foreach_point_end;
414 if (!printed_group)
415 putchar('\n');
416 gtp_flush();
417 } else {
418 gtp_error(id, "illegal status specifier", NULL);
421 /* Custom commands for handling UCT opening book */
422 } else if (!strcasecmp(cmd, "uct_genbook")) {
423 /* Board must be initialized properly, as if for genmove;
424 * makes sense only as 'uct_genbook b'. */
425 char *arg;
426 next_tok(arg);
427 enum stone color = str2stone(arg);
428 if (uct_genbook(engine, board, &ti[color], color))
429 gtp_reply(id, NULL);
430 else
431 gtp_error(id, "error generating book", NULL);
433 } else if (!strcasecmp(cmd, "uct_dumpbook")) {
434 char *arg;
435 next_tok(arg);
436 enum stone color = str2stone(arg);
437 uct_dumpbook(engine, board, color);
438 gtp_reply(id, NULL);
440 } else if (!strcasecmp(cmd, "kgs-chat")) {
441 char *loc;
442 next_tok(loc);
443 char *src;
444 next_tok(src);
445 char *msg;
446 next_tok(msg);
447 char *reply = NULL;
448 if (engine->chat)
449 reply = engine->chat(engine, board, msg);
450 if (reply)
451 gtp_reply(id, reply, NULL);
452 else
453 gtp_error(id, "unknown chat command", NULL);
455 } else if (!strcasecmp(cmd, "time_left")) {
456 char *arg;
457 next_tok(arg);
458 enum stone color = str2stone(arg);
459 next_tok(arg);
460 int time = atoi(arg);
461 next_tok(arg);
462 int stones = atoi(arg);
463 if (!ti[color].ignore_gtp) {
464 time_left(&ti[color], time, stones);
465 } else {
466 if (DEBUGL(2)) fprintf(stderr, "ignored time info\n");
469 gtp_reply(id, NULL);
471 } else if (!strcasecmp(cmd, "time_settings") || !strcasecmp(cmd, "kgs-time_settings")) {
472 char *time_system;
473 char *arg;
474 if (!strcasecmp(cmd, "kgs-time_settings")) {
475 next_tok(time_system);
476 } else {
477 time_system = "canadian";
480 int main_time = 0, byoyomi_time = 0, byoyomi_stones = 0, byoyomi_periods = 0;
481 if (!strcasecmp(time_system, "none")) {
482 main_time = -1;
483 } else if (!strcasecmp(time_system, "absolute")) {
484 next_tok(arg);
485 main_time = atoi(arg);
486 } else if (!strcasecmp(time_system, "byoyomi")) {
487 next_tok(arg);
488 main_time = atoi(arg);
489 next_tok(arg);
490 byoyomi_time = atoi(arg);
491 next_tok(arg);
492 byoyomi_periods = atoi(arg);
493 } else if (!strcasecmp(time_system, "canadian")) {
494 next_tok(arg);
495 main_time = atoi(arg);
496 next_tok(arg);
497 byoyomi_time = atoi(arg);
498 next_tok(arg);
499 byoyomi_stones = atoi(arg);
502 if (DEBUGL(1))
503 fprintf(stderr, "time_settings %d %d/%d*%d\n",
504 main_time, byoyomi_time, byoyomi_stones, byoyomi_periods);
505 if (!ti[S_BLACK].ignore_gtp) {
506 time_settings(&ti[S_BLACK], main_time, byoyomi_time, byoyomi_stones, byoyomi_periods);
507 ti[S_WHITE] = ti[S_BLACK];
508 } else {
509 if (DEBUGL(1)) fprintf(stderr, "ignored time info\n");
512 gtp_reply(id, NULL);
514 } else {
515 gtp_error(id, "unknown command", NULL);
516 return P_UNKNOWN_COMMAND;
518 return P_OK;
520 #undef next_tok