CS 2401 Assignment #2

Due Date: Monday, February 14 or Tuesday, February 15, depending on the day of your lab.

Objective: The goal of this assignment is to practice 2-dimensional arrays.

Background and assignment: This assignment deals with a simplified version of the battleship game. In this game, the defender places several ships on a grid. In our version, we will use 8 by 8 grid, and we will place 5 ships on the grid:

Each ship can be placed either vertically or horizontally.

The attacker does not know where the ships are. So, on the screen, the attacker sees an array of question marks:

? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ?
At any given moment of time, the system should ask whether an attacker wants to continue and, if yes, ask for the row and column number of the square that he or she wants to hit. If there is a ship at this location, the system should mark it with a hit sign X. If there is no ship, the system should mark this location with a 0. Then, the system should again ask for the new hit location. For example, if the attacker: then the picture on the screen should look like this:
? ? ? 0 ? ? ? ?
? X ? ? ? ? ? ?
? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ?

This can happen, e.g., if the defender placed the ships as follows:

0 0 0 0 0 0 0 0
a a a a a 0 p p
0 0 0 0 0 0 0 0
b 0 d 0 s 0 0 0
b 0 d 0 s 0 0 0
b 0 d 0 s 0 0 0
b 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
In this table, '0' means that there is no ship at this square, 'a' means that there is an aircraft carrier, 'b' means a battleship, 'd' a destroyer, 's' a submarine, and 'p' a patrol boat.

Your program should perform the following tasks:

For example, for the above configuration, the defender should indicate the following coordinates:

Hint: one possibility is to form two 2-dimensional arrays:

For extra credit:

  1. In the actual battleship game, the ships cannot intersect and cannot touch. In our program, we assume that the defender takes care of this no-touching rule by giving appropriate coordinates of the ships. For extra credit, modify your program so that it automatically checks whether there is place for the ships.
  2. Another feature that you may want to add to your program is the possibility, after the attacker quits, to report which ships were hit and which were destroyed (a ship is destroyed if all its squares were hit).