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