Home | History | Annotate | Line # | Download | only in gomoku
main.c revision 1.59
      1 /*	$NetBSD: main.c,v 1.59 2022/05/27 19:59:56 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.59 2022/05/27 19:59:56 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];		/* true if frame [a][b] overlap */
     80 short	intersect[FAREA * FAREA];	/* frame [a][b] intersection */
     81 int	movelog[BSZ * BSZ];		/* log of all played moves */
     82 unsigned int nmoves;			/* number of played moves */
     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 < nmoves; i++)
    119 		fprintf(fp, "%s\n", stoc(movelog[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 int
    226 read_move(void)
    227 {
    228 again:
    229 	if (interactive) {
    230 		ask("Select move, (S)ave or (Q)uit.");
    231 		int 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 != EOF)
    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 		    nmoves + 1, color == BLACK ? 2 : 9, "", stoc(curmove));
    316 	}
    317 
    318 	if ((outcome = makemove(color, curmove)) != MOVEOK)
    319 		return (struct outcome){ outcome, color };
    320 
    321 	if (interactive)
    322 		bdisp();
    323 	color = color != BLACK ? BLACK : WHITE;
    324 	goto again;
    325 }
    326 
    327 int
    328 main(int argc, char **argv)
    329 {
    330 	char *user_name;
    331 	int color;
    332 	enum input_source input[2];
    333 
    334 	/* Revoke setgid privileges */
    335 	setgid(getgid());
    336 
    337 	setprogname(argv[0]);
    338 
    339 	user_name = getlogin();
    340 	strlcpy(user, user_name != NULL ? user_name : "you", sizeof(user));
    341 
    342 	color = BLACK;
    343 
    344 	parse_args(argc, argv);
    345 
    346 	if (debug == 0)
    347 		srandom((unsigned int)time(0));
    348 	if (interactive)
    349 		cursinit();		/* initialize curses */
    350 again:
    351 	bdinit(board);			/* initialize board contents */
    352 
    353 	if (interactive) {
    354 		bdisp_init();		/* initialize display of board */
    355 #ifdef DEBUG
    356 		signal(SIGINT, whatsup);
    357 #else
    358 		signal(SIGINT, quitsig);
    359 #endif
    360 
    361 		if (inputfp == NULL && test == NORMAL_PLAY)
    362 			color = ask_user_color();
    363 	} else {
    364 		setbuf(stdout, NULL);
    365 		color = read_color();
    366 	}
    367 
    368 	if (inputfp != NULL) {
    369 		input[BLACK] = INPUTF;
    370 		input[WHITE] = INPUTF;
    371 	} else {
    372 		set_input_sources(input, color);
    373 	}
    374 	if (interactive) {
    375 		plyr[BLACK] = input[BLACK] == USER ? user : prog;
    376 		plyr[WHITE] = input[WHITE] == USER ? user : prog;
    377 		bdwho();
    378 		refresh();
    379 	}
    380 
    381 	struct outcome outcome = main_game_loop(input);
    382 
    383 	if (interactive) {
    384 		declare_winner(outcome.result, input, outcome.winner);
    385 		if (outcome.result != RESIGN) {
    386 		replay:
    387 			ask("Play again? ");
    388 			int ch = get_key("YyNnQqSs");
    389 			if (ch == 'Y' || ch == 'y')
    390 				goto again;
    391 			if (ch == 'S') {
    392 				save_game();
    393 				goto replay;
    394 			}
    395 		}
    396 	}
    397 	quit();
    398 }
    399 
    400 static int
    401 readinput(FILE *fp)
    402 {
    403 	int c;
    404 	char buf[128];
    405 	size_t pos;
    406 
    407 	pos = 0;
    408 	while ((c = getc(fp)) != EOF && c != '\n' && pos < sizeof(buf) - 1)
    409 		buf[pos++] = c;
    410 	buf[pos] = '\0';
    411 	return c == EOF ? EOF : ctos(buf);
    412 }
    413 
    414 #ifdef DEBUG
    415 /*
    416  * Handle strange situations.
    417  */
    418 /* ARGSUSED */
    419 void
    420 whatsup(int signum)
    421 {
    422 	int i, n, s1, s2, d1, d2;
    423 	struct spotstr *sp;
    424 	FILE *fp;
    425 	char *str;
    426 	struct elist *ep;
    427 	struct combostr *cbp;
    428 	char input[128];
    429 	char tmp[128];
    430 
    431 	if (!interactive)
    432 		quit();
    433 top:
    434 	ask("debug command: ");
    435 	if (!get_line(input, sizeof(input), NULL))
    436 		quit();
    437 	switch (*input) {
    438 	case '\0':
    439 		goto top;
    440 	case 'q':		/* conservative quit */
    441 		quit();
    442 		/* NOTREACHED */
    443 	case 'd':		/* set debug level */
    444 		debug = input[1] - '0';
    445 		debuglog("Debug set to %d", debug);
    446 		goto top;
    447 	case 'c':
    448 		break;
    449 	case 'b':		/* back up a move */
    450 		if (nmoves > 0) {
    451 			nmoves--;
    452 			board[movelog[nmoves]].s_occ = EMPTY;
    453 			bdisp();
    454 		}
    455 		goto top;
    456 	case 's':		/* suggest a move */
    457 		i = input[1] == 'b' ? BLACK : WHITE;
    458 		debuglog("suggest %c %s", i == BLACK ? 'B' : 'W',
    459 			stoc(pickmove(i)));
    460 		goto top;
    461 	case 'f':		/* go forward a move */
    462 		board[movelog[nmoves]].s_occ =
    463 		    nmoves % 2 == 0 ? BLACK : WHITE;
    464 		nmoves++;
    465 		bdisp();
    466 		goto top;
    467 	case 'l':		/* print move history */
    468 		if (input[1] == '\0') {
    469 			for (unsigned int m = 0; m < nmoves; m++)
    470 				debuglog("%s", stoc(movelog[m]));
    471 			goto top;
    472 		}
    473 		if ((fp = fopen(input + 1, "w")) == NULL)
    474 			goto top;
    475 		for (unsigned int m = 0; m < nmoves; m++) {
    476 			fprintf(fp, "%s", stoc(movelog[m]));
    477 			if (++m < nmoves)
    478 				fprintf(fp, " %s\n", stoc(movelog[m]));
    479 			else
    480 				fputc('\n', fp);
    481 		}
    482 		bdump(fp);
    483 		fclose(fp);
    484 		goto top;
    485 	case 'o':
    486 		/* avoid use w/o initialization on invalid input */
    487 		d1 = s1 = 0;
    488 
    489 		n = 0;
    490 		for (str = input + 1; *str != '\0'; str++)
    491 			if (*str == ',') {
    492 				for (d1 = 0; d1 < 4; d1++)
    493 					if (str[-1] == pdir[d1])
    494 						break;
    495 				str[-1] = '\0';
    496 				sp = &board[s1 = ctos(input + 1)];
    497 				n = (int)(sp->s_frame[d1] - frames) * FAREA;
    498 				*str++ = '\0';
    499 				break;
    500 			}
    501 		sp = &board[s2 = ctos(str)];
    502 		while (*str != '\0')
    503 			str++;
    504 		for (d2 = 0; d2 < 4; d2++)
    505 			if (str[-1] == pdir[d2])
    506 				break;
    507 		n += (int)(sp->s_frame[d2] - frames);
    508 		debuglog("overlap %s%c,%s%c = %x", stoc(s1), pdir[d1],
    509 		    stoc(s2), pdir[d2], overlap[n]);
    510 		goto top;
    511 	case 'p':
    512 		sp = &board[i = ctos(input + 1)];
    513 		debuglog("V %s %x/%d %d %x/%d %d %d %x", stoc(i),
    514 			sp->s_combo[BLACK].s, sp->s_level[BLACK],
    515 			sp->s_nforce[BLACK],
    516 			sp->s_combo[WHITE].s, sp->s_level[WHITE],
    517 			sp->s_nforce[WHITE], sp->s_wval, sp->s_flags);
    518 		debuglog("FB %s %x %x %x %x", stoc(i),
    519 			sp->s_fval[BLACK][0].s, sp->s_fval[BLACK][1].s,
    520 			sp->s_fval[BLACK][2].s, sp->s_fval[BLACK][3].s);
    521 		debuglog("FW %s %x %x %x %x", stoc(i),
    522 			sp->s_fval[WHITE][0].s, sp->s_fval[WHITE][1].s,
    523 			sp->s_fval[WHITE][2].s, sp->s_fval[WHITE][3].s);
    524 		goto top;
    525 	case 'e':	/* e {b|w} [0-9] spot */
    526 		str = input + 1;
    527 		if (*str >= '0' && *str <= '9')
    528 			n = *str++ - '0';
    529 		else
    530 			n = 0;
    531 		sp = &board[i = ctos(str)];
    532 		for (ep = sp->s_empty; ep != NULL; ep = ep->e_next) {
    533 			cbp = ep->e_combo;
    534 			if (n != 0) {
    535 				if (cbp->c_nframes > n)
    536 					continue;
    537 				if (cbp->c_nframes != n)
    538 					break;
    539 			}
    540 			printcombo(cbp, tmp, sizeof(tmp));
    541 			debuglog("%s", tmp);
    542 		}
    543 		goto top;
    544 	default:
    545 		debuglog("Options are:");
    546 		debuglog("q    - quit");
    547 		debuglog("c    - continue");
    548 		debuglog("d#   - set debug level to #");
    549 		debuglog("p#   - print values at #");
    550 		goto top;
    551 	}
    552 }
    553 #endif /* DEBUG */
    554 
    555 /*
    556  * Display debug info.
    557  */
    558 void
    559 debuglog(const char *fmt, ...)
    560 {
    561 	va_list ap;
    562 	char buf[128];
    563 
    564 	va_start(ap, fmt);
    565 	vsnprintf(buf, sizeof(buf), fmt, ap);
    566 	va_end(ap);
    567 
    568 	if (debugfp != NULL)
    569 		fprintf(debugfp, "%s\n", buf);
    570 	if (interactive)
    571 		dislog(buf);
    572 	else
    573 		fprintf(stderr, "%s\n", buf);
    574 }
    575 
    576 static void
    577 misclog(const char *fmt, ...)
    578 {
    579 	va_list ap;
    580 	char buf[128];
    581 
    582 	va_start(ap, fmt);
    583 	vsnprintf(buf, sizeof(buf), fmt, ap);
    584 	va_end(ap);
    585 
    586 	if (debugfp != NULL)
    587 		fprintf(debugfp, "%s\n", buf);
    588 	if (interactive)
    589 		dislog(buf);
    590 	else
    591 		printf("%s\n", buf);
    592 }
    593 
    594 static void
    595 quit(void)
    596 {
    597 	if (interactive) {
    598 		bdisp();		/* show final board */
    599 		cursfini();
    600 	}
    601 	exit(0);
    602 }
    603 
    604 #if !defined(DEBUG)
    605 static void
    606 quitsig(int dummy __unused)
    607 {
    608 	quit();
    609 }
    610 #endif
    611 
    612 /*
    613  * Die gracefully.
    614  */
    615 void
    616 panic(const char *fmt, ...)
    617 {
    618 	va_list ap;
    619 
    620 	if (interactive) {
    621 		bdisp();
    622 		cursfini();
    623 	}
    624 
    625 	fprintf(stderr, "%s: ", prog);
    626 	va_start(ap, fmt);
    627 	vfprintf(stderr, fmt, ap);
    628 	va_end(ap);
    629 	fprintf(stderr, "\n");
    630 
    631 	fputs("I resign\n", stdout);
    632 	exit(1);
    633 }
    634