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