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