Home | History | Annotate | Line # | Download | only in gomoku
main.c revision 1.70
      1 /*	$NetBSD: main.c,v 1.70 2022/05/29 14:37:44 rillig Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1994
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * This code is derived from software contributed to Berkeley by
      8  * Ralph Campbell.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. Neither the name of the University nor the names of its contributors
     19  *    may be used to endorse or promote products derived from this software
     20  *    without specific prior written permission.
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     32  * SUCH DAMAGE.
     33  */
     34 
     35 #include <sys/cdefs.h>
     36 __COPYRIGHT("@(#) Copyright (c) 1994\
     37  The Regents of the University of California.  All rights reserved.");
     38 /*	@(#)main.c	8.4 (Berkeley) 5/4/95	*/
     39 __RCSID("$NetBSD: main.c,v 1.70 2022/05/29 14:37:44 rillig Exp $");
     40 
     41 #include <sys/stat.h>
     42 #include <curses.h>
     43 #include <err.h>
     44 #include <limits.h>
     45 #include <signal.h>
     46 #include <stdarg.h>
     47 #include <stdlib.h>
     48 #include <string.h>
     49 #include <time.h>
     50 #include <unistd.h>
     51 
     52 #include "gomoku.h"
     53 
     54 enum input_source {
     55 	USER,			/* get input from standard input */
     56 	PROGRAM,		/* get input from program */
     57 	INPUTF			/* get input from a file */
     58 };
     59 
     60 enum testing_mode {
     61 	NORMAL_PLAY,
     62 	USER_VS_USER,
     63 	PROGRAM_VS_PROGRAM
     64 };
     65 
     66 bool	interactive = true;	/* true if interactive */
     67 int	debug;			/* > 0 if debugging */
     68 static enum testing_mode test = NORMAL_PLAY;
     69 static char *prog;		/* name of program */
     70 static char user[LOGIN_NAME_MAX]; /* name of player */
     71 static FILE *debugfp;		/* file for debug output */
     72 static FILE *inputfp;		/* file for debug input */
     73 
     74 const char	pdir[4]		= "-\\|/";
     75 
     76 struct	spotstr	board[BAREA];		/* info for board */
     77 struct	combostr frames[FAREA];		/* storage for all frames */
     78 struct	combostr *sortframes[2];	/* sorted list of non-empty frames */
     79 u_char	overlap[FAREA * FAREA];		/* non-zero if frame [a][b] overlap;
     80 					 * see init_overlap */
     81 spot_index intersect[FAREA * FAREA];	/* frame [a][b] intersection */
     82 struct game game;
     83 const char *plyr[2] = { "???", "???" };	/* who's who */
     84 
     85 static int readinput(FILE *);
     86 static void misclog(const char *, ...) __printflike(1, 2);
     87 static void quit(void) __dead;
     88 #if !defined(DEBUG)
     89 static void quitsig(int) __dead;
     90 #endif
     91 
     92 static void
     93 warn_if_exists(const char *fname)
     94 {
     95 	struct stat st;
     96 
     97 	if (lstat(fname, &st) == 0) {
     98 		int x, y;
     99 		getyx(stdscr, y, x);
    100 		addstr("  (already exists)");
    101 		move(y, x);
    102 	} else
    103 		clrtoeol();
    104 }
    105 
    106 static void
    107 save_game(void)
    108 {
    109 	char fname[PATH_MAX];
    110 	FILE *fp;
    111 
    112 	ask("Save file name? ");
    113 	(void)get_line(fname, sizeof(fname), warn_if_exists);
    114 	if ((fp = fopen(fname, "w")) == NULL) {
    115 		misclog("cannot create save file");
    116 		return;
    117 	}
    118 	for (unsigned int m = 0; m < game.nmoves; m++)
    119 		fprintf(fp, "%s\n", stoc(game.moves[m]));
    120 	fclose(fp);
    121 }
    122 
    123 static void
    124 parse_args(int argc, char **argv)
    125 {
    126 	int ch;
    127 
    128 	prog = strrchr(argv[0], '/');
    129 	prog = prog != NULL ? prog + 1 : argv[0];
    130 
    131 	while ((ch = getopt(argc, argv, "bcdD:u")) != -1) {
    132 		switch (ch) {
    133 		case 'b':	/* background */
    134 			interactive = false;
    135 			break;
    136 		case 'c':
    137 			test = PROGRAM_VS_PROGRAM;
    138 			break;
    139 		case 'd':
    140 			debug++;
    141 			break;
    142 		case 'D':	/* log debug output to file */
    143 			if ((debugfp = fopen(optarg, "w")) == NULL)
    144 				err(1, "%s", optarg);
    145 			break;
    146 		case 'u':
    147 			test = USER_VS_USER;
    148 			break;
    149 		default:
    150 		usage:
    151 			fprintf(stderr, "usage: %s [-bcdu] [-Dfile] [file]\n",
    152 			    getprogname());
    153 			exit(EXIT_FAILURE);
    154 		}
    155 	}
    156 	argc -= optind;
    157 	argv += optind;
    158 	if (argc > 1)
    159 		goto usage;
    160 	if (argc == 1 && (inputfp = fopen(*argv, "r")) == NULL)
    161 		err(1, "%s", *argv);
    162 }
    163 
    164 static void
    165 set_input_sources(enum input_source *input, int color)
    166 {
    167 	switch (test) {
    168 	case NORMAL_PLAY:
    169 		input[color] = USER;
    170 		input[color != BLACK ? BLACK : WHITE] = PROGRAM;
    171 		break;
    172 	case USER_VS_USER:
    173 		input[BLACK] = USER;
    174 		input[WHITE] = USER;
    175 		break;
    176 	case PROGRAM_VS_PROGRAM:
    177 		input[BLACK] = PROGRAM;
    178 		input[WHITE] = PROGRAM;
    179 		break;
    180 	}
    181 }
    182 
    183 static int
    184 ask_user_color(void)
    185 {
    186 	int color;
    187 
    188 	mvprintw(BSZ + 3, 0, "Black moves first. ");
    189 	ask("(B)lack or (W)hite? ");
    190 	for (;;) {
    191 		int ch = get_key(NULL);
    192 		if (ch == 'b' || ch == 'B') {
    193 			color = BLACK;
    194 			break;
    195 		}
    196 		if (ch == 'w' || ch == 'W') {
    197 			color = WHITE;
    198 			break;
    199 		}
    200 		if (ch == 'q' || ch == 'Q')
    201 			quit();
    202 
    203 		beep();
    204 		ask("Please choose (B)lack or (W)hite: ");
    205 	}
    206 	move(BSZ + 3, 0);
    207 	clrtoeol();
    208 	return color;
    209 }
    210 
    211 static int
    212 read_color(void)
    213 {
    214 	char buf[128];
    215 
    216 	get_line(buf, sizeof(buf), NULL);
    217 	if (strcmp(buf, "black") == 0)
    218 		return BLACK;
    219 	if (strcmp(buf, "white") == 0)
    220 		return WHITE;
    221 	panic("Huh?  Expected `black' or `white', got `%s'\n", buf);
    222 	/* NOTREACHED */
    223 }
    224 
    225 static spot_index
    226 read_move(void)
    227 {
    228 again:
    229 	if (interactive) {
    230 		ask("Select move, (S)ave or (Q)uit.");
    231 		spot_index s = get_coord();
    232 		if (s == SAVE) {
    233 			save_game();
    234 			goto again;
    235 		}
    236 		if (s != RESIGN && board[s].s_occ != EMPTY) {
    237 			beep();
    238 			goto again;
    239 		}
    240 		return s;
    241 	} else {
    242 		char buf[128];
    243 		if (!get_line(buf, sizeof(buf), NULL))
    244 			return RESIGN;
    245 		if (buf[0] == '\0')
    246 			goto again;
    247 		return ctos(buf);
    248 	}
    249 }
    250 
    251 static void
    252 declare_winner(int outcome, const enum input_source *input, int color)
    253 {
    254 
    255 	move(BSZ + 3, 0);
    256 	switch (outcome) {
    257 	case WIN:
    258 		if (input[color] == PROGRAM)
    259 			addstr("Ha ha, I won");
    260 		else if (input[0] == USER && input[1] == USER)
    261 			addstr("Well, you won (and lost)");
    262 		else
    263 			addstr("Rats! you won");
    264 		break;
    265 	case TIE:
    266 		addstr("Wow! It's a tie");
    267 		break;
    268 	case ILLEGAL:
    269 		addstr("Illegal move");
    270 		break;
    271 	}
    272 	clrtoeol();
    273 	bdisp();
    274 }
    275 
    276 struct outcome {
    277 	int result;
    278 	int winner;
    279 };
    280 
    281 static struct outcome
    282 main_game_loop(enum input_source *input)
    283 {
    284 	int color, curmove, outcome;
    285 
    286 	curmove = 0;		/* for GCC */
    287 	color = BLACK;
    288 
    289 again:
    290 	switch (input[color]) {
    291 	case INPUTF:
    292 		curmove = readinput(inputfp);
    293 		if (curmove != END_OF_INPUT)
    294 			break;
    295 		set_input_sources(input, color);
    296 		plyr[BLACK] = input[BLACK] == USER ? user : prog;
    297 		plyr[WHITE] = input[WHITE] == USER ? user : prog;
    298 		bdwho();
    299 		refresh();
    300 		goto again;
    301 
    302 	case USER:
    303 		curmove = read_move();
    304 		break;
    305 
    306 	case PROGRAM:
    307 		if (interactive)
    308 			ask("Thinking...");
    309 		curmove = pickmove(color);
    310 		break;
    311 	}
    312 
    313 	if (interactive && curmove != ILLEGAL) {
    314 		misclog("%3u%*s%-6s",
    315 		    game.nmoves + 1, color == BLACK ? 2 : 9, "",
    316 		    stoc(curmove));
    317 	}
    318 
    319 	if ((outcome = makemove(color, curmove)) != MOVEOK)
    320 		return (struct outcome){ outcome, color };
    321 
    322 	if (interactive)
    323 		bdisp();
    324 	color = color != BLACK ? BLACK : WHITE;
    325 	goto again;
    326 }
    327 
    328 int
    329 main(int argc, char **argv)
    330 {
    331 	char *user_name;
    332 	int color;
    333 	enum input_source input[2];
    334 
    335 	/* Revoke setgid privileges */
    336 	setgid(getgid());
    337 
    338 	setprogname(argv[0]);
    339 
    340 	user_name = getlogin();
    341 	strlcpy(user, user_name != NULL ? user_name : "you", sizeof(user));
    342 
    343 	color = BLACK;
    344 
    345 	parse_args(argc, argv);
    346 
    347 	if (debug == 0)
    348 		srandom((unsigned int)time(0));
    349 	if (interactive)
    350 		cursinit();		/* initialize curses */
    351 again:
    352 	init_board();			/* initialize board contents */
    353 
    354 	if (interactive) {
    355 		bdisp_init();		/* initialize display of board */
    356 #ifdef DEBUG
    357 		signal(SIGINT, whatsup);
    358 #else
    359 		signal(SIGINT, quitsig);
    360 #endif
    361 
    362 		if (inputfp == NULL && test == NORMAL_PLAY)
    363 			color = ask_user_color();
    364 	} else {
    365 		setbuf(stdout, NULL);
    366 		color = read_color();
    367 	}
    368 
    369 	if (inputfp != NULL) {
    370 		input[BLACK] = INPUTF;
    371 		input[WHITE] = INPUTF;
    372 	} else {
    373 		set_input_sources(input, color);
    374 	}
    375 	if (interactive) {
    376 		plyr[BLACK] = input[BLACK] == USER ? user : prog;
    377 		plyr[WHITE] = input[WHITE] == USER ? user : prog;
    378 		bdwho();
    379 		refresh();
    380 	}
    381 
    382 	struct outcome outcome = main_game_loop(input);
    383 
    384 	if (interactive) {
    385 		declare_winner(outcome.result, input, outcome.winner);
    386 		if (outcome.result != RESIGN) {
    387 		replay:
    388 			ask("Play again? ");
    389 			int ch = get_key("YyNnQqSs");
    390 			if (ch == 'Y' || ch == 'y')
    391 				goto again;
    392 			if (ch == 'S' || ch == 's') {
    393 				save_game();
    394 				goto replay;
    395 			}
    396 		}
    397 	}
    398 	quit();
    399 }
    400 
    401 static int
    402 readinput(FILE *fp)
    403 {
    404 	int c;
    405 	char buf[128];
    406 	size_t pos;
    407 
    408 	pos = 0;
    409 	while ((c = getc(fp)) != EOF && c != '\n' && pos < sizeof(buf) - 1)
    410 		buf[pos++] = c;
    411 	buf[pos] = '\0';
    412 	return c == EOF ? END_OF_INPUT : ctos(buf);
    413 }
    414 
    415 #ifdef DEBUG
    416 /*
    417  * Handle strange situations and ^C.
    418  */
    419 /* ARGSUSED */
    420 void
    421 whatsup(int signum __unused)
    422 {
    423 	int n, s1, s2, d1, d2, color;
    424 	spot_index s;
    425 	struct spotstr *sp;
    426 	FILE *fp;
    427 	char *str;
    428 	struct elist *ep;
    429 	struct combostr *cbp;
    430 	char input[128];
    431 	char tmp[128];
    432 
    433 	if (!interactive)
    434 		quit();
    435 top:
    436 	ask("debug command: ");
    437 	if (!get_line(input, sizeof(input), NULL))
    438 		quit();
    439 	switch (*input) {
    440 	case '\0':
    441 		goto top;
    442 	case 'q':		/* conservative quit */
    443 		quit();
    444 		/* NOTREACHED */
    445 	case 'd':		/* set debug level */
    446 		debug = input[1] - '0';
    447 		debuglog("Debug set to %d", debug);
    448 		goto top;
    449 	case 'c':
    450 		break;
    451 	case 'b':		/* back up a move */
    452 		if (game.nmoves > 0) {
    453 			game.nmoves--;
    454 			board[game.moves[game.nmoves]].s_occ = EMPTY;
    455 			bdisp();
    456 		}
    457 		goto top;
    458 	case 's':		/* suggest a move */
    459 		color = input[1] == 'b' ? BLACK : WHITE;
    460 		debuglog("suggest %c %s", color == BLACK ? 'B' : 'W',
    461 			stoc(pickmove(color)));
    462 		goto top;
    463 	case 'f':		/* go forward a move */
    464 		board[game.moves[game.nmoves]].s_occ =
    465 		    game.nmoves % 2 == 0 ? BLACK : WHITE;
    466 		game.nmoves++;
    467 		bdisp();
    468 		goto top;
    469 	case 'l':		/* print move history */
    470 		if (input[1] == '\0') {
    471 			for (unsigned int m = 0; m < game.nmoves; m++)
    472 				debuglog("%s", stoc(game.moves[m]));
    473 			goto top;
    474 		}
    475 		if ((fp = fopen(input + 1, "w")) == NULL)
    476 			goto top;
    477 		for (unsigned int m = 0; m < game.nmoves; m++) {
    478 			fprintf(fp, "%s", stoc(game.moves[m]));
    479 			if (++m < game.nmoves)
    480 				fprintf(fp, " %s\n", stoc(game.moves[m]));
    481 			else
    482 				fputc('\n', fp);
    483 		}
    484 		bdump(fp);
    485 		fclose(fp);
    486 		goto top;
    487 	case 'o':
    488 		/* avoid use w/o initialization on invalid input */
    489 		d1 = s1 = 0;
    490 
    491 		n = 0;
    492 		for (str = input + 1; *str != '\0'; str++)
    493 			if (*str == ',') {
    494 				for (d1 = 0; d1 < 4; d1++)
    495 					if (str[-1] == pdir[d1])
    496 						break;
    497 				str[-1] = '\0';
    498 				sp = &board[s1 = ctos(input + 1)];
    499 				n = sp->s_frame[d1] * FAREA;
    500 				*str++ = '\0';
    501 				break;
    502 			}
    503 		sp = &board[s2 = ctos(str)];
    504 		while (*str != '\0')
    505 			str++;
    506 		for (d2 = 0; d2 < 4; d2++)
    507 			if (str[-1] == pdir[d2])
    508 				break;
    509 		n += sp->s_frame[d2];
    510 		debuglog("overlap %s%c,%s%c = %x", stoc(s1), pdir[d1],
    511 		    stoc(s2), pdir[d2], overlap[n]);
    512 		goto top;
    513 	case 'p':
    514 		sp = &board[s = ctos(input + 1)];
    515 		debuglog("V %s %x/%d %d %x/%d %d %d %x", stoc(s),
    516 			sp->s_combo[BLACK].s, sp->s_level[BLACK],
    517 			sp->s_nforce[BLACK],
    518 			sp->s_combo[WHITE].s, sp->s_level[WHITE],
    519 			sp->s_nforce[WHITE], sp->s_wval, sp->s_flags);
    520 		debuglog("FB %s %x %x %x %x", stoc(s),
    521 			sp->s_fval[BLACK][0].s, sp->s_fval[BLACK][1].s,
    522 			sp->s_fval[BLACK][2].s, sp->s_fval[BLACK][3].s);
    523 		debuglog("FW %s %x %x %x %x", stoc(s),
    524 			sp->s_fval[WHITE][0].s, sp->s_fval[WHITE][1].s,
    525 			sp->s_fval[WHITE][2].s, sp->s_fval[WHITE][3].s);
    526 		goto top;
    527 	case 'e':	/* e {b|w} [0-9] spot */
    528 		str = input + 1;
    529 		if (*str >= '0' && *str <= '9')
    530 			n = *str++ - '0';
    531 		else
    532 			n = 0;
    533 		sp = &board[ctos(str)];
    534 		for (ep = sp->s_empty; ep != NULL; ep = ep->e_next) {
    535 			cbp = ep->e_combo;
    536 			if (n != 0) {
    537 				if (cbp->c_nframes > n)
    538 					continue;
    539 				if (cbp->c_nframes != n)
    540 					break;
    541 			}
    542 			printcombo(cbp, tmp, sizeof(tmp));
    543 			debuglog("%s", tmp);
    544 		}
    545 		goto top;
    546 	default:
    547 		debuglog("Options are:");
    548 		debuglog("q    - quit");
    549 		debuglog("c    - continue");
    550 		debuglog("d#   - set debug level to #");
    551 		debuglog("p#   - print values at #");
    552 		goto top;
    553 	}
    554 }
    555 #endif /* DEBUG */
    556 
    557 /*
    558  * Display debug info.
    559  */
    560 void
    561 debuglog(const char *fmt, ...)
    562 {
    563 	va_list ap;
    564 	char buf[128];
    565 
    566 	va_start(ap, fmt);
    567 	vsnprintf(buf, sizeof(buf), fmt, ap);
    568 	va_end(ap);
    569 
    570 	if (debugfp != NULL)
    571 		fprintf(debugfp, "%s\n", buf);
    572 	if (interactive)
    573 		dislog(buf);
    574 	else
    575 		fprintf(stderr, "%s\n", buf);
    576 }
    577 
    578 static void
    579 misclog(const char *fmt, ...)
    580 {
    581 	va_list ap;
    582 	char buf[128];
    583 
    584 	va_start(ap, fmt);
    585 	vsnprintf(buf, sizeof(buf), fmt, ap);
    586 	va_end(ap);
    587 
    588 	if (debugfp != NULL)
    589 		fprintf(debugfp, "%s\n", buf);
    590 	if (interactive)
    591 		dislog(buf);
    592 	else
    593 		printf("%s\n", buf);
    594 }
    595 
    596 static void
    597 quit(void)
    598 {
    599 	if (interactive) {
    600 		bdisp();		/* show final board */
    601 		cursfini();
    602 	}
    603 	exit(0);
    604 }
    605 
    606 #if !defined(DEBUG)
    607 static void
    608 quitsig(int dummy __unused)
    609 {
    610 	quit();
    611 }
    612 #endif
    613 
    614 /*
    615  * Die gracefully.
    616  */
    617 void
    618 panic(const char *fmt, ...)
    619 {
    620 	va_list ap;
    621 
    622 	if (interactive) {
    623 		bdisp();
    624 		cursfini();
    625 	}
    626 
    627 	fprintf(stderr, "%s: ", prog);
    628 	va_start(ap, fmt);
    629 	vfprintf(stderr, fmt, ap);
    630 	va_end(ap);
    631 	fprintf(stderr, "\n");
    632 
    633 	fputs("I resign\n", stdout);
    634 	exit(1);
    635 }
    636