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