Goals
Create a program to play the game Battleship. The computer will automatically place down a ship on the “board”. The human will guess the location of the ship to try to sink it.
Skills
- 2D Arrays
- Algorithms
Program Details
Your game needs to be designed with the following rules.
- The game board is a 5×5 array.
- The ship is 2 adjacent “squares” large and is randomly placed by the computer on the board.
- Reprint the board after every guess showing hits, misses and blanks.
- Set the maximum number of attempts to 10.
- Report if the game has been won or lost in 10 attempts.
Hints to Build the Game
- Your game board is really a location of guesses.
- Misses could be displayed with an “X”.
- Hits could be an “S”.
- Spots not guessed can be displayed as a “-“, “|”, or “<space”.
- What the array actually is and how it is displayed can be different. Your array may actually be integers, but you display characters.
- Example:
- Array
0, 0, 0, 0, 0
0, 1, 2, 1, 0
0, 0, 2, 0, 0
0, 0, 0, 1, 0
0, 1, 0, 0, 0 - Display
– – – – –
– X S X –
– – S – –
– – – X –
– X – – –
- Array
- Don’t try to program the whole thing all at once. Build it in pieces.
- Start by just making and displaying the board. You may find that displaying the board (writing it to the console) may be easiest done in its own method.
- Add the guessing system. Make sure the user can guess a location and you can display their guesses.
- Add the ship and the ability of the guess to “hit” the ship.
- The ship can just be two (x,y) points.
- Compare the guess array to the ship’s coordinates to determine if it has been hit.
- Initially, put the ship in one location only.
- Once the rest of the code works, then put it in a random location.
- Add a check to see if the ship has been sunk, i.e. both points have been guesses. This could be it’s own method as well.
- Limit the number of guesses to win or lose the game.
Resources
Java Textbook
Chapter 8: Arrays
CS Awesome Website
Bill Barnum's AP Computer Science A videos
AP College Board test prep videos
AP College Board 6.4: Algorithms using arrays