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