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.4 2003/11/12 14:53:52 eirikn Exp $
22 #ifndef A_UNDERLINE /* BSD curses */
23 #define beep() write(1,"\007",1);
25 #define saveterm savetty
26 #define resetterm resetty
27 #define nocbreak nocrmode
29 #endif /* !A_UNDERLINE */
33 * Constants for tuning the random-fire algorithm. It prefers moves that
34 * diagonal-stripe the board with a stripe separation of srchstep. If
35 * no such preferred moves are found, srchstep is decremented.
37 #define BEGINSTEP 3 /* initial value of srchstep */
39 /* miscellaneous constants */
41 #define OTHER (1-turn)
46 #define CTRLC '\003' /* used as terminate command */
47 #define FF '\014' /* used as redraw command */
49 /* coordinate handling */
55 #define SHOWSPLASH ' '
56 #define IS_SHIP(c) isupper(c)
58 /* how to position us on player board */
61 #define PY(y) (PYBASE + (y))
62 #define PX(x) (PXBASE + (x)*3)
63 #define pgoto(y, x) (void)move(PY(y), PX(x))
65 /* how to position us on cpu board */
68 #define CY(y) (CYBASE + (y))
69 #define CX(x) (CXBASE + (x)*3)
70 #define cgoto(y, x) (void)move(CY(y), CX(x))
72 #define ONBOARD(x, y) (x >= 0 && x < BWIDTH && y >= 0 && y < BDEPTH)
74 /* other board locations */
76 #define PROMPTLINE 21 /* prompt line */
77 #define SYBASE CYBASE + BDEPTH + 3 /* move key diagram */
79 #define MYBASE SYBASE - 1 /* diagram caption */
81 #define HYBASE SYBASE - 1 /* help area */
84 /* this will need to be changed if BWIDTH changes */
85 static char numbers[] = " 0 1 2 3 4 5 6 7 8 9";
87 static char carrier[] = "Aircraft Carrier";
88 static char battle[] = "Battleship";
89 static char sub[] = "Submarine";
90 static char destroy[] = "Destroyer";
91 static char ptboat[] = "PT Boat";
94 static char dftname[] = "stranger";
96 /* direction constants */
97 enum directions { E, SE, S, SW, W, NW, N, NE };
98 static int xincr[8] = {1, 1, 0, -1, -1, -1, 0, 1};
99 static int yincr[8] = {0, 1, 1, 1, 0, -1, -1, -1};
101 /* current ship position and direction */
102 static int curx = (BWIDTH / 2);
103 static int cury = (BDEPTH / 2);
107 char *name; /* name of the ship type */
108 unsigned int hits; /* how many times has this ship been hit? */
109 char symbol; /* symbol for game purposes */
110 char length; /* length of ship */
111 char x, y; /* coordinates of ship start point */
112 enum directions dir;/* direction of `bow' */
113 bool placed; /* has it been placed on the board? */
117 ship_t plyship[SHIPTYPES] =
119 { carrier, 0, 'A', 5},
120 { battle, 0, 'B', 4},
121 { destroy, 0, 'D', 3},
123 { ptboat, 0, 'P', 2},
126 ship_t cpuship[SHIPTYPES] =
128 { carrier, 0, 'A', 5},
129 { battle, 0, 'B', 4},
130 { destroy, 0, 'D', 3},
132 { ptboat, 0, 'P', 2},
135 /* "Hits" board, and main board. */
136 static char hits[2][BWIDTH][BDEPTH], board[2][BWIDTH][BDEPTH];
138 static int turn; /* 0=player, 1=computer */
139 static int plywon=0, cpuwon=0; /* How many games has each won? */
141 static int salvo, blitz, closepack;
143 #define PR (void)addstr
145 static bool checkplace (int, ship_t *, int);
146 static int getcoord (int);
147 int playagain (void);
149 static void uninitgame(sig)
150 /* end the game, either normally or due to signal */
161 static void announceopts()
162 /* announce which game options are enabled */
164 if (salvo || blitz || closepack)
166 (void) printw("Playing optional game (");
168 (void) printw("salvo, ");
170 (void) printw("nosalvo, ");
172 (void) printw("blitz ");
174 (void) printw("noblitz, ");
176 (void) printw("closepack)");
178 (void) printw("noclosepack)");
182 "Playing standard game (noblitz, nosalvo, noclosepack)");
191 tmpname = getlogin();
192 (void) signal(SIGINT,uninitgame);
193 (void) signal(SIGINT,uninitgame);
194 (void) signal(SIGIOT,uninitgame); /* for assert(3) */
195 if(signal(SIGQUIT,SIG_IGN) != SIG_IGN)
196 (void)signal(SIGQUIT,uninitgame);
200 (void)strcpy(name,tmpname);
201 name[0] = toupper(name[0]);
204 (void)strcpy(name,dftname);
208 keypad(stdscr, TRUE);
217 (void)mvaddstr(4,29,"Welcome to Battleship!");
221 PR(" \\ \\ \\ \\ \\_____________\n");
222 PR(" \\ \\ \\_____________ \\ \\/ |\n");
223 PR(" \\ \\/ \\ \\/ |\n");
224 PR(" \\/ \\_____/ |__\n");
225 PR(" ________________/ |\n");
226 PR(" \\ S.S. Penguin |\n");
228 PR(" \\___________________________________________________/\n");
230 (void) mvaddstr(22,27,"Hit any key to continue..."); (void)refresh();
237 init_pair(COLOR_BLACK, COLOR_BLACK, COLOR_BLACK);
238 init_pair(COLOR_GREEN, COLOR_GREEN, COLOR_BLACK);
239 init_pair(COLOR_RED, COLOR_RED, COLOR_BLACK);
240 init_pair(COLOR_CYAN, COLOR_CYAN, COLOR_BLACK);
241 init_pair(COLOR_WHITE, COLOR_WHITE, COLOR_BLACK);
242 init_pair(COLOR_MAGENTA, COLOR_MAGENTA, COLOR_BLACK);
243 init_pair(COLOR_BLUE, COLOR_BLUE, COLOR_BLACK);
244 init_pair(COLOR_YELLOW, COLOR_YELLOW, COLOR_BLACK);
250 static void prompt(n, f, s)
251 /* print a message at the prompt line */
255 (void) move(PROMPTLINE + n, 0);
264 (void) move(PROMPTLINE + 2, 0);
273 static void placeship(b, ss, vis)
280 for(l = 0; l < ss->length; ++l)
282 int newx = ss->x + l * xincr[ss->dir];
283 int newy = ss->y + l * yincr[ss->dir];
285 board[b][newx][newy] = ss->symbol;
289 (void) addch((chtype)ss->symbol);
298 return(random() % n);
301 static void randomplace(b, ss)
302 /* generate a valid random ship placement into px,py */
306 int bwidth = BWIDTH - ss->length;
307 int bdepth = BDEPTH - ss->length;
312 ss->dir = rnd(2) ? E : S;
314 (!checkplace(b, ss, FALSE));
317 static void initgame()
323 (void) mvaddstr(0,35,"BATTLESHIPS");
324 (void) move(PROMPTLINE + 2, 0);
327 bzero(board, sizeof(char) * BWIDTH * BDEPTH * 2);
328 bzero(hits, sizeof(char) * BWIDTH * BDEPTH * 2);
329 for (i = 0; i < SHIPTYPES; i++)
332 ss->x = ss->y = ss->dir = ss->hits = ss->placed = 0;
334 ss->x = ss->y = ss->dir = ss->hits = ss->placed = 0;
337 /* draw empty boards */
338 (void) mvaddstr(PYBASE - 2, PXBASE + 5, "Main Board");
339 (void) mvaddstr(PYBASE - 1, PXBASE - 3,numbers);
340 for(i=0; i < BDEPTH; ++i)
342 (void) mvaddch(PYBASE + i, PXBASE - 3, i + 'A');
345 attron(COLOR_PAIR(COLOR_BLUE));
348 for (j = 0; j < BWIDTH; j++)
349 (void) addstr(" . ");
354 (void) addch(i + 'A');
356 (void) mvaddstr(PYBASE + BDEPTH, PXBASE - 3,numbers);
357 (void) mvaddstr(CYBASE - 2, CXBASE + 7,"Hit/Miss Board");
358 (void) mvaddstr(CYBASE - 1, CXBASE - 3, numbers);
359 for(i=0; i < BDEPTH; ++i)
361 (void) mvaddch(CYBASE + i, CXBASE - 3, i + 'A');
364 attron(COLOR_PAIR(COLOR_BLUE));
367 for (j = 0; j < BWIDTH; j++)
368 (void) addstr(" . ");
373 (void) addch(i + 'A');
376 (void) mvaddstr(CYBASE + BDEPTH,CXBASE - 3,numbers);
378 (void) mvprintw(HYBASE, HXBASE,
379 "To position your ships: move the cursor to a spot, then");
380 (void) mvprintw(HYBASE+1,HXBASE,
381 "type the first letter of a ship type to select it, then");
382 (void) mvprintw(HYBASE+2,HXBASE,
383 "type a direction ([hjkl] or [4862]), indicating how the");
384 (void) mvprintw(HYBASE+3,HXBASE,
385 "ship should be pointed. You may also type a ship letter");
386 (void) mvprintw(HYBASE+4,HXBASE,
387 "followed by `r' to position it randomly, or type `R' to");
388 (void) mvprintw(HYBASE+5,HXBASE,
389 "place all remaining ships randomly.");
391 (void) mvaddstr(MYBASE, MXBASE, "Aiming keys:");
392 (void) mvaddstr(SYBASE, SXBASE, "y k u 7 8 9");
393 (void) mvaddstr(SYBASE+1, SXBASE, " \\|/ \\|/ ");
394 (void) mvaddstr(SYBASE+2, SXBASE, "h-+-l 4-+-6");
395 (void) mvaddstr(SYBASE+3, SXBASE, " /|\\ /|\\ ");
396 (void) mvaddstr(SYBASE+4, SXBASE, "b j n 1 2 3");
398 /* have the computer place ships */
399 for(ss = cpuship; ss < cpuship + SHIPTYPES; ss++)
401 randomplace(COMPUTER, ss);
402 placeship(COMPUTER, ss, FALSE);
407 char c, docked[SHIPTYPES + 2], *cp = docked;
409 /* figure which ships still wait to be placed */
411 for (i = 0; i < SHIPTYPES; i++)
412 if (!plyship[i].placed)
413 *cp++ = plyship[i].symbol;
416 /* get a command letter */
417 prompt(1, "Type one of [%s] to pick a ship.", docked+1);
419 c = getcoord(PLAYER);
421 (!strchr(docked, c));
427 /* map that into the corresponding symbol */
428 for (ss = plyship; ss < plyship + SHIPTYPES; ss++)
432 prompt(1, "Type one of [hjklrR] to place your %s.", ss->name);
439 (!strchr("hjklrR", c) || c == FF);
443 (void)clearok(stdscr, TRUE);
448 prompt(1, "Random-placing your %s", ss->name);
449 randomplace(PLAYER, ss);
450 placeship(PLAYER, ss, TRUE);
456 prompt(1, "Placing the rest of your fleet at random...");
457 for (ss = plyship; ss < plyship + SHIPTYPES; ss++)
460 randomplace(PLAYER, ss);
461 placeship(PLAYER, ss, TRUE);
466 else if (strchr("hjkl8462", c))
473 case 'k': case '8': ss->dir = N; break;
474 case 'j': case '2': ss->dir = S; break;
475 case 'h': case '4': ss->dir = W; break;
476 case 'l': case '6': ss->dir = E; break;
479 if (checkplace(PLAYER, ss, TRUE))
481 placeship(PLAYER, ss, TRUE);
487 for (unplaced = i = 0; i < SHIPTYPES; i++)
488 unplaced += !plyship[i].placed;
494 (void) mvprintw(HYBASE, HXBASE,
495 "To fire, move the cursor to your chosen aiming point ");
496 (void) mvprintw(HYBASE+1, HXBASE,
497 "and strike any key other than a motion key. ");
498 (void) mvprintw(HYBASE+2, HXBASE,
500 (void) mvprintw(HYBASE+3, HXBASE,
502 (void) mvprintw(HYBASE+4, HXBASE,
504 (void) mvprintw(HYBASE+5, HXBASE,
507 (void) prompt(0, "Press any key to start...");
511 static int getcoord(atcpu)
525 (void) mvprintw(CYBASE + BDEPTH+1, CXBASE+11, "(%d, %c)", curx, 'A'+cury);
530 (void) mvprintw(PYBASE + BDEPTH+1, PXBASE+11, "(%d, %c)", curx, 'A'+cury);
540 ny = cury+BDEPTH-1; nx = curx;
546 ny = cury+1; nx = curx;
552 ny = cury; nx = curx+BWIDTH-1;
558 ny = cury; nx = curx+1;
564 ny = cury+BDEPTH-1; nx = curx+BWIDTH-1;
570 ny = cury+1; nx = curx+BWIDTH-1;
576 ny = cury+BDEPTH-1; nx = curx+1;
582 ny = cury+1; nx = curx+1;
585 nx = curx; ny = cury;
586 (void)clearok(stdscr, TRUE);
591 (void) mvaddstr(CYBASE + BDEPTH + 1, CXBASE + 11, " ");
593 (void) mvaddstr(PYBASE + BDEPTH + 1, PXBASE + 11, " ");
602 static int collidecheck(b, y, x)
603 /* is this location on the selected zboard adjacent to a ship? */
609 /* anything on the square */
610 if ((collide = IS_SHIP(board[b][x][y])) != 0)
613 /* anything on the neighbors */
618 for (i = 0; i < 8; i++)
624 if (ONBOARD(xend, yend))
625 collide += IS_SHIP(board[b][xend][yend]);
631 static bool checkplace(b, ss, vis)
638 /* first, check for board edges */
639 xend = ss->x + ss->length * xincr[ss->dir];
640 yend = ss->y + ss->length * yincr[ss->dir];
641 if (!ONBOARD(xend, yend))
647 error("Ship is hanging from the edge of the world");
650 error("Try fitting it on the board");
653 error("Figure I won't find it if you put it there?");
659 for(l = 0; l < ss->length; ++l)
661 if(collidecheck(b, ss->y+l*yincr[ss->dir], ss->x+l*xincr[ss->dir]))
667 error("There's already a ship there");
670 error("Collision alert! Aaaaaagh!");
673 error("Er, Admiral, what about the other ship?");
689 ss = (i) ? cpuship : plyship;
690 for(j=0; j < SHIPTYPES; ++j, ++ss)
691 if(ss->length > ss->hits)
699 static ship_t *hitship(x, y)
700 /* a hit on the targeted ship */
707 getyx(stdscr, oldy, oldx);
708 sb = (turn) ? plyship : cpuship;
709 if(!(sym = board[OTHER][x][y]))
710 return((ship_t *)NULL);
711 for(ss = sb; ss < sb + SHIPTYPES; ++ss)
712 if(ss->symbol == sym)
714 if (++ss->hits < ss->length) /* still afloat? */
715 return((ship_t *)NULL);
721 for (j = -1; j <= 1; j++)
723 int bx = ss->x + j * xincr[(ss->dir + 2) % 8];
724 int by = ss->y + j * yincr[(ss->dir + 2) % 8];
726 for (i = -1; i <= ss->length; ++i)
730 x = bx + i * xincr[ss->dir];
731 y = by + i * yincr[ss->dir];
734 hits[turn][x][y] = MARK_MISS;
735 if (turn % 2 == PLAYER)
740 attron(COLOR_PAIR(COLOR_GREEN));
742 (void)addch(MARK_MISS);
751 for (i = 0; i < ss->length; ++i)
753 int x = ss->x + i * xincr[ss->dir];
754 int y = ss->y + i * yincr[ss->dir];
756 hits[turn][x][y] = ss->symbol;
757 if (turn % 2 == PLAYER)
760 (void) addch(ss->symbol);
764 (void) move(oldy, oldx);
768 (void) move(oldy, oldx);
769 return((ship_t *)NULL);
779 prompt(1, "Where do you want to shoot? ");
782 (void) getcoord(COMPUTER);
783 if (hits[PLAYER][curx][cury])
785 prompt(1, "You shelled this spot already! Try again.");
791 hit = IS_SHIP(board[COMPUTER][curx][cury]);
792 hits[PLAYER][curx][cury] = hit ? MARK_HIT : MARK_MISS;
797 attron(COLOR_PAIR(COLOR_RED));
799 attron(COLOR_PAIR(COLOR_GREEN));
802 (void) addch((chtype)hits[PLAYER][curx][cury]);
807 prompt(1, "You %s.", hit ? "scored a hit" : "missed");
808 if(hit && (ss = hitship(curx, cury)))
813 m = " You sank my %s!";
816 m = " I have this sinking feeling about my %s....";
819 m = " My %s has gone to Davy Jones's locker!";
822 m = " Glub, glub -- my %s is headed for the bottom!";
825 m = " You'll pick up survivors from my %s, I hope...!";
828 (void)printw(m, ss->name);
830 return(awinna() == -1);
849 for (s1=s; *s1 && ch != *s1; ++s1)
853 (void) addch((chtype)ch);
861 static void randomfire(px, py)
862 /* random-fire routine -- implements simple diagonal-striping strategy */
865 static int turncount = 0;
866 static int srchstep = BEGINSTEP;
867 static int huntoffs; /* Offset on search strategy */
868 int ypossible[BWIDTH * BDEPTH], xpossible[BWIDTH * BDEPTH], nposs;
869 int ypreferred[BWIDTH * BDEPTH], xpreferred[BWIDTH * BDEPTH], npref;
872 if (turncount++ == 0)
873 huntoffs = rnd(srchstep);
875 /* first, list all possible moves */
877 for (x = 0; x < BWIDTH; x++)
878 for (y = 0; y < BDEPTH; y++)
879 if (!hits[COMPUTER][x][y])
881 xpossible[nposs] = x;
882 ypossible[nposs] = y;
884 if (((x+huntoffs) % srchstep) != (y % srchstep))
886 xpreferred[npref] = x;
887 ypreferred[npref] = y;
911 error("No moves possible?? Help!");
921 static bool cpufire(x, y)
922 /* fire away at given location */
929 hits[COMPUTER][x][y] = (hit = (board[PLAYER][x][y])) ? MARK_HIT : MARK_MISS;
930 (void) mvprintw(PROMPTLINE, 0,
931 "I shoot at %c%d. I %s!", y + 'A', x, hit ? "hit" : "miss");
935 (void) printw(" I've sunk your %s", ss->name);
942 attron(COLOR_PAIR(COLOR_RED));
944 attron(COLOR_PAIR(COLOR_GREEN));
947 (void)addch((chtype)(hit ? SHOWHIT : SHOWSPLASH));
952 return(hit ? (sunk ? S_SUNK : S_HIT) : S_MISS);
956 * This code implements a fairly irregular FSM, so please forgive the rampant
957 * unstructuredness below. The five labels are states which need to be held
958 * between computer turns.
960 static bool cputurn()
962 #define POSSIBLE(x, y) (ONBOARD(x, y) && !hits[COMPUTER][x][y])
963 #define RANDOM_FIRE 0
965 #define HUNT_DIRECT 2
967 #define REVERSE_JUMP 4
968 #define SECOND_PASS 5
969 static int next = RANDOM_FIRE;
972 int navail, x, y, d, n, hit = S_MISS;
976 case RANDOM_FIRE: /* last shot was random and missed */
979 if (!(hit = cpufire(x, y)))
985 next = (hit == S_SUNK) ? RANDOM_FIRE : RANDOM_HIT;
989 case RANDOM_HIT: /* last shot was random and hit */
990 used[E/2] = used[S/2] = used[W/2] = used[N/2] = FALSE;
993 case HUNT_DIRECT: /* last shot hit, we're looking for ship's long axis */
994 for (d = navail = 0; d < 4; d++)
996 x = ts.x + xincr[d*2]; y = ts.y + yincr[d*2];
997 if (!used[d] && POSSIBLE(x, y))
1002 if (navail == 0) /* no valid places for shots adjacent... */
1003 goto refire; /* ...so we must random-fire */
1006 for (d = 0, n = rnd(navail) + 1; n; n--)
1013 x = ts.x + xincr[d*2];
1014 y = ts.y + yincr[d*2];
1016 assert(POSSIBLE(x, y));
1018 if (!(hit = cpufire(x, y)))
1022 ts.x = x; ts.y = y; ts.dir = d*2; ts.hits++;
1023 next = (hit == S_SUNK) ? RANDOM_FIRE : FIRST_PASS;
1028 case FIRST_PASS: /* we have a start and a direction now */
1029 x = ts.x + xincr[ts.dir];
1030 y = ts.y + yincr[ts.dir];
1031 if (POSSIBLE(x, y) && (hit = cpufire(x, y)))
1033 ts.x = x; ts.y = y; ts.hits++;
1034 next = (hit == S_SUNK) ? RANDOM_FIRE : FIRST_PASS;
1037 next = REVERSE_JUMP;
1040 case REVERSE_JUMP: /* nail down the ship's other end */
1042 x = ts.x + ts.hits * xincr[d];
1043 y = ts.y + ts.hits * yincr[d];
1044 if (POSSIBLE(x, y) && (hit = cpufire(x, y)))
1046 ts.x = x; ts.y = y; ts.dir = d; ts.hits++;
1047 next = (hit == S_SUNK) ? RANDOM_FIRE : SECOND_PASS;
1053 case SECOND_PASS: /* kill squares not caught on first pass */
1054 x = ts.x + xincr[ts.dir];
1055 y = ts.y + yincr[ts.dir];
1056 if (POSSIBLE(x, y) && (hit = cpufire(x, y)))
1058 ts.x = x; ts.y = y; ts.hits++;
1059 next = (hit == S_SUNK) ? RANDOM_FIRE: SECOND_PASS;
1067 /* check for continuation and/or winner */
1077 (void) mvprintw(PROMPTLINE + 2, 0,
1078 "New state %d, x=%d, y=%d, d=%d",
1090 for (ss = cpuship; ss < cpuship + SHIPTYPES; ss++)
1091 for(j = 0; j < ss->length; j++)
1093 cgoto(ss->y + j * yincr[ss->dir], ss->x + j * xincr[ss->dir]);
1094 (void)addch((chtype)ss->symbol);
1101 j = 18 + strlen(name);
1106 (void) mvprintw(1,(COLWIDTH-j)/2,
1107 "%s: %d Computer: %d",name,plywon,cpuwon);
1109 prompt(2, (awinna()) ? "Want to be humiliated again, %s [yn]? "
1110 : "Going to give me a chance for revenge, %s [yn]? ",name);
1111 return(sgetc("YN") == 'Y');
1114 static void do_options(c,op)
1128 (void) fprintf(stderr, "Usage: battle [-s | -b] [-c]\n");
1129 (void) fprintf(stderr, "\tWhere the options are:\n");
1130 (void) fprintf(stderr, "\t-s : play a salvo game\n");
1131 (void) fprintf(stderr, "\t-b : play a blitz game\n");
1132 (void) fprintf(stderr, "\t-c : ships may be adjacent\n");
1142 (void) fprintf(stderr,
1143 "Bad Arg: -b and -s are mutually exclusive\n");
1151 (void) fprintf(stderr,
1152 "Bad Arg: -s and -b are mutually exclusive\n");
1160 (void) fprintf(stderr,
1161 "Bad arg: type \"%s ?\" for usage message\n", op[0]);
1169 static int scount(who)
1176 sp = cpuship; /* count cpu shots */
1178 sp = plyship; /* count player shots */
1180 for (i=0, shots = 0; i < SHIPTYPES; i++, sp++)
1182 if (sp->hits >= sp->length)
1183 continue; /* dead ship */
1198 do_options(argc, argv);
1203 while(awinna() == -1)
1223 if (cputurn() && awinna() != -1)
1228 if (plyturn() && awinna() != -1)
1235 while(turn ? cputurn() : plyturn())
1247 /* bs.c ends here */