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