Home | History | Annotate | Line # | Download | only in gomoku
main.c revision 1.60
      1 /*	$NetBSD: main.c,v 1.60 2022/05/28 06:25:35 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.60 2022/05/28 06:25:35 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 short	intersect[FAREA * FAREA];	/* frame [a][b] intersection */
     82 int	movelog[BSZ * BSZ];		/* log of all played moves */
     83 unsigned int nmoves;			/* number of played moves */
     84 const char *plyr[2] = { "???", "???" };	/* who's who */
     85 
     86 static int readinput(FILE *);
     87 static void misclog(const char *, ...) __printflike(1, 2);
     88 static void quit(void) __dead;
     89 #if !defined(DEBUG)
     90 static void quitsig(int) __dead;
     91 #endif
     92 
     93 static void
     94 warn_if_exists(const char *fname)
     95 {
     96 	struct stat st;
     97 
     98 	if (lstat(fname, &st) == 0) {
     99 		int x, y;
    100 		getyx(stdscr, y, x);
    101 		addstr("  (already exists)");
    102 		move(y, x);
    103 	} else
    104 		clrtoeol();
    105 }
    106 
    107 static void
    108 save_game(void)
    109 {
    110 	char fname[PATH_MAX];
    111 	FILE *fp;
    112 
    113 	ask("Save file name? ");
    114 	(void)get_line(fname, sizeof(fname), warn_if_exists);
    115 	if ((fp = fopen(fname, "w")) == NULL) {
    116 		misclog("cannot create save file");
    117 		return;
    118 	}
    119 	for (unsigned int i = 0; i < nmoves; i++)
    120 		fprintf(fp, "%s\n", stoc(movelog[i]));
    121 	fclose(fp);
    122 }
    123 
    124 static void
    125 parse_args(int argc, char **argv)
    126 {
    127 	int ch;
    128 
    129 	prog = strrchr(argv[0], '/');
    130 	prog = prog != NULL ? prog + 1 : argv[0];
    131 
    132 	while ((ch = getopt(argc, argv, "bcdD:u")) != -1) {
    133 		switch (ch) {
    134 		case 'b':	/* background */
    135 			interactive = false;
    136 			break;
    137 		case 'c':
    138 			test = PROGRAM_VS_PROGRAM;
    139 			break;
    140 		case 'd':
    141 			debug++;
    142 			break;
    143 		case 'D':	/* log debug output to file */
    144 			if ((debugfp = fopen(optarg, "w")) == NULL)
    145 				err(1, "%s", optarg);
    146 			break;
    147 		case 'u':
    148 			test = USER_VS_USER;
    149 			break;
    150 		default:
    151 		usage:
    152 			fprintf(stderr, "usage: %s [-bcdu] [-Dfile] [file]\n",
    153 			    getprogname());
    154 			exit(EXIT_FAILURE);
    155 		}
    156 	}
    157 	argc -= optind;
    158 	argv += optind;
    159 	if (argc > 1)
    160 		goto usage;
    161 	if (argc == 1 && (inputfp = fopen(*argv, "r")) == NULL)
    162 		err(1, "%s", *argv);
    163 }
    164 
    165 static void
    166 set_input_sources(enum input_source *input, int color)
    167 {
    168 	switch (test) {
    169 	case NORMAL_PLAY:
    170 		input[color] = USER;
    171 		input[color != BLACK ? BLACK : WHITE] = PROGRAM;
    172 		break;
    173 	case USER_VS_USER:
    174 		input[BLACK] = USER;
    175 		input[WHITE] = USER;
    176 		break;
    177 	case PROGRAM_VS_PROGRAM:
    178 		input[BLACK] = PROGRAM;
    179 		input[WHITE] = PROGRAM;
    180 		break;
    181 	}
    182 }
    183 
    184 static int
    185 ask_user_color(void)
    186 {
    187 	int color;
    188 
    189 	mvprintw(BSZ + 3, 0, "Black moves first. ");
    190 	ask("(B)lack or (W)hite? ");
    191 	for (;;) {
    192 		int ch = get_key(NULL);
    193 		if (ch == 'b' || ch == 'B') {
    194 			color = BLACK;
    195 			break;
    196 		}
    197 		if (ch == 'w' || ch == 'W') {
    198 			color = WHITE;
    199 			break;
    200 		}
    201 		if (ch == 'q' || ch == 'Q')
    202 			quit();
    203 
    204 		beep();
    205 		ask("Please choose (B)lack or (W)hite: ");
    206 	}
    207 	move(BSZ + 3, 0);
    208 	clrtoeol();
    209 	return color;
    210 }
    211 
    212 static int
    213 read_color(void)
    214 {
    215 	char buf[128];
    216 
    217 	get_line(buf, sizeof(buf), NULL);
    218 	if (strcmp(buf, "black") == 0)
    219 		return BLACK;
    220 	if (strcmp(buf, "white") == 0)
    221 		return WHITE;
    222 	panic("Huh?  Expected `black' or `white', got `%s'\n", buf);
    223 	/* NOTREACHED */
    224 }
    225 
    226 static int
    227 read_move(void)
    228 {
    229 again:
    230 	if (interactive) {
    231 		ask("Select move, (S)ave or (Q)uit.");
    232 		int s = get_coord();
    233 		if (s == SAVE) {
    234 			save_game();
    235 			goto again;
    236 		}
    237 		if (s != RESIGN && board[s].s_occ != EMPTY) {
    238 			beep();
    239 			goto again;
    240 		}
    241 		return s;
    242 	} else {
    243 		char buf[128];
    244 		if (!get_line(buf, sizeof(buf), NULL))
    245 			return RESIGN;
    246 		if (buf[0] == '\0')
    247 			goto again;
    248 		return ctos(buf);
    249 	}
    250 }
    251 
    252 static void
    253 declare_winner(int outcome, const enum input_source *input, int color)
    254 {
    255 
    256 	move(BSZ + 3, 0);
    257 	switch (outcome) {
    258 	case WIN:
    259 		if (input[color] == PROGRAM)
    260 			addstr("Ha ha, I won");
    261 		else if (input[0] == USER && input[1] == USER)
    262 			addstr("Well, you won (and lost)");
    263 		else
    264 			addstr("Rats! you won");
    265 		break;
    266 	case TIE:
    267 		addstr("Wow! It's a tie");
    268 		break;
    269 	case ILLEGAL:
    270 		addstr("Illegal move");
    271 		break;
    272 	}
    273 	clrtoeol();
    274 	bdisp();
    275 }
    276 
    277 struct outcome {
    278 	int result;
    279 	int winner;
    280 };
    281 
    282 static struct outcome
    283 main_game_loop(enum input_source *input)
    284 {
    285 	int color, curmove, outcome;
    286 
    287 	curmove = 0;		/* for GCC */
    288 	color = BLACK;
    289 
    290 again:
    291 	switch (input[color]) {
    292 	case INPUTF:
    293 		curmove = readinput(inputfp);
    294 		if (curmove != EOF)
    295 			break;
    296 		set_input_sources(input, color);
    297 		plyr[BLACK] = input[BLACK] == USER ? user : prog;
    298 		plyr[WHITE] = input[WHITE] == USER ? user : prog;
    299 		bdwho();
    300 		refresh();
    301 		goto again;
    302 
    303 	case USER:
    304 		curmove = read_move();
    305 		break;
    306 
    307 	case PROGRAM:
    308 		if (interactive)
    309 			ask("Thinking...");
    310 		curmove = pickmove(color);
    311 		break;
    312 	}
    313 
    314 	if (interactive && curmove != ILLEGAL) {
    315 		misclog("%3u%*s%-6s",
    316 		    nmoves + 1, color == BLACK ? 2 : 9, "", 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 	bdinit(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') {
    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 ? EOF : ctos(buf);
    413 }
    414 
    415 #ifdef DEBUG
    416 /*
    417  * Handle strange situations.
    418  */
    419 /* ARGSUSED */
    420 void
    421 whatsup(int signum)
    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 (nmoves > 0) {
    452 			nmoves--;
    453 			board[movelog[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[movelog[nmoves]].s_occ =
    464 		    nmoves % 2 == 0 ? BLACK : WHITE;
    465 		nmoves++;
    466 		bdisp();
    467 		goto top;
    468 	case 'l':		/* print move history */
    469 		if (input[1] == '\0') {
    470 			for (unsigned int m = 0; m < nmoves; m++)
    471 				debuglog("%s", stoc(movelog[m]));
    472 			goto top;
    473 		}
    474 		if ((fp = fopen(input + 1, "w")) == NULL)
    475 			goto top;
    476 		for (unsigned int m = 0; m < nmoves; m++) {
    477 			fprintf(fp, "%s", stoc(movelog[m]));
    478 			if (++m < nmoves)
    479 				fprintf(fp, " %s\n", stoc(movelog[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 = (int)(sp->s_frame[d1] - frames) * 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 += (int)(sp->s_frame[d2] - frames);
    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