Java Reference
In-Depth Information
public class Main {
public static void main(String [] args) {
Scanner k = new Scanner(System. in) ;
Board board = new Board() ;
System. out . println (board) ;
while (! board. isAllMarked() ) {
int row , column ;
System. out . print ( "Enter guess: " );
row = k . nextInt () ;
column = k . nextInt () ;
board . visit (row, column) ;
if (board . isPartOfShip(row, column) ) {
if (board . isSunkAt(row, column))
System. out . println ( "Ship Destroyed!" );
System. out . println ( "Ship Damaged!" );
System. out . println (board) ;
else {
System. out . println ( "Empty!" );
System. out . println (board) ;
The method has a continuous loop that asks for user input and then visits the specified cell.
The loop terminates when all the ships are sunk. If the user hits a ship, then the isSunk
method of the Ship class checks to see whether the ship is sunk and an appropriate message
is printed.
Although at first glance simple, the design of the battleship game is not rudimentary
and it involves the interaction of four classes. When creating the design, we observed the
following general design rules.
1. All non-constant variables of a class should be private.
2. All public methods of a class should be used to provide access to the data of the class
to the outside world.
3. All methods should be simple and perform a single task.
4. Inter-class interaction should be minimized.
In order to demonstrate the last point, note that the Main class interacts only with the
Board class. A design where the Main class interacts additionally with objects of the Cell
and Ship classes is certainly possible. However, this will increase the number of inter-class
interactions and will make the Board class partially obsolete. That is, why have a Board
class if the Main class directly interacts with the cells and the ships of the game?
Search WWH ::

Custom Search