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