Home | History | Annotate | Line # | Download | only in gomoku
main.c revision 1.53
      1 /*	$NetBSD: main.c,v 1.53 2022/05/22 08:28:10 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.53 2022/05/22 08:28:10 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 read_move(void)
    181 {
    182 again:
    183 	if (interactive) {
    184 		ask("Select move, (S)ave or (Q)uit.");
    185 		int s = get_coord();
    186 		if (s == SAVE) {
    187 			save_game();
    188 			goto again;
    189 		}
    190 		if (s != RESIGN && board[s].s_occ != EMPTY) {
    191 			beep();
    192 			goto again;
    193 		}
    194 		return s;
    195 	} else {
    196 		char buf[128];
    197 		if (!get_line(buf, sizeof(buf), NULL))
    198 			return RESIGN;
    199 		if (buf[0] == '\0')
    200 			goto again;
    201 		return ctos(buf);
    202 	}
    203 }
    204 
    205 int
    206 main(int argc, char **argv)
    207 {
    208 	char buf[128];
    209 	char *user_name;
    210 	int color, curmove;
    211 	enum input_source input[2];
    212 
    213 	/* Revoke setgid privileges */
    214 	setgid(getgid());
    215 
    216 	setprogname(argv[0]);
    217 
    218 	user_name = getlogin();
    219 	strlcpy(user, user_name != NULL ? user_name : "you", sizeof(user));
    220 
    221 	color = curmove = 0;
    222 
    223 	parse_args(argc, argv);
    224 
    225 	if (debug == 0)
    226 		srandom((unsigned int)time(0));
    227 	if (interactive)
    228 		cursinit();		/* initialize curses */
    229 again:
    230 	bdinit(board);			/* initialize board contents */
    231 
    232 	if (interactive) {
    233 		plyr[BLACK] = plyr[WHITE] = "???";
    234 		bdisp_init();		/* initialize display of board */
    235 #ifdef DEBUG
    236 		signal(SIGINT, whatsup);
    237 #else
    238 		signal(SIGINT, quitsig);
    239 #endif
    240 
    241 		if (inputfp == NULL && test == 0) {
    242 			mvprintw(BSZ + 3, 0, "Black moves first. ");
    243 			ask("(B)lack or (W)hite? ");
    244 			for (;;) {
    245 				int ch = get_key(NULL);
    246 				if (ch == 'b' || ch == 'B') {
    247 					color = BLACK;
    248 					break;
    249 				}
    250 				if (ch == 'w' || ch == 'W') {
    251 					color = WHITE;
    252 					break;
    253 				}
    254 				if (ch == 'q' || ch == 'Q') {
    255 					quit();
    256 				}
    257 				beep();
    258 				ask("Please choose (B)lack or (W)hite: ");
    259 			}
    260 			move(BSZ + 3, 0);
    261 			clrtoeol();
    262 		}
    263 	} else {
    264 		setbuf(stdout, 0);
    265 		get_line(buf, sizeof(buf), NULL);
    266 		if (strcmp(buf, "black") == 0)
    267 			color = BLACK;
    268 		else if (strcmp(buf, "white") == 0)
    269 			color = WHITE;
    270 		else {
    271 			panic("Huh?  Expected `black' or `white', got `%s'\n",
    272 			    buf);
    273 		}
    274 	}
    275 
    276 	if (inputfp != NULL) {
    277 		input[BLACK] = INPUTF;
    278 		input[WHITE] = INPUTF;
    279 	} else {
    280 		set_input_sources(input, color);
    281 	}
    282 	if (interactive) {
    283 		plyr[BLACK] = input[BLACK] == USER ? user : prog;
    284 		plyr[WHITE] = input[WHITE] == USER ? user : prog;
    285 		bdwho();
    286 		refresh();
    287 	}
    288 
    289 	int outcome;
    290 	for (color = BLACK; ; color = color != BLACK ? BLACK : WHITE) {
    291 	top:
    292 		switch (input[color]) {
    293 		case INPUTF: /* input comes from a file */
    294 			curmove = readinput(inputfp);
    295 			if (curmove != EOF)
    296 				break;
    297 			set_input_sources(input, color);
    298 			plyr[BLACK] = input[BLACK] == USER ? user : prog;
    299 			plyr[WHITE] = input[WHITE] == USER ? user : prog;
    300 			bdwho();
    301 			refresh();
    302 			goto top;
    303 
    304 		case USER: /* input comes from standard input */
    305 			curmove = read_move();
    306 			break;
    307 
    308 		case PROGRAM: /* input comes from the program */
    309 			if (interactive)
    310 				ask("Thinking...");
    311 			curmove = pickmove(color);
    312 			break;
    313 		}
    314 		if (interactive && curmove != ILLEGAL) {
    315 			misclog("%3d%*s%-6s", movenum,
    316 			    color == BLACK ? 2 : 9, "", stoc(curmove));
    317 		}
    318 		if ((outcome = makemove(color, curmove)) != MOVEOK)
    319 			break;
    320 		if (interactive)
    321 			bdisp();
    322 	}
    323 	if (interactive) {
    324 		move(BSZ + 3, 0);
    325 		switch (outcome) {
    326 		case WIN:
    327 			if (input[color] == PROGRAM)
    328 				addstr("Ha ha, I won");
    329 			else if (input[0] == USER && input[1] == USER)
    330 				addstr("Well, you won (and lost)");
    331 			else
    332 				addstr("Rats! you won");
    333 			break;
    334 		case TIE:
    335 			addstr("Wow! It's a tie");
    336 			break;
    337 		case ILLEGAL:
    338 			addstr("Illegal move");
    339 			break;
    340 		}
    341 		clrtoeol();
    342 		bdisp();
    343 		if (outcome != RESIGN) {
    344 		replay:
    345 			ask("Play again? ");
    346 			int ch = get_key("YyNnQqSs");
    347 			if (ch == 'Y' || ch == 'y')
    348 				goto again;
    349 			if (ch == 'S') {
    350 				save_game();
    351 				goto replay;
    352 			}
    353 		}
    354 	}
    355 	quit();
    356 }
    357 
    358 static int
    359 readinput(FILE *fp)
    360 {
    361 	int c;
    362 	char buf[128];
    363 	size_t pos;
    364 
    365 	pos = 0;
    366 	while ((c = getc(fp)) != EOF && c != '\n' && pos < sizeof(buf) - 1)
    367 		buf[pos++] = c;
    368 	buf[pos] = '\0';
    369 	return c == EOF ? EOF : ctos(buf);
    370 }
    371 
    372 #ifdef DEBUG
    373 /*
    374  * Handle strange situations.
    375  */
    376 /* ARGSUSED */
    377 void
    378 whatsup(int signum)
    379 {
    380 	int i, n, s1, s2, d1, d2;
    381 	struct spotstr *sp;
    382 	FILE *fp;
    383 	char *str;
    384 	struct elist *ep;
    385 	struct combostr *cbp;
    386 	char input[128];
    387 	char tmp[128];
    388 
    389 	if (!interactive)
    390 		quit();
    391 top:
    392 	ask("debug command: ");
    393 	if (!get_line(input, sizeof(input), NULL))
    394 		quit();
    395 	switch (*input) {
    396 	case '\0':
    397 		goto top;
    398 	case 'q':		/* conservative quit */
    399 		quit();
    400 		/* NOTREACHED */
    401 	case 'd':		/* set debug level */
    402 		debug = input[1] - '0';
    403 		debuglog("Debug set to %d", debug);
    404 		goto top;
    405 	case 'c':
    406 		break;
    407 	case 'b':		/* back up a move */
    408 		if (movenum > 1) {
    409 			movenum--;
    410 			board[movelog[movenum - 1]].s_occ = EMPTY;
    411 			bdisp();
    412 		}
    413 		goto top;
    414 	case 's':		/* suggest a move */
    415 		i = input[1] == 'b' ? BLACK : WHITE;
    416 		debuglog("suggest %c %s", i == BLACK ? 'B' : 'W',
    417 			stoc(pickmove(i)));
    418 		goto top;
    419 	case 'f':		/* go forward a move */
    420 		board[movelog[movenum - 1]].s_occ =
    421 		    (movenum & 1) != 0 ? BLACK : WHITE;
    422 		movenum++;
    423 		bdisp();
    424 		goto top;
    425 	case 'l':		/* print move history */
    426 		if (input[1] == '\0') {
    427 			for (i = 0; i < movenum - 1; i++)
    428 				debuglog("%s", stoc(movelog[i]));
    429 			goto top;
    430 		}
    431 		if ((fp = fopen(input + 1, "w")) == NULL)
    432 			goto top;
    433 		for (i = 0; i < movenum - 1; i++) {
    434 			fprintf(fp, "%s", stoc(movelog[i]));
    435 			if (++i < movenum - 1)
    436 				fprintf(fp, " %s\n", stoc(movelog[i]));
    437 			else
    438 				fputc('\n', fp);
    439 		}
    440 		bdump(fp);
    441 		fclose(fp);
    442 		goto top;
    443 	case 'o':
    444 		/* avoid use w/o initialization on invalid input */
    445 		d1 = s1 = 0;
    446 
    447 		n = 0;
    448 		for (str = input + 1; *str != '\0'; str++)
    449 			if (*str == ',') {
    450 				for (d1 = 0; d1 < 4; d1++)
    451 					if (str[-1] == pdir[d1])
    452 						break;
    453 				str[-1] = '\0';
    454 				sp = &board[s1 = ctos(input + 1)];
    455 				n = (int)(sp->s_frame[d1] - frames) * FAREA;
    456 				*str++ = '\0';
    457 				break;
    458 			}
    459 		sp = &board[s2 = ctos(str)];
    460 		while (*str != '\0')
    461 			str++;
    462 		for (d2 = 0; d2 < 4; d2++)
    463 			if (str[-1] == pdir[d2])
    464 				break;
    465 		n += (int)(sp->s_frame[d2] - frames);
    466 		debuglog("overlap %s%c,%s%c = %x", stoc(s1), pdir[d1],
    467 		    stoc(s2), pdir[d2], overlap[n]);
    468 		goto top;
    469 	case 'p':
    470 		sp = &board[i = ctos(input + 1)];
    471 		debuglog("V %s %x/%d %d %x/%d %d %d %x", stoc(i),
    472 			sp->s_combo[BLACK].s, sp->s_level[BLACK],
    473 			sp->s_nforce[BLACK],
    474 			sp->s_combo[WHITE].s, sp->s_level[WHITE],
    475 			sp->s_nforce[WHITE], sp->s_wval, sp->s_flags);
    476 		debuglog("FB %s %x %x %x %x", stoc(i),
    477 			sp->s_fval[BLACK][0].s, sp->s_fval[BLACK][1].s,
    478 			sp->s_fval[BLACK][2].s, sp->s_fval[BLACK][3].s);
    479 		debuglog("FW %s %x %x %x %x", stoc(i),
    480 			sp->s_fval[WHITE][0].s, sp->s_fval[WHITE][1].s,
    481 			sp->s_fval[WHITE][2].s, sp->s_fval[WHITE][3].s);
    482 		goto top;
    483 	case 'e':	/* e {b|w} [0-9] spot */
    484 		str = input + 1;
    485 		if (*str >= '0' && *str <= '9')
    486 			n = *str++ - '0';
    487 		else
    488 			n = 0;
    489 		sp = &board[i = ctos(str)];
    490 		for (ep = sp->s_empty; ep != NULL; ep = ep->e_next) {
    491 			cbp = ep->e_combo;
    492 			if (n != 0) {
    493 				if (cbp->c_nframes > n)
    494 					continue;
    495 				if (cbp->c_nframes != n)
    496 					break;
    497 			}
    498 			printcombo(cbp, tmp, sizeof(tmp));
    499 			debuglog("%s", tmp);
    500 		}
    501 		goto top;
    502 	default:
    503 		debuglog("Options are:");
    504 		debuglog("q    - quit");
    505 		debuglog("c    - continue");
    506 		debuglog("d#   - set debug level to #");
    507 		debuglog("p#   - print values at #");
    508 		goto top;
    509 	}
    510 }
    511 #endif /* DEBUG */
    512 
    513 /*
    514  * Display debug info.
    515  */
    516 void
    517 debuglog(const char *fmt, ...)
    518 {
    519 	va_list ap;
    520 	char buf[128];
    521 
    522 	va_start(ap, fmt);
    523 	vsnprintf(buf, sizeof(buf), fmt, ap);
    524 	va_end(ap);
    525 
    526 	if (debugfp != NULL)
    527 		fprintf(debugfp, "%s\n", buf);
    528 	if (interactive)
    529 		dislog(buf);
    530 	else
    531 		fprintf(stderr, "%s\n", buf);
    532 }
    533 
    534 static void
    535 misclog(const char *fmt, ...)
    536 {
    537 	va_list ap;
    538 	char buf[128];
    539 
    540 	va_start(ap, fmt);
    541 	vsnprintf(buf, sizeof(buf), fmt, ap);
    542 	va_end(ap);
    543 
    544 	if (debugfp != NULL)
    545 		fprintf(debugfp, "%s\n", buf);
    546 	if (interactive)
    547 		dislog(buf);
    548 	else
    549 		printf("%s\n", buf);
    550 }
    551 
    552 static void
    553 quit(void)
    554 {
    555 	if (interactive) {
    556 		bdisp();		/* show final board */
    557 		cursfini();
    558 	}
    559 	exit(0);
    560 }
    561 
    562 #if !defined(DEBUG)
    563 static void
    564 quitsig(int dummy __unused)
    565 {
    566 	quit();
    567 }
    568 #endif
    569 
    570 /*
    571  * Die gracefully.
    572  */
    573 void
    574 panic(const char *fmt, ...)
    575 {
    576 	va_list ap;
    577 
    578 	if (interactive) {
    579 		bdisp();
    580 		cursfini();
    581 	}
    582 
    583 	fprintf(stderr, "%s: ", prog);
    584 	va_start(ap, fmt);
    585 	vfprintf(stderr, fmt, ap);
    586 	va_end(ap);
    587 	fprintf(stderr, "\n");
    588 
    589 	fputs("I resign\n", stdout);
    590 	exit(1);
    591 }
    592