]> ncurses.scripts.mit.edu Git - ncurses.git/blob - test/bs.c
ncurses 6.0 - patch 20171125
[ncurses.git] / test / bs.c
1 /****************************************************************************
2  * Copyright (c) 1998-2016,2017 Free Software Foundation, Inc.              *
3  *                                                                          *
4  * Permission is hereby granted, free of charge, to any person obtaining a  *
5  * copy of this software and associated documentation files (the            *
6  * "Software"), to deal in the Software without restriction, including      *
7  * without limitation the rights to use, copy, modify, merge, publish,      *
8  * distribute, distribute with modifications, sublicense, and/or sell       *
9  * copies of the Software, and to permit persons to whom the Software is    *
10  * furnished to do so, subject to the following conditions:                 *
11  *                                                                          *
12  * The above copyright notice and this permission notice shall be included  *
13  * in all copies or substantial portions of the Software.                   *
14  *                                                                          *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
16  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
17  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
18  * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
19  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
20  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
21  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
22  *                                                                          *
23  * Except as contained in this notice, the name(s) of the above copyright   *
24  * holders shall not be used in advertising or otherwise to promote the     *
25  * sale, use or other dealings in this Software without prior written       *
26  * authorization.                                                           *
27  ****************************************************************************/
28 /* 
29  * bs.c - original author: Bruce Holloway
30  *              salvo option by: Chuck A DeGaul
31  * with improved user interface, autoconfiguration and code cleanup
32  *              by Eric S. Raymond <esr@snark.thyrsus.com>
33  * v1.2 with color support and minor portability fixes, November 1990
34  * v2.0 featuring strict ANSI/POSIX conformance, November 1993.
35  * v2.1 with ncurses mouse support, September 1995
36  *
37  * $Id: bs.c,v 1.71 2017/10/18 23:03:07 tom Exp $
38  */
39
40 #include <test.priv.h>
41
42 #include <time.h>
43
44 #ifndef SIGIOT
45 #define SIGIOT SIGABRT
46 #endif
47
48 static int getcoord(int);
49
50 /*
51  * Constants for tuning the random-fire algorithm. It prefers moves that
52  * diagonal-stripe the board with a stripe separation of srchstep. If
53  * no such preferred moves are found, srchstep is decremented.
54  */
55 #define BEGINSTEP       3       /* initial value of srchstep */
56
57 /* miscellaneous constants */
58 #define SHIPTYPES       5
59 #define OTHER           (1-turn)
60 #define PLAYER          0
61 #define COMPUTER        1
62 #define MARK_HIT        'H'
63 #define MARK_MISS       'o'
64 #define CTRLC           '\003'  /* used as terminate command */
65 #define FF              '\014'  /* used as redraw command */
66
67 #define is_QUIT(c) ((c) == CTRLC || (c) == QUIT)
68
69 /* coordinate handling */
70 #define BWIDTH          10
71 #define BDEPTH          10
72
73 /* display symbols */
74 #define SHOWHIT         '*'
75 #define SHOWSPLASH      ' '
76 #define IS_SHIP(c)      (isupper(UChar(c)) ? TRUE : FALSE)
77
78 /* how to position us on player board */
79 #define PYBASE  3
80 #define PXBASE  3
81 #define PY(y)   (PYBASE + (y))
82 #define PX(x)   (PXBASE + (x)*3)
83 #define pgoto(y, x)     (void)move(PY(y), PX(x))
84
85 /* how to position us on cpu board */
86 #define CYBASE  3
87 #define CXBASE  48
88 #define CY(y)   (CYBASE + (y))
89 #define CX(x)   (CXBASE + (x)*3)
90 #define CYINV(y)        ((y) - CYBASE)
91 #define CXINV(x)        (((x) - CXBASE) / 3)
92 #define cgoto(y, x)     (void)move(CY(y), CX(x))
93
94 #define ONBOARD(x, y)   (x >= 0 && x < BWIDTH && y >= 0 && y < BDEPTH)
95
96 /* other board locations */
97 #define COLWIDTH        80
98 #define PROMPTLINE      21      /* prompt line */
99 #define SYBASE          CYBASE + BDEPTH + 3     /* move key diagram */
100 #define SXBASE          63
101 #define MYBASE          SYBASE - 1      /* diagram caption */
102 #define MXBASE          64
103 #define HYBASE          SYBASE - 1      /* help area */
104 #define HXBASE          0
105
106 /* this will need to be changed if BWIDTH changes */
107 static char numbers[] = "   0  1  2  3  4  5  6  7  8  9";
108
109 static char carrier[] = "Aircraft Carrier";
110 static char battle[] = "Battleship";
111 static char sub[] = "Submarine";
112 static char destroy[] = "Destroyer";
113 static char ptboat[] = "PT Boat";
114
115 static char *your_name;
116 static char dftname[] = "stranger";
117
118 /* direction constants */
119 #define E       0
120 #define SE      1
121 #define S       2
122 #define SW      3
123 #define W       4
124 #define NW      5
125 #define N       6
126 #define NE      7
127 static int xincr[8] =
128 {1, 1, 0, -1, -1, -1, 0, 1};
129 static int yincr[8] =
130 {0, 1, 1, 1, 0, -1, -1, -1};
131
132 /* current ship position and direction */
133 static int curx = (BWIDTH / 2);
134 static int cury = (BDEPTH / 2);
135
136 typedef struct {
137     char *name;                 /* name of the ship type */
138     int hits;                   /* how many times has this ship been hit? */
139     char symbol;                /* symbol for game purposes */
140     int length;                 /* length of ship */
141     int x, y;                   /* coordinates of ship start point */
142     int dir;                    /* direction of `bow' */
143     bool placed;                /* has it been placed on the board? */
144 } ship_t;
145
146 static bool checkplace(int b, ship_t * ss, int vis);
147
148 #define SHIPIT(name, symbol, length) { name, 0, symbol, length, 0,0, 0, FALSE }
149
150 /* "ply=player", "cpu=computer" */
151 static ship_t plyship[SHIPTYPES] =
152 {
153     SHIPIT(carrier, 'A', 5),
154     SHIPIT(battle, 'B', 4),
155     SHIPIT(destroy, 'D', 3),
156     SHIPIT(sub, 'S', 3),
157     SHIPIT(ptboat, 'P', 2),
158 };
159
160 static ship_t cpuship[SHIPTYPES] =
161 {
162     SHIPIT(carrier, 'A', 5),
163     SHIPIT(battle, 'B', 4),
164     SHIPIT(destroy, 'D', 3),
165     SHIPIT(sub, 'S', 3),
166     SHIPIT(ptboat, 'P', 2),
167 };
168
169 /* "Hits" board, and main board. */
170 static char hits[2][BWIDTH][BDEPTH];
171 static char board[2][BWIDTH][BDEPTH];
172
173 static int turn;                /* 0=player, 1=computer */
174 static int plywon = 0, cpuwon = 0;      /* How many games has each won? */
175
176 static int salvo, blitz, closepack;
177
178 #define PR      (void)addstr
179
180 static void uninitgame(int sig) GCC_NORETURN;
181
182 static void
183 uninitgame(int sig GCC_UNUSED)
184 /* end the game, either normally or due to signal */
185 {
186     clear();
187     (void) refresh();
188     (void) reset_shell_mode();
189     (void) echo();
190     (void) endwin();
191     free(your_name);
192     ExitProgram(sig ? EXIT_FAILURE : EXIT_SUCCESS);
193 }
194
195 static void
196 announceopts(void)
197 /* announce which game options are enabled */
198 {
199     if (salvo || blitz || closepack) {
200         (void) printw("Playing optional game (");
201         if (salvo)
202             (void) printw("salvo, ");
203         else
204             (void) printw("nosalvo, ");
205         if (blitz)
206             (void) printw("blitz ");
207         else
208             (void) printw("noblitz, ");
209         if (closepack)
210             (void) printw("closepack)");
211         else
212             (void) printw("noclosepack)");
213     } else
214         (void) printw(
215                          "Playing standard game (noblitz, nosalvo, noclosepack)");
216 }
217
218 static void
219 intro(void)
220 {
221     const char *tmpname;
222
223     srand((unsigned) (time(0L) + getpid()));    /* Kick the random number generator */
224
225     InitAndCatch(initscr(), uninitgame);
226
227     if ((tmpname = getlogin()) != 0 &&
228         (your_name = strdup(tmpname)) != 0) {
229         your_name[0] = (char) toupper(UChar(your_name[0]));
230     } else {
231         your_name = strdup(dftname);
232     }
233
234     keypad(stdscr, TRUE);
235     (void) def_prog_mode();
236     (void) nonl();
237     (void) cbreak();
238     (void) noecho();
239
240 #ifdef PENGUIN
241     (void) clear();
242     MvAddStr(4, 29, "Welcome to Battleship!");
243     (void) move(8, 0);
244     PR("                                                  \\\n");
245     PR("                           \\                     \\ \\\n");
246     PR("                          \\ \\                   \\ \\ \\_____________\n");
247     PR("                         \\ \\ \\_____________      \\ \\/            |\n");
248     PR("                          \\ \\/             \\      \\/             |\n");
249     PR("                           \\/               \\_____/              |__\n");
250     PR("           ________________/                                       |\n");
251     PR("           \\  S.S. Penguin                                         |\n");
252     PR("            \\                                                     /\n");
253     PR("             \\___________________________________________________/\n");
254
255     MvAddStr(22, 27, "Hit any key to continue...");
256     (void) refresh();
257     (void) getch();
258 #endif /* PENGUIN */
259
260 #ifdef A_COLOR
261     start_color();
262
263     init_pair(COLOR_BLACK, COLOR_BLACK, COLOR_BLACK);
264     init_pair(COLOR_GREEN, COLOR_GREEN, COLOR_BLACK);
265     init_pair(COLOR_RED, COLOR_RED, COLOR_BLACK);
266     init_pair(COLOR_CYAN, COLOR_CYAN, COLOR_BLACK);
267     init_pair(COLOR_WHITE, COLOR_WHITE, COLOR_BLACK);
268     init_pair(COLOR_MAGENTA, COLOR_MAGENTA, COLOR_BLACK);
269     init_pair(COLOR_BLUE, COLOR_BLUE, COLOR_BLACK);
270     init_pair(COLOR_YELLOW, COLOR_YELLOW, COLOR_BLACK);
271 #endif /* A_COLOR */
272
273 #ifdef NCURSES_MOUSE_VERSION
274     (void) mousemask(BUTTON1_CLICKED, (mmask_t *) NULL);
275 #endif /* NCURSES_MOUSE_VERSION */
276 }
277
278 /* VARARGS1 */
279 static void
280 prompt(int n, NCURSES_CONST char *f, const char *s)
281 /* print a message at the prompt line */
282 {
283     (void) move(PROMPTLINE + n, 0);
284     (void) clrtoeol();
285     (void) printw(f, s);
286     (void) refresh();
287 }
288
289 static void
290 error(NCURSES_CONST char *s)
291 {
292     (void) move(PROMPTLINE + 2, 0);
293     (void) clrtoeol();
294     if (s) {
295         (void) addstr(s);
296         (void) beep();
297     }
298 }
299
300 static void
301 placeship(int b, ship_t * ss, int vis)
302 {
303     int l;
304
305     for (l = 0; l < ss->length; ++l) {
306         int newx = ss->x + l * xincr[ss->dir];
307         int newy = ss->y + l * yincr[ss->dir];
308
309         board[b][newx][newy] = ss->symbol;
310         if (vis) {
311             pgoto(newy, newx);
312             AddCh(ss->symbol);
313         }
314     }
315     ss->hits = 0;
316 }
317
318 static int
319 rnd(int n)
320 {
321     return (((rand() & 0x7FFF) % n));
322 }
323
324 static void
325 randomplace(int b, ship_t * ss)
326 /* generate a valid random ship placement into px,py */
327 {
328
329     do {
330         ss->dir = rnd(2) ? E : S;
331         ss->x = rnd(BWIDTH - (ss->dir == E ? ss->length : 0));
332         ss->y = rnd(BDEPTH - (ss->dir == S ? ss->length : 0));
333     } while
334         (!checkplace(b, ss, FALSE));
335 }
336
337 static void
338 initgame(void)
339 {
340     int i, j, unplaced;
341     ship_t *ss;
342
343     (void) clear();
344     MvAddStr(0, 35, "BATTLESHIPS");
345     (void) move(PROMPTLINE + 2, 0);
346     announceopts();
347
348     memset(board, 0, sizeof(char) * BWIDTH * BDEPTH * 2);
349     memset(hits, 0, sizeof(char) * BWIDTH * BDEPTH * 2);
350     for (i = 0; i < SHIPTYPES; i++) {
351         ss = cpuship + i;
352
353         ss->x =
354             ss->y =
355             ss->dir =
356             ss->hits = 0;
357         ss->placed = FALSE;
358
359         ss = plyship + i;
360
361         ss->x =
362             ss->y =
363             ss->dir =
364             ss->hits = 0;
365         ss->placed = FALSE;
366     }
367
368     /* draw empty boards */
369     MvAddStr(PYBASE - 2, PXBASE + 5, "Main Board");
370     MvAddStr(PYBASE - 1, PXBASE - 3, numbers);
371     for (i = 0; i < BDEPTH; ++i) {
372         MvAddCh(PYBASE + i, PXBASE - 3, (chtype) (i + 'A'));
373 #ifdef A_COLOR
374         if (has_colors())
375             attron(COLOR_PAIR(COLOR_BLUE));
376 #endif /* A_COLOR */
377         AddCh(' ');
378         for (j = 0; j < BWIDTH; j++)
379             (void) addstr(" . ");
380 #ifdef A_COLOR
381         (void) attrset(0);
382 #endif /* A_COLOR */
383         AddCh(' ');
384         AddCh(i + 'A');
385     }
386     MvAddStr(PYBASE + BDEPTH, PXBASE - 3, numbers);
387     MvAddStr(CYBASE - 2, CXBASE + 7, "Hit/Miss Board");
388     MvAddStr(CYBASE - 1, CXBASE - 3, numbers);
389     for (i = 0; i < BDEPTH; ++i) {
390         MvAddCh(CYBASE + i, CXBASE - 3, (chtype) (i + 'A'));
391 #ifdef A_COLOR
392         if (has_colors())
393             attron(COLOR_PAIR(COLOR_BLUE));
394 #endif /* A_COLOR */
395         AddCh(' ');
396         for (j = 0; j < BWIDTH; j++)
397             (void) addstr(" . ");
398 #ifdef A_COLOR
399         (void) attrset(0);
400 #endif /* A_COLOR */
401         AddCh(' ');
402         AddCh(i + 'A');
403     }
404
405     MvAddStr(CYBASE + BDEPTH, CXBASE - 3, numbers);
406
407     MvPrintw(HYBASE, HXBASE,
408              "To position your ships: move the cursor to a spot, then");
409     MvPrintw(HYBASE + 1, HXBASE,
410              "type the first letter of a ship type to select it, then");
411     MvPrintw(HYBASE + 2, HXBASE,
412              "type a direction ([hjkl] or [4862]), indicating how the");
413     MvPrintw(HYBASE + 3, HXBASE,
414              "ship should be pointed. You may also type a ship letter");
415     MvPrintw(HYBASE + 4, HXBASE,
416              "followed by `r' to position it randomly, or type `R' to");
417     MvPrintw(HYBASE + 5, HXBASE,
418              "place all remaining ships randomly.");
419
420     MvAddStr(MYBASE, MXBASE, "Aiming keys:");
421     MvAddStr(SYBASE, SXBASE, "y k u    7 8 9");
422     MvAddStr(SYBASE + 1, SXBASE, " \\|/      \\|/ ");
423     MvAddStr(SYBASE + 2, SXBASE, "h-+-l    4-+-6");
424     MvAddStr(SYBASE + 3, SXBASE, " /|\\      /|\\ ");
425     MvAddStr(SYBASE + 4, SXBASE, "b j n    1 2 3");
426
427     /* have the computer place ships */
428     for (ss = cpuship; ss < cpuship + SHIPTYPES; ss++) {
429         randomplace(COMPUTER, ss);
430         placeship(COMPUTER, ss, FALSE);
431     }
432
433     do {
434         char c, docked[SHIPTYPES + 2], *cp = docked;
435
436         ss = (ship_t *) NULL;
437
438         /* figure which ships still wait to be placed */
439         *cp++ = 'R';
440         for (i = 0; i < SHIPTYPES; i++)
441             if (!plyship[i].placed)
442                 *cp++ = plyship[i].symbol;
443         *cp = '\0';
444
445         /* get a command letter */
446         prompt(1, "Type one of [%s] to pick a ship.", docked + 1);
447         do {
448             c = (char) getcoord(PLAYER);
449         } while
450             (!(strchr) (docked, c));
451
452         if (c == 'R')
453             (void) ungetch('R');
454         else {
455             /* map that into the corresponding symbol */
456             for (ss = plyship; ss < plyship + SHIPTYPES; ss++)
457                 if (ss->symbol == c)
458                     break;
459
460             prompt(1, "Type one of [hjklrR] to place your %s.", ss->name);
461             pgoto(cury, curx);
462         }
463
464         do {
465             c = (char) getch();
466         } while
467             (!(strchr("hjkl8462rR", c) || c == FF || is_QUIT(c)));
468
469         if (is_QUIT(c)) {
470             uninitgame(0);
471         } else if (c == FF) {
472             (void) clearok(stdscr, TRUE);
473             (void) refresh();
474         } else if (ss == 0) {
475             beep();             /* simple to verify, unlikely to happen */
476         } else if (c == 'r') {
477             prompt(1, "Random-placing your %s", ss->name);
478             randomplace(PLAYER, ss);
479             placeship(PLAYER, ss, TRUE);
480             error((char *) NULL);
481             ss->placed = TRUE;
482         } else if (c == 'R') {
483             prompt(1, "Placing the rest of your fleet at random...", "");
484             for (ss = plyship; ss < plyship + SHIPTYPES; ss++)
485                 if (!ss->placed) {
486                     randomplace(PLAYER, ss);
487                     placeship(PLAYER, ss, TRUE);
488                     ss->placed = TRUE;
489                 }
490             error((char *) NULL);
491         } else if (strchr("hjkl8462", c)) {
492             ss->x = curx;
493             ss->y = cury;
494
495             switch (c) {
496             case 'k':
497             case '8':
498                 ss->dir = N;
499                 break;
500             case 'j':
501             case '2':
502                 ss->dir = S;
503                 break;
504             case 'h':
505             case '4':
506                 ss->dir = W;
507                 break;
508             case 'l':
509             case '6':
510                 ss->dir = E;
511                 break;
512             }
513
514             if (checkplace(PLAYER, ss, TRUE)) {
515                 placeship(PLAYER, ss, TRUE);
516                 error((char *) NULL);
517                 ss->placed = TRUE;
518             }
519         }
520
521         for (unplaced = i = 0; i < SHIPTYPES; i++)
522             unplaced += !plyship[i].placed;
523     } while
524         (unplaced);
525
526     turn = rnd(2);
527
528     MvPrintw(HYBASE, HXBASE,
529              "To fire, move the cursor to your chosen aiming point   ");
530     MvPrintw(HYBASE + 1, HXBASE,
531              "and strike any key other than a motion key.            ");
532     MvPrintw(HYBASE + 2, HXBASE,
533              "                                                       ");
534     MvPrintw(HYBASE + 3, HXBASE,
535              "                                                       ");
536     MvPrintw(HYBASE + 4, HXBASE,
537              "                                                       ");
538     MvPrintw(HYBASE + 5, HXBASE,
539              "                                                       ");
540
541     (void) prompt(0, "Press any key to start...", "");
542     (void) getch();
543 }
544
545 static int
546 getcoord(int atcpu)
547 {
548     int ny, nx, c;
549
550     if (atcpu)
551         cgoto(cury, curx);
552     else
553         pgoto(cury, curx);
554     (void) refresh();
555     for (;;) {
556         if (atcpu) {
557             MvPrintw(CYBASE + BDEPTH + 1, CXBASE + 11, "(%d, %c)",
558                      curx, 'A' + cury);
559             cgoto(cury, curx);
560         } else {
561             MvPrintw(PYBASE + BDEPTH + 1, PXBASE + 11, "(%d, %c)",
562                      curx, 'A' + cury);
563             pgoto(cury, curx);
564         }
565
566         switch (c = getch()) {
567         case 'k':
568         case '8':
569         case KEY_UP:
570             ny = cury + BDEPTH - 1;
571             nx = curx;
572             break;
573         case 'j':
574         case '2':
575         case KEY_DOWN:
576             ny = cury + 1;
577             nx = curx;
578             break;
579         case 'h':
580         case '4':
581         case KEY_LEFT:
582             ny = cury;
583             nx = curx + BWIDTH - 1;
584             break;
585         case 'l':
586         case '6':
587         case KEY_RIGHT:
588             ny = cury;
589             nx = curx + 1;
590             break;
591         case 'y':
592         case '7':
593         case KEY_A1:
594             ny = cury + BDEPTH - 1;
595             nx = curx + BWIDTH - 1;
596             break;
597         case 'b':
598         case '1':
599         case KEY_C1:
600             ny = cury + 1;
601             nx = curx + BWIDTH - 1;
602             break;
603         case 'u':
604         case '9':
605         case KEY_A3:
606             ny = cury + BDEPTH - 1;
607             nx = curx + 1;
608             break;
609         case 'n':
610         case '3':
611         case KEY_C3:
612             ny = cury + 1;
613             nx = curx + 1;
614             break;
615         case FF:
616             nx = curx;
617             ny = cury;
618             (void) clearok(stdscr, TRUE);
619             (void) refresh();
620             break;
621 #ifdef NCURSES_MOUSE_VERSION
622         case KEY_MOUSE:
623             {
624                 MEVENT myevent;
625
626                 getmouse(&myevent);
627                 if (atcpu
628                     && myevent.y >= CY(0) && myevent.y <= CY(BDEPTH)
629                     && myevent.x >= CX(0) && myevent.x <= CX(BDEPTH)) {
630                     curx = CXINV(myevent.x);
631                     cury = CYINV(myevent.y);
632                     return (' ');
633                 } else {
634                     beep();
635                     continue;
636                 }
637             }
638             /* no fall through */
639 #endif /* NCURSES_MOUSE_VERSION */
640
641         default:
642             if (atcpu)
643                 MvAddStr(CYBASE + BDEPTH + 1, CXBASE + 11, "      ");
644             else
645                 MvAddStr(PYBASE + BDEPTH + 1, PXBASE + 11, "      ");
646             return (c);
647         }
648
649         curx = nx % BWIDTH;
650         cury = ny % BDEPTH;
651     }
652 }
653
654 static bool
655 collidecheck(int b, int y, int x)
656 /* is this location on the selected zboard adjacent to a ship? */
657 {
658     bool collide;
659
660     /* anything on the square */
661     if ((collide = IS_SHIP(board[b][x][y])) != FALSE)
662         return (collide);
663
664     /* anything on the neighbors */
665     if (!closepack) {
666         int i;
667
668         for (i = 0; i < 8; i++) {
669             int xend, yend;
670
671             yend = y + yincr[i];
672             xend = x + xincr[i];
673             if (ONBOARD(xend, yend)
674                 && IS_SHIP(board[b][xend][yend])) {
675                 collide = TRUE;
676                 break;
677             }
678         }
679     }
680     return (collide);
681 }
682
683 static bool
684 checkplace(int b, ship_t * ss, int vis)
685 {
686     int l, xend, yend;
687
688     /* first, check for board edges */
689     xend = ss->x + (ss->length - 1) * xincr[ss->dir];
690     yend = ss->y + (ss->length - 1) * yincr[ss->dir];
691     if (!ONBOARD(xend, yend)) {
692         if (vis)
693             switch (rnd(3)) {
694             case 0:
695                 error("Ship is hanging from the edge of the world");
696                 break;
697             case 1:
698                 error("Try fitting it on the board");
699                 break;
700             case 2:
701                 error("Figure I won't find it if you put it there?");
702                 break;
703             }
704         return (FALSE);
705     }
706
707     for (l = 0; l < ss->length; ++l) {
708         if (collidecheck(b, ss->y + l * yincr[ss->dir], ss->x + l * xincr[ss->dir])) {
709             if (vis)
710                 switch (rnd(3)) {
711                 case 0:
712                     error("There's already a ship there");
713                     break;
714                 case 1:
715                     error("Collision alert!  Aaaaaagh!");
716                     break;
717                 case 2:
718                     error("Er, Admiral, what about the other ship?");
719                     break;
720                 }
721             return (FALSE);
722         }
723     }
724     return (TRUE);
725 }
726
727 static int
728 awinna(void)
729 {
730     int i, j;
731     ship_t *ss;
732
733     for (i = 0; i < 2; ++i) {
734         ss = (i) ? cpuship : plyship;
735         for (j = 0; j < SHIPTYPES; ++j, ++ss)
736             if (ss->length > ss->hits)
737                 break;
738         if (j == SHIPTYPES)
739             return (OTHER);
740     }
741     return (-1);
742 }
743
744 static ship_t *
745 hitship(int x, int y)
746 /* register a hit on the targeted ship */
747 {
748     ship_t *sb, *ss;
749     char sym;
750     int oldx, oldy;
751
752     getyx(stdscr, oldy, oldx);
753     sb = (turn) ? plyship : cpuship;
754     if ((sym = board[OTHER][x][y]) == 0)
755         return ((ship_t *) NULL);
756     for (ss = sb; ss < sb + SHIPTYPES; ++ss)
757         if (ss->symbol == sym) {
758             if (++ss->hits < ss->length)        /* still afloat? */
759                 return ((ship_t *) NULL);
760             else {              /* sunk! */
761                 int i, j;
762
763                 if (!closepack)
764                     for (j = -1; j <= 1; j++) {
765                         int bx = ss->x + j * xincr[(ss->dir + 2) % 8];
766                         int by = ss->y + j * yincr[(ss->dir + 2) % 8];
767
768                         for (i = -1; i <= ss->length; ++i) {
769                             int x1, y1;
770
771                             x1 = bx + i * xincr[ss->dir];
772                             y1 = by + i * yincr[ss->dir];
773                             if (ONBOARD(x1, y1)) {
774                                 hits[turn][x1][y1] = MARK_MISS;
775                                 if (turn % 2 == PLAYER) {
776                                     cgoto(y1, x1);
777 #ifdef A_COLOR
778                                     if (has_colors())
779                                         attron(COLOR_PAIR(COLOR_GREEN));
780 #endif /* A_COLOR */
781                                     AddCh(MARK_MISS);
782 #ifdef A_COLOR
783                                     (void) attrset(0);
784 #endif /* A_COLOR */
785                                 } else {
786                                     pgoto(y1, x1);
787                                     AddCh(SHOWSPLASH);
788                                 }
789                             }
790                         }
791                     }
792
793                 for (i = 0; i < ss->length; ++i) {
794                     int x1 = ss->x + i * xincr[ss->dir];
795                     int y1 = ss->y + i * yincr[ss->dir];
796
797                     hits[turn][x1][y1] = ss->symbol;
798                     if (turn % 2 == PLAYER) {
799                         cgoto(y1, x1);
800                         AddCh(ss->symbol);
801                     } else {
802                         pgoto(y1, x1);
803 #ifdef A_COLOR
804                         if (has_colors())
805                             attron(COLOR_PAIR(COLOR_RED));
806 #endif /* A_COLOR */
807                         AddCh(SHOWHIT);
808 #ifdef A_COLOR
809                         (void) attrset(0);
810 #endif /* A_COLOR */
811                     }
812                 }
813
814                 (void) move(oldy, oldx);
815                 return (ss);
816             }
817         }
818     (void) move(oldy, oldx);
819     return ((ship_t *) NULL);
820 }
821
822 static bool
823 plyturn(void)
824 {
825     ship_t *ss;
826     bool hit;
827     NCURSES_CONST char *m = NULL;
828
829     prompt(1, "Where do you want to shoot? ", "");
830     for (;;) {
831         (void) getcoord(COMPUTER);
832         if (hits[PLAYER][curx][cury]) {
833             prompt(1, "You shelled this spot already! Try again.", "");
834             beep();
835         } else
836             break;
837     }
838     hit = IS_SHIP(board[COMPUTER][curx][cury]);
839     hits[PLAYER][curx][cury] = (char) (hit ? MARK_HIT : MARK_MISS);
840     cgoto(cury, curx);
841 #ifdef A_COLOR
842     if (has_colors()) {
843         if (hit)
844             attron(COLOR_PAIR(COLOR_RED));
845         else
846             attron(COLOR_PAIR(COLOR_GREEN));
847     }
848 #endif /* A_COLOR */
849     AddCh(hits[PLAYER][curx][cury]);
850 #ifdef A_COLOR
851     (void) attrset(0);
852 #endif /* A_COLOR */
853
854     prompt(1, "You %s.", hit ? "scored a hit" : "missed");
855     if (hit && (ss = hitship(curx, cury))) {
856         switch (rnd(5)) {
857         case 0:
858             m = " You sank my %s!";
859             break;
860         case 1:
861             m = " I have this sinking feeling about my %s....";
862             break;
863         case 2:
864             m = " My %s has gone to Davy Jones's locker!";
865             break;
866         case 3:
867             m = " Glub, glub -- my %s is headed for the bottom!";
868             break;
869         case 4:
870             m = " You'll pick up survivors from my %s, I hope...!";
871             break;
872         }
873         if (m != 0) {
874             (void) printw(m, ss->name);
875         }
876         (void) beep();
877     }
878     return (hit);
879 }
880
881 static int
882 sgetc(const char *s)
883 {
884     const char *s1;
885     int ch;
886
887     (void) refresh();
888     for (;;) {
889         ch = getch();
890         if (islower(ch))
891             ch = toupper(ch);
892         if (is_QUIT(ch))
893             uninitgame(0);
894         for (s1 = s; *s1 && ch != *s1; ++s1)
895             continue;
896         if (*s1) {
897             AddCh(ch);
898             (void) refresh();
899             return (ch);
900         }
901     }
902 }
903
904 static void
905 randomfire(int *px, int *py)
906 /* random-fire routine -- implements simple diagonal-striping strategy */
907 {
908     static int turncount = 0;
909     static int srchstep = BEGINSTEP;
910     static int huntoffs;        /* Offset on search strategy */
911     int ypossible[BWIDTH * BDEPTH], xpossible[BWIDTH * BDEPTH], nposs;
912     int ypreferred[BWIDTH * BDEPTH], xpreferred[BWIDTH * BDEPTH], npref;
913     int x, y, i;
914
915     if (turncount++ == 0)
916         huntoffs = rnd(srchstep);
917
918     /* first, list all possible moves */
919     nposs = npref = 0;
920     for (x = 0; x < BWIDTH; x++)
921         for (y = 0; y < BDEPTH; y++)
922             if (!hits[COMPUTER][x][y]) {
923                 xpossible[nposs] = x;
924                 ypossible[nposs] = y;
925                 nposs++;
926                 if (((x + huntoffs) % srchstep) != (y % srchstep)) {
927                     xpreferred[npref] = x;
928                     ypreferred[npref] = y;
929                     npref++;
930                 }
931             }
932
933     if (npref) {
934         i = rnd(npref);
935
936         *px = xpreferred[i];
937         *py = ypreferred[i];
938     } else if (nposs) {
939         i = rnd(nposs);
940
941         *px = xpossible[i];
942         *py = ypossible[i];
943
944         if (srchstep > 1)
945             --srchstep;
946     } else {
947         error("No moves possible?? Help!");
948         ExitProgram(EXIT_FAILURE);
949         /*NOTREACHED */
950     }
951 }
952
953 #define S_MISS  0
954 #define S_HIT   1
955 #define S_SUNK  -1
956
957 static int
958 cpufire(int x, int y)
959 /* fire away at given location */
960 {
961     bool hit, sunk;
962     ship_t *ss = NULL;
963
964     hit = (bool) board[PLAYER][x][y];
965     hits[COMPUTER][x][y] = (hit ? MARK_HIT : MARK_MISS);
966     MvPrintw(PROMPTLINE, 0,
967              "I shoot at %c%d. I %s!", y + 'A', x, hit ? "hit" :
968              "miss");
969     if ((sunk = (hit && (ss = hitship(x, y)))) != 0)
970         (void) printw(" I've sunk your %s", ss->name);
971     (void) clrtoeol();
972
973     pgoto(y, x);
974 #ifdef A_COLOR
975     if (has_colors()) {
976         if (hit)
977             attron(COLOR_PAIR(COLOR_RED));
978         else
979             attron(COLOR_PAIR(COLOR_GREEN));
980     }
981 #endif /* A_COLOR */
982     AddCh((hit ? SHOWHIT : SHOWSPLASH));
983 #ifdef A_COLOR
984     (void) attrset(0);
985 #endif /* A_COLOR */
986
987     return hit ? (sunk ? S_SUNK : S_HIT) : S_MISS;
988 }
989
990 /*
991  * This code implements a fairly irregular FSM, so please forgive the rampant
992  * unstructuredness below. The five labels are states which need to be held
993  * between computer turns.
994  *
995  * The FSM is not externally reset to RANDOM_FIRE if the player wins. Instead,
996  * the other states check for "impossible" conditions which signify a new
997  * game, then if found transition to RANDOM_FIRE.
998  */
999 static bool
1000 cputurn(void)
1001 {
1002 #define POSSIBLE(x, y)  (ONBOARD(x, y) && !hits[COMPUTER][x][y])
1003 #define RANDOM_FIRE     0
1004 #define RANDOM_HIT      1
1005 #define HUNT_DIRECT     2
1006 #define FIRST_PASS      3
1007 #define REVERSE_JUMP    4
1008 #define SECOND_PASS     5
1009     static int next = RANDOM_FIRE;
1010     static bool used[5];
1011     static ship_t ts;
1012     int navail, x, y, d, n;
1013     int hit = S_MISS;
1014
1015     switch (next) {
1016     case RANDOM_FIRE:           /* last shot was random and missed */
1017       refire:
1018         randomfire(&x, &y);
1019         if (!(hit = cpufire(x, y)))
1020             next = RANDOM_FIRE;
1021         else {
1022             ts.x = x;
1023             ts.y = y;
1024             ts.hits = 1;
1025             next = (hit == S_SUNK) ? RANDOM_FIRE : RANDOM_HIT;
1026         }
1027         break;
1028
1029     case RANDOM_HIT:            /* last shot was random and hit */
1030         used[E / 2] = used[S / 2] = used[W / 2] = used[N / 2] = FALSE;
1031         /* FALLTHROUGH */
1032
1033     case HUNT_DIRECT:           /* last shot hit, we're looking for ship's long axis */
1034         for (d = navail = 0; d < 4; d++) {
1035             x = ts.x + xincr[d * 2];
1036             y = ts.y + yincr[d * 2];
1037             if (!used[d] && POSSIBLE(x, y))
1038                 navail++;
1039             else
1040                 used[d] = TRUE;
1041         }
1042         if (navail == 0)        /* no valid places for shots adjacent... */
1043             goto refire;        /* ...so we must random-fire */
1044         else {
1045             n = rnd(navail) + 1;
1046             for (d = 0; d < 4 && used[d]; d++) ;
1047             /* used[d] is first that == 0 */
1048             for (; n > 1; n--)
1049                 while (d < 4 && used[++d]) ;
1050             /* used[d] is next that == 0 */
1051
1052             assert(d < 4);
1053             assert(used[d] == FALSE);
1054
1055             used[d] = TRUE;
1056             x = ts.x + xincr[d * 2];
1057             y = ts.y + yincr[d * 2];
1058
1059             assert(POSSIBLE(x, y));
1060
1061             if (!(hit = cpufire(x, y)))
1062                 next = HUNT_DIRECT;
1063             else {
1064                 ts.x = x;
1065                 ts.y = y;
1066                 ts.dir = d * 2;
1067                 ts.hits++;
1068                 next = (hit == S_SUNK) ? RANDOM_FIRE : FIRST_PASS;
1069             }
1070         }
1071         break;
1072
1073     case FIRST_PASS:            /* we have a start and a direction now */
1074         x = ts.x + xincr[ts.dir];
1075         y = ts.y + yincr[ts.dir];
1076         if (POSSIBLE(x, y) && (hit = cpufire(x, y))) {
1077             ts.x = x;
1078             ts.y = y;
1079             ts.hits++;
1080             next = (hit == S_SUNK) ? RANDOM_FIRE : FIRST_PASS;
1081         } else
1082             next = REVERSE_JUMP;
1083         break;
1084
1085     case REVERSE_JUMP:          /* nail down the ship's other end */
1086         d = (ts.dir + 4) % 8;
1087         x = ts.x + ts.hits * xincr[d];
1088         y = ts.y + ts.hits * yincr[d];
1089         if (POSSIBLE(x, y) && (hit = cpufire(x, y))) {
1090             ts.x = x;
1091             ts.y = y;
1092             ts.dir = d;
1093             ts.hits++;
1094             next = (hit == S_SUNK) ? RANDOM_FIRE : SECOND_PASS;
1095         } else
1096             next = RANDOM_FIRE;
1097         break;
1098
1099     case SECOND_PASS:           /* continue shooting after reversing */
1100         x = ts.x + xincr[ts.dir];
1101         y = ts.y + yincr[ts.dir];
1102         if (POSSIBLE(x, y) && (hit = cpufire(x, y))) {
1103             ts.x = x;
1104             ts.y = y;
1105             ts.hits++;
1106             next = (hit == S_SUNK) ? RANDOM_FIRE : SECOND_PASS;
1107             break;
1108         } else
1109             next = RANDOM_FIRE;
1110         break;
1111     }
1112
1113     /* pause between shots in salvo */
1114     if (salvo) {
1115         (void) refresh();
1116         (void) sleep(1);
1117     }
1118 #ifdef DEBUG
1119     MvPrintw(PROMPTLINE + 2, 0,
1120              "New state %d, x=%d, y=%d, d=%d",
1121              next, x, y, d);
1122 #endif /* DEBUG */
1123     return ((hit) ? TRUE : FALSE);
1124 }
1125
1126 static int
1127 playagain(void)
1128 {
1129     int j;
1130     ship_t *ss;
1131
1132     for (ss = cpuship; ss < cpuship + SHIPTYPES; ss++)
1133         for (j = 0; j < ss->length; j++) {
1134             cgoto(ss->y + j * yincr[ss->dir], ss->x + j * xincr[ss->dir]);
1135             AddCh(ss->symbol);
1136         }
1137
1138     if (awinna())
1139         ++cpuwon;
1140     else
1141         ++plywon;
1142     j = 18 + (int) strlen(your_name);
1143     if (plywon >= 10)
1144         ++j;
1145     if (cpuwon >= 10)
1146         ++j;
1147     MvPrintw(1, (COLWIDTH - j) / 2,
1148              "%s: %d     Computer: %d", your_name, plywon, cpuwon);
1149
1150     prompt(2, (awinna())? "Want to be humiliated again, %s [yn]? "
1151            : "Going to give me a chance for revenge, %s [yn]? ", your_name);
1152     return (sgetc("YN") == 'Y');
1153 }
1154
1155 static void
1156 do_options(int c, char *op[])
1157 {
1158     register int i;
1159
1160     if (c > 1) {
1161         for (i = 1; i < c; i++) {
1162             switch (op[i][0]) {
1163             default:
1164             case '?':
1165                 (void) fprintf(stderr, "Usage: bs [-s | -b] [-c]\n");
1166                 (void) fprintf(stderr, "\tWhere the options are:\n");
1167                 (void) fprintf(stderr, "\t-s : play a salvo game\n");
1168                 (void) fprintf(stderr, "\t-b : play a blitz game\n");
1169                 (void) fprintf(stderr, "\t-c : ships may be adjacent\n");
1170                 ExitProgram(EXIT_FAILURE);
1171                 break;
1172             case '-':
1173                 switch (op[i][1]) {
1174                 case 'b':
1175                     blitz = 1;
1176                     if (salvo == 1) {
1177                         (void) fprintf(stderr,
1178                                        "Bad Arg: -b and -s are mutually exclusive\n");
1179                         ExitProgram(EXIT_FAILURE);
1180                     }
1181                     break;
1182                 case 's':
1183                     salvo = 1;
1184                     if (blitz == 1) {
1185                         (void) fprintf(stderr,
1186                                        "Bad Arg: -s and -b are mutually exclusive\n");
1187                         ExitProgram(EXIT_FAILURE);
1188                     }
1189                     break;
1190                 case 'c':
1191                     closepack = 1;
1192                     break;
1193                 default:
1194                     (void) fprintf(stderr,
1195                                    "Bad arg: type \"%s ?\" for usage message\n",
1196                                    op[0]);
1197                     ExitProgram(EXIT_FAILURE);
1198                 }
1199             }
1200         }
1201     }
1202 }
1203
1204 static int
1205 scount(int who)
1206 {
1207     register int i, shots;
1208     register ship_t *sp;
1209
1210     if (who)
1211         sp = cpuship;           /* count cpu shots */
1212     else
1213         sp = plyship;           /* count player shots */
1214
1215     for (i = 0, shots = 0; i < SHIPTYPES; i++, sp++) {
1216         if (sp->hits >= sp->length)
1217             continue;           /* dead ship */
1218         else
1219             shots++;
1220     }
1221     return (shots);
1222 }
1223
1224 int
1225 main(int argc, char *argv[])
1226 {
1227     setlocale(LC_ALL, "");
1228
1229     do_options(argc, argv);
1230
1231     intro();
1232     do {
1233         initgame();
1234         while (awinna() == -1) {
1235             if (!blitz) {
1236                 if (!salvo) {
1237                     if (turn)
1238                         (void) cputurn();
1239                     else
1240                         (void) plyturn();
1241                 } else {
1242                     register int i;
1243
1244                     i = scount(turn);
1245                     while (i--) {
1246                         if (turn) {
1247                             if (cputurn() && awinna() != -1)
1248                                 i = 0;
1249                         } else {
1250                             if (plyturn() && awinna() != -1)
1251                                 i = 0;
1252                         }
1253                     }
1254                 }
1255             } else
1256                 while ((turn ? cputurn() : plyturn()) && awinna() == -1)
1257                     continue;
1258             turn = OTHER;
1259         }
1260     } while
1261         (playagain());
1262     uninitgame(0);
1263     /*NOTREACHED */
1264 }
1265
1266 /* bs.c ends here */