Java Assignment 10 -- Battleship

Hidden in the grid is a "Battleship" that is four cells long.
Clicking on a cell tests for the battleship.
The battleship may be hidden vertically or horizontally, but not diagonally.
A miss is recorded as a blue cell and a hit is red.

This assignment asks you to write an applet for a simple one-player Battleship game. Every time the user clicks the mouse, the cell is tested. If the user clicks on a cell that does not contain the battleship, a miss is recorded as a blue cell. If the user clicks on a cell that hides the battleship, the cell becomes red. After all four cells for the battleship have been struck, the game is over, and GAME OVER appears at the top of the screen. The player can start a new game at any time by pressing the reset button.

Program requirements

Your battleship game must have:
  1. At least one 4 cell long battleship hidden horizontally or vertically (but not diagonally).
  2. At least a 5 x 5 grid of buttons. (Look at the example on the website).
  3. At least two classes: A Ship class as well as the Applet class.
  4. A count of the current number of hits and the total number of shots used so far.
  5. A reset button that resets the game to it initial values.

The Ship class

In addition to the applet class you well need to use a class to represent the ship. Your ship class should have a method that “hides” the ship in the grid and stores its position as member data. It should also have a method that checks to see if a button press hits the hidden ship. Remember to use appropriate constants.
In your applet you might then declare

The Applet

You may find the Array of Buttons example on the class website helpful for this assignment. It shows how to make an array of buttons and arrange them using a grid layout. Since there will be more than just buttons in displayed in the applet, you may want to use a Panel. You can use a grid layout for the buttons on the panel, and then place the panel anywhere you want using setBounds.

Panel buttonPanel = new Panel();
buttonPanel.setBounds(50,50,200,200);
add(buttonPanel);
buttonPanel.setLayout(new GridLayout(nNUM_ROWS, nNUM_COLUMNS, 0, 0));

You can then add the buttons to the Panel much as you would to an Applet. Since you have an array of buttons, you may want some code similar to the following in a loop that initializes each of the buttons:

buttonArray[nNum] = new Button("");
buttonPanel.add(buttonArray[nNum]);

//or the same thing in one line of code!
buttonPanel.add(buttonArray[nNum] = new Button(""));

Extensions and modifications

There are many possibilities to extend this assignment if you have extra time. None of these are required however.

You will need a web page to display your applet. Your homepage should have a link to the web page for this assignment.

Submit the URL of your applet along with your Java code (the .java file(s)) in an email message to mrsimon@lycos.com.