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