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