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.
9 * $FreeBSD: src/games/bs/bs.c,v 1.9 2000/02/21 03:07:31 billf Exp $
10 * $DragonFly: src/games/bs/bs.c,v 1.7 2007/04/18 18:32:12 swildner Exp $
23 * Constants for tuning the random-fire algorithm. It prefers moves that
24 * diagonal-stripe the board with a stripe separation of srchstep. If
25 * no such preferred moves are found, srchstep is decremented.
27 #define BEGINSTEP 3 /* initial value of srchstep */
29 /* miscellaneous constants */
31 #define OTHER (1-turn)
36 #define CTRLC '\003' /* used as terminate command */
37 #define FF '\014' /* used as redraw command */
39 /* coordinate handling */
45 #define SHOWSPLASH ' '
46 #define IS_SHIP(c) isupper(c)
48 /* how to position us on player board */
51 #define PY(y) (PYBASE + (y))
52 #define PX(x) (PXBASE + (x)*3)
53 #define pgoto(y, x) move(PY(y), PX(x))
55 /* how to position us on cpu board */
58 #define CY(y) (CYBASE + (y))
59 #define CX(x) (CXBASE + (x)*3)
60 #define cgoto(y, x) move(CY(y), CX(x))
62 #define ONBOARD(x, y) (x >= 0 && x < BWIDTH && y >= 0 && y < BDEPTH)
64 /* other board locations */
66 #define PROMPTLINE 21 /* prompt line */
67 #define SYBASE CYBASE + BDEPTH + 3 /* move key diagram */
69 #define MYBASE SYBASE - 1 /* diagram caption */
71 #define HYBASE SYBASE - 1 /* help area */
74 /* this will need to be changed if BWIDTH changes */
75 static char numbers[] = " 0 1 2 3 4 5 6 7 8 9";
77 static char carrier[] = "Aircraft Carrier";
78 static char battle[] = "Battleship";
79 static char sub[] = "Submarine";
80 static char destroy[] = "Destroyer";
81 static char ptboat[] = "PT Boat";
84 static char dftname[] = "stranger";
86 /* direction constants */
87 enum directions { E, SE, S, SW, W, NW, N, NE };
88 static int xincr[8] = {1, 1, 0, -1, -1, -1, 0, 1};
89 static int yincr[8] = {0, 1, 1, 1, 0, -1, -1, -1};
91 /* current ship position and direction */
92 static int curx = (BWIDTH / 2);
93 static int cury = (BDEPTH / 2);
96 char *name; /* name of the ship type */
97 char hits; /* how many times has this ship been hit? */
98 char symbol; /* symbol for game purposes */
99 char length; /* length of ship */
100 char x, y; /* coordinates of ship start point */
101 enum directions dir; /* direction of `bow' */
102 bool placed; /* has it been placed on the board? */
106 ship_t plyship[SHIPTYPES] =
108 { carrier, 0, 'A', 5, 0, 0, E, FALSE},
109 { battle, 0, 'B', 4, 0, 0, E, FALSE},
110 { destroy, 0, 'D', 3, 0, 0, E, FALSE},
111 { sub, 0, 'S', 3, 0, 0, E, FALSE},
112 { ptboat, 0, 'P', 2, 0, 0, E, FALSE},
115 ship_t cpuship[SHIPTYPES] =
117 { carrier, 0, 'A', 5, 0, 0, E, FALSE},
118 { battle, 0, 'B', 4, 0, 0, E, FALSE},
119 { destroy, 0, 'D', 3, 0, 0, E, FALSE},
120 { sub, 0, 'S', 3, 0, 0, E, FALSE},
121 { ptboat, 0, 'P', 2, 0, 0, E, FALSE},
124 /* "Hits" board, and main board. */
125 static char hits[2][BWIDTH][BDEPTH], board[2][BWIDTH][BDEPTH];
127 static int turn; /* 0=player, 1=computer */
128 static int plywon=0, cpuwon=0; /* How many games has each won? */
130 static int salvo, blitz, closepack;
134 static bool checkplace (int, ship_t *, int);
135 static int getcoord (int);
136 int playagain (void);
138 /* end the game, either normally or due to signal */
151 sighandler(__unused int sig)
156 /* announce which game options are enabled */
160 printw("Playing %s game (", (salvo || blitz || closepack) ?
161 "optional" : "standard");
174 printw("closepack)");
176 printw("noclosepack)");
186 tmpname = getlogin();
187 signal(SIGINT,sighandler);
188 signal(SIGINT,sighandler);
189 signal(SIGIOT,sighandler); /* for assert(3) */
190 if(signal(SIGQUIT,SIG_IGN) != SIG_IGN)
191 signal(SIGQUIT,sighandler);
193 if(tmpname != '\0') {
194 strcpy(name,tmpname);
195 name[0] = toupper(name[0]);
197 strcpy(name,dftname);
202 keypad(stdscr, TRUE);
211 mvaddstr(4,29,"Welcome to Battleship!");
215 PR(" \\ \\ \\ \\ \\_____________\n");
216 PR(" \\ \\ \\_____________ \\ \\/ |\n");
217 PR(" \\ \\/ \\ \\/ |\n");
218 PR(" \\/ \\_____/ |__\n");
219 PR(" ________________/ |\n");
220 PR(" \\ S.S. Penguin |\n");
222 PR(" \\___________________________________________________/\n");
224 mvaddstr(22,27,"Hit any key to continue..."); refresh();
231 init_pair(COLOR_BLACK, COLOR_BLACK, COLOR_BLACK);
232 init_pair(COLOR_GREEN, COLOR_GREEN, COLOR_BLACK);
233 init_pair(COLOR_RED, COLOR_RED, COLOR_BLACK);
234 init_pair(COLOR_CYAN, COLOR_CYAN, COLOR_BLACK);
235 init_pair(COLOR_WHITE, COLOR_WHITE, COLOR_BLACK);
236 init_pair(COLOR_MAGENTA, COLOR_MAGENTA, COLOR_BLACK);
237 init_pair(COLOR_BLUE, COLOR_BLUE, COLOR_BLACK);
238 init_pair(COLOR_YELLOW, COLOR_YELLOW, COLOR_BLACK);
243 /* print a message at the prompt line */
245 prompt(int n, const char *f, ...)
247 char buf[COLWIDTH + 1];
251 move(PROMPTLINE + n, 0);
253 vsnprintf(buf, COLWIDTH + 1, f, ap);
262 move(PROMPTLINE + 2, 0);
271 placeship(int b, ship_t *ss, int vis)
275 for(l = 0; l < ss->length; ++l) {
276 int newx = ss->x + l * xincr[ss->dir];
277 int newy = ss->y + l * yincr[ss->dir];
279 board[b][newx][newy] = ss->symbol;
282 addch((chtype)ss->symbol);
291 return(random() % n);
294 /* generate a valid random ship placement into px,py */
296 randomplace(int b, ship_t *ss)
301 ss->dir = rnd(2) ? E : S;
302 } while (!checkplace(b, ss, FALSE));
312 mvaddstr(0,35,"BATTLESHIPS");
313 move(PROMPTLINE + 2, 0);
316 bzero(board, sizeof(char) * BWIDTH * BDEPTH * 2);
317 bzero(hits, sizeof(char) * BWIDTH * BDEPTH * 2);
318 for (i = 0; i < SHIPTYPES; i++) {
320 ss->x = ss->y = ss->dir = ss->hits = ss->placed = 0;
322 ss->x = ss->y = ss->dir = ss->hits = ss->placed = 0;
325 /* draw empty boards */
326 mvaddstr(PYBASE - 2, PXBASE + 5, "Main Board");
327 mvaddstr(PYBASE - 1, PXBASE - 3,numbers);
328 for(i=0; i < BDEPTH; ++i)
330 mvaddch(PYBASE + i, PXBASE - 3, i + 'A');
333 attron(COLOR_PAIR(COLOR_BLUE));
336 for (j = 0; j < BWIDTH; j++)
344 mvaddstr(PYBASE + BDEPTH, PXBASE - 3,numbers);
345 mvaddstr(CYBASE - 2, CXBASE + 7,"Hit/Miss Board");
346 mvaddstr(CYBASE - 1, CXBASE - 3, numbers);
347 for(i=0; i < BDEPTH; ++i)
349 mvaddch(CYBASE + i, CXBASE - 3, i + 'A');
352 attron(COLOR_PAIR(COLOR_BLUE));
355 for (j = 0; j < BWIDTH; j++)
364 mvaddstr(CYBASE + BDEPTH,CXBASE - 3,numbers);
366 mvprintw(HYBASE, HXBASE,
367 "To position your ships: move the cursor to a spot, then");
368 mvprintw(HYBASE+1,HXBASE,
369 "type the first letter of a ship type to select it, then");
370 mvprintw(HYBASE+2,HXBASE,
371 "type a direction ([hjkl] or [4862]), indicating how the");
372 mvprintw(HYBASE+3,HXBASE,
373 "ship should be pointed. You may also type a ship letter");
374 mvprintw(HYBASE+4,HXBASE,
375 "followed by `r' to position it randomly, or type `R' to");
376 mvprintw(HYBASE+5,HXBASE,
377 "place all remaining ships randomly.");
379 mvaddstr(MYBASE, MXBASE, "Aiming keys:");
380 mvaddstr(SYBASE, SXBASE, "y k u 7 8 9");
381 mvaddstr(SYBASE+1, SXBASE, " \\|/ \\|/ ");
382 mvaddstr(SYBASE+2, SXBASE, "h-+-l 4-+-6");
383 mvaddstr(SYBASE+3, SXBASE, " /|\\ /|\\ ");
384 mvaddstr(SYBASE+4, SXBASE, "b j n 1 2 3");
386 /* have the computer place ships */
387 for(ss = cpuship; ss < cpuship + SHIPTYPES; ss++)
389 randomplace(COMPUTER, ss);
390 placeship(COMPUTER, ss, FALSE);
395 char c, docked[SHIPTYPES + 2], *cp = docked;
397 /* figure which ships still wait to be placed */
399 for (i = 0; i < SHIPTYPES; i++)
400 if (!plyship[i].placed)
401 *cp++ = plyship[i].symbol;
404 /* get a command letter */
405 prompt(1, "Type one of [%s] to pick a ship.", docked+1);
407 c = getcoord(PLAYER);
409 (!strchr(docked, c));
415 /* map that into the corresponding symbol */
416 for (ss = plyship; ss < plyship + SHIPTYPES; ss++)
420 prompt(1, "Type one of [hjklrR] to place your %s.", ss->name);
427 (!strchr("hjklrR", c) || c == FF);
431 clearok(stdscr, TRUE);
436 prompt(1, "Random-placing your %s", ss->name);
437 randomplace(PLAYER, ss);
438 placeship(PLAYER, ss, TRUE);
444 prompt(1, "Placing the rest of your fleet at random...");
445 for (ss = plyship; ss < plyship + SHIPTYPES; ss++)
448 randomplace(PLAYER, ss);
449 placeship(PLAYER, ss, TRUE);
454 else if (strchr("hjkl8462", c))
461 case 'k': case '8': ss->dir = N; break;
462 case 'j': case '2': ss->dir = S; break;
463 case 'h': case '4': ss->dir = W; break;
464 case 'l': case '6': ss->dir = E; break;
467 if (checkplace(PLAYER, ss, TRUE))
469 placeship(PLAYER, ss, TRUE);
475 for (unplaced = i = 0; i < SHIPTYPES; i++)
476 unplaced += !plyship[i].placed;
482 mvprintw(HYBASE, HXBASE,
483 "To fire, move the cursor to your chosen aiming point ");
484 mvprintw(HYBASE+1, HXBASE,
485 "and strike any key other than a motion key. ");
486 mvprintw(HYBASE+2, HXBASE,
488 mvprintw(HYBASE+3, HXBASE,
490 mvprintw(HYBASE+4, HXBASE,
492 mvprintw(HYBASE+5, HXBASE,
495 prompt(0, "Press any key to start...");
513 mvprintw(CYBASE + BDEPTH+1, CXBASE+11, "(%d, %c)", curx, 'A'+cury);
518 mvprintw(PYBASE + BDEPTH+1, PXBASE+11, "(%d, %c)", curx, 'A'+cury);
528 ny = cury+BDEPTH-1; nx = curx;
534 ny = cury+1; nx = curx;
540 ny = cury; nx = curx+BWIDTH-1;
546 ny = cury; nx = curx+1;
552 ny = cury+BDEPTH-1; nx = curx+BWIDTH-1;
558 ny = cury+1; nx = curx+BWIDTH-1;
564 ny = cury+BDEPTH-1; nx = curx+1;
570 ny = cury+1; nx = curx+1;
573 nx = curx; ny = cury;
574 clearok(stdscr, TRUE);
579 mvaddstr(CYBASE + BDEPTH + 1, CXBASE + 11, " ");
581 mvaddstr(PYBASE + BDEPTH + 1, PXBASE + 11, " ");
590 /* is this location on the selected zboard adjacent to a ship? */
592 collidecheck(int b, int y, int x)
596 /* anything on the square */
597 if ((collide = IS_SHIP(board[b][x][y])) != 0)
600 /* anything on the neighbors */
604 for (i = 0; i < 8; i++) {
609 if (ONBOARD(xend, yend))
610 collide += IS_SHIP(board[b][xend][yend]);
618 checkplace(int b, ship_t *ss, int vis)
622 /* first, check for board edges */
623 xend = ss->x + (ss->length - 1) * xincr[ss->dir];
624 yend = ss->y + (ss->length - 1) * yincr[ss->dir];
625 if (!ONBOARD(xend, yend)) {
629 error("Ship is hanging from the edge of the world");
632 error("Try fitting it on the board");
635 error("Figure I won't find it if you put it there?");
642 for(l = 0; l < ss->length; ++l) {
643 if(collidecheck(b, ss->y+l*yincr[ss->dir], ss->x+l*xincr[ss->dir])) {
647 error("There's already a ship there");
650 error("Collision alert! Aaaaaagh!");
653 error("Er, Admiral, what about the other ship?");
671 ss = (i) ? cpuship : plyship;
672 for(j=0; j < SHIPTYPES; ++j, ++ss)
673 if(ss->length > ss->hits)
681 /* a hit on the targeted ship */
683 hitship(int x, int y)
689 getyx(stdscr, oldy, oldx);
690 sb = (turn) ? plyship : cpuship;
691 if(!(sym = board[OTHER][x][y]))
693 for(ss = sb; ss < sb + SHIPTYPES; ++ss)
694 if(ss->symbol == sym)
696 if (++ss->hits < ss->length) { /* still afloat? */
702 for (j = -1; j <= 1; j++) {
703 int bx = ss->x + j * xincr[(ss->dir + 2) % 8];
704 int by = ss->y + j * yincr[(ss->dir + 2) % 8];
706 for (i = -1; i <= ss->length; ++i) {
709 cx = bx + i * xincr[ss->dir];
710 cy = by + i * yincr[ss->dir];
711 if (ONBOARD(cx, cy)) {
712 hits[turn][cx][cy] = MARK_MISS;
713 if (turn % 2 == PLAYER) {
717 attron(COLOR_PAIR(COLOR_GREEN));
730 for (i = 0; i < ss->length; ++i)
732 int dx = ss->x + i * xincr[ss->dir];
733 int dy = ss->y + i * yincr[ss->dir];
735 hits[turn][dx][dy] = ss->symbol;
736 if (turn % 2 == PLAYER)
759 prompt(1, "Where do you want to shoot? ");
763 if (hits[PLAYER][curx][cury])
765 prompt(1, "You shelled this spot already! Try again.");
771 hit = IS_SHIP(board[COMPUTER][curx][cury]);
772 hits[PLAYER][curx][cury] = hit ? MARK_HIT : MARK_MISS;
777 attron(COLOR_PAIR(COLOR_RED));
779 attron(COLOR_PAIR(COLOR_GREEN));
782 addch((chtype)hits[PLAYER][curx][cury]);
787 prompt(1, "You %s.", hit ? "scored a hit" : "missed");
788 if(hit && (ss = hitship(curx, cury)))
793 m = " You sank my %s!";
796 m = " I have this sinking feeling about my %s....";
799 m = " My %s has gone to Davy Jones's locker!";
802 m = " Glub, glub -- my %s is headed for the bottom!";
805 m = " You'll pick up survivors from my %s, I hope...!";
810 return(awinna() == -1);
830 for (s1=s; *s1 && ch != *s1; ++s1)
841 /* random-fire routine -- implements simple diagonal-striping strategy */
843 randomfire(int *px, int *py)
845 static int turncount = 0;
846 static int srchstep = BEGINSTEP;
847 static int huntoffs; /* Offset on search strategy */
848 int ypossible[BWIDTH * BDEPTH], xpossible[BWIDTH * BDEPTH], nposs;
849 int ypreferred[BWIDTH * BDEPTH], xpreferred[BWIDTH * BDEPTH], npref;
852 if (turncount++ == 0)
853 huntoffs = rnd(srchstep);
855 /* first, list all possible moves */
857 for (x = 0; x < BWIDTH; x++)
858 for (y = 0; y < BDEPTH; y++)
859 if (!hits[COMPUTER][x][y])
861 xpossible[nposs] = x;
862 ypossible[nposs] = y;
864 if (((x+huntoffs) % srchstep) != (y % srchstep))
866 xpreferred[npref] = x;
867 ypreferred[npref] = y;
891 error("No moves possible?? Help!");
901 /* fire away at given location */
903 cpufire(int x, int y)
909 hits[COMPUTER][x][y] = (hit = (board[PLAYER][x][y])) ? MARK_HIT : MARK_MISS;
910 mvprintw(PROMPTLINE, 0,
911 "I shoot at %c%d. I %s!", y + 'A', x, hit ? "hit" : "miss");
915 printw(" I've sunk your %s", ss->name);
922 attron(COLOR_PAIR(COLOR_RED));
924 attron(COLOR_PAIR(COLOR_GREEN));
927 addch((chtype)(hit ? SHOWHIT : SHOWSPLASH));
932 return(hit ? (sunk ? S_SUNK : S_HIT) : S_MISS);
936 * This code implements a fairly irregular FSM, so please forgive the rampant
937 * unstructuredness below. The five labels are states which need to be held
938 * between computer turns.
943 #define POSSIBLE(x, y) (ONBOARD(x, y) && !hits[COMPUTER][x][y])
944 #define RANDOM_FIRE 0
946 #define HUNT_DIRECT 2
948 #define REVERSE_JUMP 4
949 #define SECOND_PASS 5
950 static int next = RANDOM_FIRE;
953 int navail, x, y, d, n, hit = S_MISS;
957 case RANDOM_FIRE: /* last shot was random and missed */
960 if (!(hit = cpufire(x, y)))
966 next = (hit == S_SUNK) ? RANDOM_FIRE : RANDOM_HIT;
970 case RANDOM_HIT: /* last shot was random and hit */
971 used[E/2] = used[S/2] = used[W/2] = used[N/2] = FALSE;
974 case HUNT_DIRECT: /* last shot hit, we're looking for ship's long axis */
975 for (d = navail = 0; d < 4; d++)
977 x = ts.x + xincr[d*2]; y = ts.y + yincr[d*2];
978 if (!used[d] && POSSIBLE(x, y))
983 if (navail == 0) /* no valid places for shots adjacent... */
984 goto refire; /* ...so we must random-fire */
987 for (d = 0, n = rnd(navail) + 1; n; n--)
994 x = ts.x + xincr[d*2];
995 y = ts.y + yincr[d*2];
997 assert(POSSIBLE(x, y));
999 if (!(hit = cpufire(x, y)))
1003 ts.x = x; ts.y = y; ts.dir = d*2; ts.hits++;
1004 next = (hit == S_SUNK) ? RANDOM_FIRE : FIRST_PASS;
1009 case FIRST_PASS: /* we have a start and a direction now */
1010 x = ts.x + xincr[ts.dir];
1011 y = ts.y + yincr[ts.dir];
1012 if (POSSIBLE(x, y) && (hit = cpufire(x, y)))
1014 ts.x = x; ts.y = y; ts.hits++;
1015 next = (hit == S_SUNK) ? RANDOM_FIRE : FIRST_PASS;
1018 next = REVERSE_JUMP;
1021 case REVERSE_JUMP: /* nail down the ship's other end */
1023 x = ts.x + ts.hits * xincr[d];
1024 y = ts.y + ts.hits * yincr[d];
1025 if (POSSIBLE(x, y) && (hit = cpufire(x, y)))
1027 ts.x = x; ts.y = y; ts.dir = d; ts.hits++;
1028 next = (hit == S_SUNK) ? RANDOM_FIRE : SECOND_PASS;
1034 case SECOND_PASS: /* kill squares not caught on first pass */
1035 x = ts.x + xincr[ts.dir];
1036 y = ts.y + yincr[ts.dir];
1037 if (POSSIBLE(x, y) && (hit = cpufire(x, y)))
1039 ts.x = x; ts.y = y; ts.hits++;
1040 next = (hit == S_SUNK) ? RANDOM_FIRE: SECOND_PASS;
1048 /* check for continuation and/or winner */
1058 mvprintw(PROMPTLINE + 2, 0,
1059 "New state %d, x=%d, y=%d, d=%d",
1071 for (ss = cpuship; ss < cpuship + SHIPTYPES; ss++) {
1072 for(j = 0; j < ss->length; j++) {
1073 cgoto(ss->y + j * yincr[ss->dir], ss->x + j * xincr[ss->dir]);
1074 addch((chtype)ss->symbol);
1084 j = 18 + strlen(name);
1087 } else if(cpuwon >= 10) {
1091 mvprintw(1,(COLWIDTH-j)/2,
1092 "%s: %d Computer: %d",name,plywon,cpuwon);
1094 prompt(2, (awinna()) ? "Want to be humiliated again, %s [yn]? "
1095 : "Going to give me a chance for revenge, %s [yn]? ",name);
1096 return(sgetc("YN") == 'Y');
1102 fprintf(stderr, "Usage: battle [-s | -b] [-c]\n");
1103 fprintf(stderr, "\tWhere the options are:\n");
1104 fprintf(stderr, "\t-s : salvo - One shot per ship in play\n");
1105 fprintf(stderr, "\t-b : blitz - Fire until you miss\n");
1106 fprintf(stderr, "\t-c : closepack - Ships may be adjacent\n");
1107 fprintf(stderr, "Blitz and Salvo are mutually exclusive\n");
1118 sp = cpuship; /* count cpu shots */
1120 sp = plyship; /* count player shots */
1122 for (i=0, shots = 0; i < SHIPTYPES; i++, sp++)
1124 if (sp->hits >= sp->length)
1125 continue; /* dead ship */
1133 main(int argc, char **argv)
1140 while ((ch = getopt(argc, argv, "bsc")) != -1) {
1166 while(awinna() == -1) {
1168 while(turn ? cputurn() : plyturn())
1176 if (cputurn() && awinna() != -1)
1179 if (plyturn() && awinna() != -1)
1183 } else { /* Normal game */
1191 } while (playagain());