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