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