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