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