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