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