Home | History | Annotate | Line # | Download | only in gomoku
main.c revision 1.69
      1 /*	$NetBSD: main.c,v 1.69 2022/05/29 10:37:21 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.69 2022/05/29 10:37:21 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 i = 0; i < game.nmoves; i++)
    119 		fprintf(fp, "%s\n", stoc(game.moves[i]));
    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 i, n, s1, s2, d1, d2;
    424 	struct spotstr *sp;
    425 	FILE *fp;
    426 	char *str;
    427 	struct elist *ep;
    428 	struct combostr *cbp;
    429 	char input[128];
    430 	char tmp[128];
    431 
    432 	if (!interactive)
    433 		quit();
    434 top:
    435 	ask("debug command: ");
    436 	if (!get_line(input, sizeof(input), NULL))
    437 		quit();
    438 	switch (*input) {
    439 	case '\0':
    440 		goto top;
    441 	case 'q':		/* conservative quit */
    442 		quit();
    443 		/* NOTREACHED */
    444 	case 'd':		/* set debug level */
    445 		debug = input[1] - '0';
    446 		debuglog("Debug set to %d", debug);
    447 		goto top;
    448 	case 'c':
    449 		break;
    450 	case 'b':		/* back up a move */
    451 		if (game.nmoves > 0) {
    452 			game.nmoves--;
    453 			board[game.moves[game.nmoves]].s_occ = EMPTY;
    454 			bdisp();
    455 		}
    456 		goto top;
    457 	case 's':		/* suggest a move */
    458 		i = input[1] == 'b' ? BLACK : WHITE;
    459 		debuglog("suggest %c %s", i == BLACK ? 'B' : 'W',
    460 			stoc(pickmove(i)));
    461 		goto top;
    462 	case 'f':		/* go forward a move */
    463 		board[game.moves[game.nmoves]].s_occ =
    464 		    game.nmoves % 2 == 0 ? BLACK : WHITE;
    465 		game.nmoves++;
    466 		bdisp();
    467 		goto top;
    468 	case 'l':		/* print move history */
    469 		if (input[1] == '\0') {
    470 			for (unsigned int m = 0; m < game.nmoves; m++)
    471 				debuglog("%s", stoc(game.moves[m]));
    472 			goto top;
    473 		}
    474 		if ((fp = fopen(input + 1, "w")) == NULL)
    475 			goto top;
    476 		for (unsigned int m = 0; m < game.nmoves; m++) {
    477 			fprintf(fp, "%s", stoc(game.moves[m]));
    478 			if (++m < game.nmoves)
    479 				fprintf(fp, " %s\n", stoc(game.moves[m]));
    480 			else
    481 				fputc('\n', fp);
    482 		}
    483 		bdump(fp);
    484 		fclose(fp);
    485 		goto top;
    486 	case 'o':
    487 		/* avoid use w/o initialization on invalid input */
    488 		d1 = s1 = 0;
    489 
    490 		n = 0;
    491 		for (str = input + 1; *str != '\0'; str++)
    492 			if (*str == ',') {
    493 				for (d1 = 0; d1 < 4; d1++)
    494 					if (str[-1] == pdir[d1])
    495 						break;
    496 				str[-1] = '\0';
    497 				sp = &board[s1 = ctos(input + 1)];
    498 				n = sp->s_frame[d1] * FAREA;
    499 				*str++ = '\0';
    500 				break;
    501 			}
    502 		sp = &board[s2 = ctos(str)];
    503 		while (*str != '\0')
    504 			str++;
    505 		for (d2 = 0; d2 < 4; d2++)
    506 			if (str[-1] == pdir[d2])
    507 				break;
    508 		n += sp->s_frame[d2];
    509 		debuglog("overlap %s%c,%s%c = %x", stoc(s1), pdir[d1],
    510 		    stoc(s2), pdir[d2], overlap[n]);
    511 		goto top;
    512 	case 'p':
    513 		sp = &board[i = ctos(input + 1)];
    514 		debuglog("V %s %x/%d %d %x/%d %d %d %x", stoc(i),
    515 			sp->s_combo[BLACK].s, sp->s_level[BLACK],
    516 			sp->s_nforce[BLACK],
    517 			sp->s_combo[WHITE].s, sp->s_level[WHITE],
    518 			sp->s_nforce[WHITE], sp->s_wval, sp->s_flags);
    519 		debuglog("FB %s %x %x %x %x", stoc(i),
    520 			sp->s_fval[BLACK][0].s, sp->s_fval[BLACK][1].s,
    521 			sp->s_fval[BLACK][2].s, sp->s_fval[BLACK][3].s);
    522 		debuglog("FW %s %x %x %x %x", stoc(i),
    523 			sp->s_fval[WHITE][0].s, sp->s_fval[WHITE][1].s,
    524 			sp->s_fval[WHITE][2].s, sp->s_fval[WHITE][3].s);
    525 		goto top;
    526 	case 'e':	/* e {b|w} [0-9] spot */
    527 		str = input + 1;
    528 		if (*str >= '0' && *str <= '9')
    529 			n = *str++ - '0';
    530 		else
    531 			n = 0;
    532 		sp = &board[i = ctos(str)];
    533 		for (ep = sp->s_empty; ep != NULL; ep = ep->e_next) {
    534 			cbp = ep->e_combo;
    535 			if (n != 0) {
    536 				if (cbp->c_nframes > n)
    537 					continue;
    538 				if (cbp->c_nframes != n)
    539 					break;
    540 			}
    541 			printcombo(cbp, tmp, sizeof(tmp));
    542 			debuglog("%s", tmp);
    543 		}
    544 		goto top;
    545 	default:
    546 		debuglog("Options are:");
    547 		debuglog("q    - quit");
    548 		debuglog("c    - continue");
    549 		debuglog("d#   - set debug level to #");
    550 		debuglog("p#   - print values at #");
    551 		goto top;
    552 	}
    553 }
    554 #endif /* DEBUG */
    555 
    556 /*
    557  * Display debug info.
    558  */
    559 void
    560 debuglog(const char *fmt, ...)
    561 {
    562 	va_list ap;
    563 	char buf[128];
    564 
    565 	va_start(ap, fmt);
    566 	vsnprintf(buf, sizeof(buf), fmt, ap);
    567 	va_end(ap);
    568 
    569 	if (debugfp != NULL)
    570 		fprintf(debugfp, "%s\n", buf);
    571 	if (interactive)
    572 		dislog(buf);
    573 	else
    574 		fprintf(stderr, "%s\n", buf);
    575 }
    576 
    577 static void
    578 misclog(const char *fmt, ...)
    579 {
    580 	va_list ap;
    581 	char buf[128];
    582 
    583 	va_start(ap, fmt);
    584 	vsnprintf(buf, sizeof(buf), fmt, ap);
    585 	va_end(ap);
    586 
    587 	if (debugfp != NULL)
    588 		fprintf(debugfp, "%s\n", buf);
    589 	if (interactive)
    590 		dislog(buf);
    591 	else
    592 		printf("%s\n", buf);
    593 }
    594 
    595 static void
    596 quit(void)
    597 {
    598 	if (interactive) {
    599 		bdisp();		/* show final board */
    600 		cursfini();
    601 	}
    602 	exit(0);
    603 }
    604 
    605 #if !defined(DEBUG)
    606 static void
    607 quitsig(int dummy __unused)
    608 {
    609 	quit();
    610 }
    611 #endif
    612 
    613 /*
    614  * Die gracefully.
    615  */
    616 void
    617 panic(const char *fmt, ...)
    618 {
    619 	va_list ap;
    620 
    621 	if (interactive) {
    622 		bdisp();
    623 		cursfini();
    624 	}
    625 
    626 	fprintf(stderr, "%s: ", prog);
    627 	va_start(ap, fmt);
    628 	vfprintf(stderr, fmt, ap);
    629 	va_end(ap);
    630 	fprintf(stderr, "\n");
    631 
    632 	fputs("I resign\n", stdout);
    633 	exit(1);
    634 }
    635