CS Department, Fall 1997, Java Programming

Battleship: stage 3

Your next stage is to play an actual game against the computer. This will involve completing work on the interface, if necessary, and implementing a strategy that the computer can use in making guesses. Here are some issues you may want to think about:

  1. Use a random number generator to makes the guesses that are not made on the basis of previous gusses (see 3). The standard generators (Math.random and the class Random) produce useful even distributions, just right for this game.
  2. Make sure the computer doesn’t guess the same square twice. The computer needs to record its guesses, just as you will do through the visual interface.
  3. Record the sequence of guesses, not just their position. This way the computer will be able to tailor its next guess to the last one or two. If you follow up two hits in adjacent squares (horizontally or vertically) with a third in the same line, this stands a better chance of success.
  4. Any other strategy, such as trying to second-guess the opponent is much harder to implement. You don't need to spend time on this, since this is not an AI project!

At the end of this stage your program should:

  1. Show the game graphically, with initial placement of the ships and the visual recording of computer responses to player guesses.
  2. Be able to play any number of games (in sequence), play each game to completion, with the computer as opponent, and process options to quit the game (surrender, if you like) at any time.

Looking ahead to stage 4

You may want to look ahead when you write the code for stage 3 to the two-player version in stage 4. The protocol that your program should follow in order to play a game with another player on another machine is now posted. This protocol will be processed by a class that runs in a separate thread from your main program. We can use the produce/consumer idea from the textbook. Assume that your stage 3 code contains a mouse handler for guesses that looks like this (this is a sketch, not real code you can copy):

boolean action or boolean mouseDown {
processMyGuess(); // from the position of the mouse click, // determine hit or miss from the computer's fleet position
getComputerGuess(); // the computer generates a guess
processComputerGuess(); // determine hit or miss on my fleet position
}

There is no change to the sequence above, just in what it does:

 boolean action or boolean mouseDown {
processMyGuess(); // from the position of the mouse click, // put the guess into a shared object for // the protocol thread to send to the other player
getOpponentGuess(); // retrieve the other player's guess (wait until it arrives)
processOpponentGuess(); // determine hit or miss on my fleet position
}