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