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