Home | History | Annotate | Line # | Download | only in gomoku
main.c revision 1.54
      1 /*	$NetBSD: main.c,v 1.54 2022/05/22 08:31:12 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.54 2022/05/22 08:31:12 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 bool	interactive = true;	/* true if interactive */
     61 int	debug;			/* > 0 if debugging */
     62 static int test;		/* both moves come from 1: input, 2: computer */
     63 static char *prog;		/* name of program */
     64 static char user[LOGIN_NAME_MAX]; /* name of player */
     65 static FILE *debugfp;		/* file for debug output */
     66 static FILE *inputfp;		/* file for debug input */
     67 
     68 const char	pdir[4]		= "-\\|/";
     69 
     70 struct	spotstr	board[BAREA];		/* info for board */
     71 struct	combostr frames[FAREA];		/* storage for all frames */
     72 struct	combostr *sortframes[2];	/* sorted list of non-empty frames */
     73 u_char	overlap[FAREA * FAREA];		/* true if frame [a][b] overlap */
     74 short	intersect[FAREA * FAREA];	/* frame [a][b] intersection */
     75 int	movelog[BSZ * BSZ];		/* log of all the moves */
     76 int	movenum;			/* current move number */
     77 const char	*plyr[2];		/* who's who */
     78 
     79 static int readinput(FILE *);
     80 static void misclog(const char *, ...) __printflike(1, 2);
     81 static void quit(void) __dead;
     82 #if !defined(DEBUG)
     83 static void quitsig(int) __dead;
     84 #endif
     85 
     86 static void
     87 warn_if_exists(const char *fname)
     88 {
     89 	struct stat st;
     90 
     91 	if (lstat(fname, &st) == 0) {
     92 		int x, y;
     93 		getyx(stdscr, y, x);
     94 		addstr("  (already exists)");
     95 		move(y, x);
     96 	} else
     97 		clrtoeol();
     98 }
     99 
    100 static void
    101 save_game(void)
    102 {
    103 	char fname[PATH_MAX];
    104 	FILE *fp;
    105 
    106 	ask("Save file name? ");
    107 	(void)get_line(fname, sizeof(fname), warn_if_exists);
    108 	if ((fp = fopen(fname, "w")) == NULL) {
    109 		misclog("cannot create save file");
    110 		return;
    111 	}
    112 	for (int i = 0; i < movenum - 1; i++)
    113 		fprintf(fp, "%s\n", stoc(movelog[i]));
    114 	fclose(fp);
    115 }
    116 
    117 static void
    118 parse_args(int argc, char **argv)
    119 {
    120 	int ch;
    121 
    122 	prog = strrchr(argv[0], '/');
    123 	prog = prog != NULL ? prog + 1 : argv[0];
    124 
    125 	while ((ch = getopt(argc, argv, "bcdD:u")) != -1) {
    126 		switch (ch) {
    127 		case 'b':	/* background */
    128 			interactive = false;
    129 			break;
    130 		case 'c':	/* testing: computer versus computer */
    131 			test = 2;
    132 			break;
    133 		case 'd':
    134 			debug++;
    135 			break;
    136 		case 'D':	/* log debug output to file */
    137 			if ((debugfp = fopen(optarg, "w")) == NULL)
    138 				err(1, "%s", optarg);
    139 			break;
    140 		case 'u':	/* testing: user versus user */
    141 			test = 1;
    142 			break;
    143 		default:
    144 		usage:
    145 			fprintf(stderr, "usage: %s [-bcdu] [-Dfile] [file]\n",
    146 			    getprogname());
    147 			exit(EXIT_FAILURE);
    148 		}
    149 	}
    150 	argc -= optind;
    151 	argv += optind;
    152 	if (argc > 1)
    153 		goto usage;
    154 	if (argc == 1 && (inputfp = fopen(*argv, "r")) == NULL)
    155 		err(1, "%s", *argv);
    156 }
    157 
    158 static void
    159 set_input_sources(enum input_source *input, int color)
    160 {
    161 	switch (test) {
    162 	case 0:			/* user versus program */
    163 		input[color] = USER;
    164 		input[color != BLACK ? BLACK : WHITE] = PROGRAM;
    165 		break;
    166 
    167 	case 1:			/* user versus user */
    168 		input[BLACK] = USER;
    169 		input[WHITE] = USER;
    170 		break;
    171 
    172 	case 2:			/* program versus program */
    173 		input[BLACK] = PROGRAM;
    174 		input[WHITE] = PROGRAM;
    175 		break;
    176 	}
    177 }
    178 
    179 static int
    180 ask_user_color(void)
    181 {
    182 	int color;
    183 
    184 	mvprintw(BSZ + 3, 0, "Black moves first. ");
    185 	ask("(B)lack or (W)hite? ");
    186 	for (;;) {
    187 		int ch = get_key(NULL);
    188 		if (ch == 'b' || ch == 'B') {
    189 			color = BLACK;
    190 			break;
    191 		}
    192 		if (ch == 'w' || ch == 'W') {
    193 			color = WHITE;
    194 			break;
    195 		}
    196 		if (ch == 'q' || ch == 'Q')
    197 			quit();
    198 
    199 		beep();
    200 		ask("Please choose (B)lack or (W)hite: ");
    201 	}
    202 	move(BSZ + 3, 0);
    203 	clrtoeol();
    204 	return color;
    205 }
    206 
    207 static int
    208 read_move(void)
    209 {
    210 again:
    211 	if (interactive) {
    212 		ask("Select move, (S)ave or (Q)uit.");
    213 		int s = get_coord();
    214 		if (s == SAVE) {
    215 			save_game();
    216 			goto again;
    217 		}
    218 		if (s != RESIGN && board[s].s_occ != EMPTY) {
    219 			beep();
    220 			goto again;
    221 		}
    222 		return s;
    223 	} else {
    224 		char buf[128];
    225 		if (!get_line(buf, sizeof(buf), NULL))
    226 			return RESIGN;
    227 		if (buf[0] == '\0')
    228 			goto again;
    229 		return ctos(buf);
    230 	}
    231 }
    232 
    233 int
    234 main(int argc, char **argv)
    235 {
    236 	char buf[128];
    237 	char *user_name;
    238 	int color, curmove;
    239 	enum input_source input[2];
    240 
    241 	/* Revoke setgid privileges */
    242 	setgid(getgid());
    243 
    244 	setprogname(argv[0]);
    245 
    246 	user_name = getlogin();
    247 	strlcpy(user, user_name != NULL ? user_name : "you", sizeof(user));
    248 
    249 	color = curmove = 0;
    250 
    251 	parse_args(argc, argv);
    252 
    253 	if (debug == 0)
    254 		srandom((unsigned int)time(0));
    255 	if (interactive)
    256 		cursinit();		/* initialize curses */
    257 again:
    258 	bdinit(board);			/* initialize board contents */
    259 
    260 	if (interactive) {
    261 		plyr[BLACK] = plyr[WHITE] = "???";
    262 		bdisp_init();		/* initialize display of board */
    263 #ifdef DEBUG
    264 		signal(SIGINT, whatsup);
    265 #else
    266 		signal(SIGINT, quitsig);
    267 #endif
    268 
    269 		if (inputfp == NULL && test == 0) {
    270 			color = ask_user_color();
    271 		}
    272 	} else {
    273 		setbuf(stdout, 0);
    274 		get_line(buf, sizeof(buf), NULL);
    275 		if (strcmp(buf, "black") == 0)
    276 			color = BLACK;
    277 		else if (strcmp(buf, "white") == 0)
    278 			color = WHITE;
    279 		else {
    280 			panic("Huh?  Expected `black' or `white', got `%s'\n",
    281 			    buf);
    282 		}
    283 	}
    284 
    285 	if (inputfp != NULL) {
    286 		input[BLACK] = INPUTF;
    287 		input[WHITE] = INPUTF;
    288 	} else {
    289 		set_input_sources(input, color);
    290 	}
    291 	if (interactive) {
    292 		plyr[BLACK] = input[BLACK] == USER ? user : prog;
    293 		plyr[WHITE] = input[WHITE] == USER ? user : prog;
    294 		bdwho();
    295 		refresh();
    296 	}
    297 
    298 	int outcome;
    299 	for (color = BLACK; ; color = color != BLACK ? BLACK : WHITE) {
    300 	top:
    301 		switch (input[color]) {
    302 		case INPUTF: /* input comes from a file */
    303 			curmove = readinput(inputfp);
    304 			if (curmove != EOF)
    305 				break;
    306 			set_input_sources(input, color);
    307 			plyr[BLACK] = input[BLACK] == USER ? user : prog;
    308 			plyr[WHITE] = input[WHITE] == USER ? user : prog;
    309 			bdwho();
    310 			refresh();
    311 			goto top;
    312 
    313 		case USER: /* input comes from standard input */
    314 			curmove = read_move();
    315 			break;
    316 
    317 		case PROGRAM: /* input comes from the program */
    318 			if (interactive)
    319 				ask("Thinking...");
    320 			curmove = pickmove(color);
    321 			break;
    322 		}
    323 		if (interactive && curmove != ILLEGAL) {
    324 			misclog("%3d%*s%-6s", movenum,
    325 			    color == BLACK ? 2 : 9, "", stoc(curmove));
    326 		}
    327 		if ((outcome = makemove(color, curmove)) != MOVEOK)
    328 			break;
    329 		if (interactive)
    330 			bdisp();
    331 	}
    332 	if (interactive) {
    333 		move(BSZ + 3, 0);
    334 		switch (outcome) {
    335 		case WIN:
    336 			if (input[color] == PROGRAM)
    337 				addstr("Ha ha, I won");
    338 			else if (input[0] == USER && input[1] == USER)
    339 				addstr("Well, you won (and lost)");
    340 			else
    341 				addstr("Rats! you won");
    342 			break;
    343 		case TIE:
    344 			addstr("Wow! It's a tie");
    345 			break;
    346 		case ILLEGAL:
    347 			addstr("Illegal move");
    348 			break;
    349 		}
    350 		clrtoeol();
    351 		bdisp();
    352 		if (outcome != RESIGN) {
    353 		replay:
    354 			ask("Play again? ");
    355 			int ch = get_key("YyNnQqSs");
    356 			if (ch == 'Y' || ch == 'y')
    357 				goto again;
    358 			if (ch == 'S') {
    359 				save_game();
    360 				goto replay;
    361 			}
    362 		}
    363 	}
    364 	quit();
    365 }
    366 
    367 static int
    368 readinput(FILE *fp)
    369 {
    370 	int c;
    371 	char buf[128];
    372 	size_t pos;
    373 
    374 	pos = 0;
    375 	while ((c = getc(fp)) != EOF && c != '\n' && pos < sizeof(buf) - 1)
    376 		buf[pos++] = c;
    377 	buf[pos] = '\0';
    378 	return c == EOF ? EOF : ctos(buf);
    379 }
    380 
    381 #ifdef DEBUG
    382 /*
    383  * Handle strange situations.
    384  */
    385 /* ARGSUSED */
    386 void
    387 whatsup(int signum)
    388 {
    389 	int i, n, s1, s2, d1, d2;
    390 	struct spotstr *sp;
    391 	FILE *fp;
    392 	char *str;
    393 	struct elist *ep;
    394 	struct combostr *cbp;
    395 	char input[128];
    396 	char tmp[128];
    397 
    398 	if (!interactive)
    399 		quit();
    400 top:
    401 	ask("debug command: ");
    402 	if (!get_line(input, sizeof(input), NULL))
    403 		quit();
    404 	switch (*input) {
    405 	case '\0':
    406 		goto top;
    407 	case 'q':		/* conservative quit */
    408 		quit();
    409 		/* NOTREACHED */
    410 	case 'd':		/* set debug level */
    411 		debug = input[1] - '0';
    412 		debuglog("Debug set to %d", debug);
    413 		goto top;
    414 	case 'c':
    415 		break;
    416 	case 'b':		/* back up a move */
    417 		if (movenum > 1) {
    418 			movenum--;
    419 			board[movelog[movenum - 1]].s_occ = EMPTY;
    420 			bdisp();
    421 		}
    422 		goto top;
    423 	case 's':		/* suggest a move */
    424 		i = input[1] == 'b' ? BLACK : WHITE;
    425 		debuglog("suggest %c %s", i == BLACK ? 'B' : 'W',
    426 			stoc(pickmove(i)));
    427 		goto top;
    428 	case 'f':		/* go forward a move */
    429 		board[movelog[movenum - 1]].s_occ =
    430 		    (movenum & 1) != 0 ? BLACK : WHITE;
    431 		movenum++;
    432 		bdisp();
    433 		goto top;
    434 	case 'l':		/* print move history */
    435 		if (input[1] == '\0') {
    436 			for (i = 0; i < movenum - 1; i++)
    437 				debuglog("%s", stoc(movelog[i]));
    438 			goto top;
    439 		}
    440 		if ((fp = fopen(input + 1, "w")) == NULL)
    441 			goto top;
    442 		for (i = 0; i < movenum - 1; i++) {
    443 			fprintf(fp, "%s", stoc(movelog[i]));
    444 			if (++i < movenum - 1)
    445 				fprintf(fp, " %s\n", stoc(movelog[i]));
    446 			else
    447 				fputc('\n', fp);
    448 		}
    449 		bdump(fp);
    450 		fclose(fp);
    451 		goto top;
    452 	case 'o':
    453 		/* avoid use w/o initialization on invalid input */
    454 		d1 = s1 = 0;
    455 
    456 		n = 0;
    457 		for (str = input + 1; *str != '\0'; str++)
    458 			if (*str == ',') {
    459 				for (d1 = 0; d1 < 4; d1++)
    460 					if (str[-1] == pdir[d1])
    461 						break;
    462 				str[-1] = '\0';
    463 				sp = &board[s1 = ctos(input + 1)];
    464 				n = (int)(sp->s_frame[d1] - frames) * FAREA;
    465 				*str++ = '\0';
    466 				break;
    467 			}
    468 		sp = &board[s2 = ctos(str)];
    469 		while (*str != '\0')
    470 			str++;
    471 		for (d2 = 0; d2 < 4; d2++)
    472 			if (str[-1] == pdir[d2])
    473 				break;
    474 		n += (int)(sp->s_frame[d2] - frames);
    475 		debuglog("overlap %s%c,%s%c = %x", stoc(s1), pdir[d1],
    476 		    stoc(s2), pdir[d2], overlap[n]);
    477 		goto top;
    478 	case 'p':
    479 		sp = &board[i = ctos(input + 1)];
    480 		debuglog("V %s %x/%d %d %x/%d %d %d %x", stoc(i),
    481 			sp->s_combo[BLACK].s, sp->s_level[BLACK],
    482 			sp->s_nforce[BLACK],
    483 			sp->s_combo[WHITE].s, sp->s_level[WHITE],
    484 			sp->s_nforce[WHITE], sp->s_wval, sp->s_flags);
    485 		debuglog("FB %s %x %x %x %x", stoc(i),
    486 			sp->s_fval[BLACK][0].s, sp->s_fval[BLACK][1].s,
    487 			sp->s_fval[BLACK][2].s, sp->s_fval[BLACK][3].s);
    488 		debuglog("FW %s %x %x %x %x", stoc(i),
    489 			sp->s_fval[WHITE][0].s, sp->s_fval[WHITE][1].s,
    490 			sp->s_fval[WHITE][2].s, sp->s_fval[WHITE][3].s);
    491 		goto top;
    492 	case 'e':	/* e {b|w} [0-9] spot */
    493 		str = input + 1;
    494 		if (*str >= '0' && *str <= '9')
    495 			n = *str++ - '0';
    496 		else
    497 			n = 0;
    498 		sp = &board[i = ctos(str)];
    499 		for (ep = sp->s_empty; ep != NULL; ep = ep->e_next) {
    500 			cbp = ep->e_combo;
    501 			if (n != 0) {
    502 				if (cbp->c_nframes > n)
    503 					continue;
    504 				if (cbp->c_nframes != n)
    505 					break;
    506 			}
    507 			printcombo(cbp, tmp, sizeof(tmp));
    508 			debuglog("%s", tmp);
    509 		}
    510 		goto top;
    511 	default:
    512 		debuglog("Options are:");
    513 		debuglog("q    - quit");
    514 		debuglog("c    - continue");
    515 		debuglog("d#   - set debug level to #");
    516 		debuglog("p#   - print values at #");
    517 		goto top;
    518 	}
    519 }
    520 #endif /* DEBUG */
    521 
    522 /*
    523  * Display debug info.
    524  */
    525 void
    526 debuglog(const char *fmt, ...)
    527 {
    528 	va_list ap;
    529 	char buf[128];
    530 
    531 	va_start(ap, fmt);
    532 	vsnprintf(buf, sizeof(buf), fmt, ap);
    533 	va_end(ap);
    534 
    535 	if (debugfp != NULL)
    536 		fprintf(debugfp, "%s\n", buf);
    537 	if (interactive)
    538 		dislog(buf);
    539 	else
    540 		fprintf(stderr, "%s\n", buf);
    541 }
    542 
    543 static void
    544 misclog(const char *fmt, ...)
    545 {
    546 	va_list ap;
    547 	char buf[128];
    548 
    549 	va_start(ap, fmt);
    550 	vsnprintf(buf, sizeof(buf), fmt, ap);
    551 	va_end(ap);
    552 
    553 	if (debugfp != NULL)
    554 		fprintf(debugfp, "%s\n", buf);
    555 	if (interactive)
    556 		dislog(buf);
    557 	else
    558 		printf("%s\n", buf);
    559 }
    560 
    561 static void
    562 quit(void)
    563 {
    564 	if (interactive) {
    565 		bdisp();		/* show final board */
    566 		cursfini();
    567 	}
    568 	exit(0);
    569 }
    570 
    571 #if !defined(DEBUG)
    572 static void
    573 quitsig(int dummy __unused)
    574 {
    575 	quit();
    576 }
    577 #endif
    578 
    579 /*
    580  * Die gracefully.
    581  */
    582 void
    583 panic(const char *fmt, ...)
    584 {
    585 	va_list ap;
    586 
    587 	if (interactive) {
    588 		bdisp();
    589 		cursfini();
    590 	}
    591 
    592 	fprintf(stderr, "%s: ", prog);
    593 	va_start(ap, fmt);
    594 	vfprintf(stderr, fmt, ap);
    595 	va_end(ap);
    596 	fprintf(stderr, "\n");
    597 
    598 	fputs("I resign\n", stdout);
    599 	exit(1);
    600 }
    601