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