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