Java Reference
In-Depth Information
}
else {
if (ship != null )
{
return "X" ;
}
else {
return "" ;
}
}
}
public boolean isSunk()
{
return ship . isSunk() ;
}
}
Note that the class does not have a constructor. This means that a default constructor
with no formal parameters is automatically introduced. This default constructor will not
do anything. The first four methods provide access to the two variables of the class. Note
that there is no method to return the ship that crosses through the current cell. The reason
is that a class should be designed the same way as the Central Intelligent Agency (CIA)
agent. It should receive only the information it needs and it should provide information
to the outside world on a need-to-know basis. For example, the outside world does not
need to know which ship crosses through the current cell and therefore a getShip method
should not be part of the interface of the class. The need-to-know basis design reduces the
interaction between the class and the outside world, which simplifies the code.
The toString method converts an object of type Cell to a String . If the cell is not
visited, then "O" will be returned (meaning that we do not know whether there is a ship
crossing the cell). If the cell is visited and empty, then "" will be returned. Finally, if
the cell is visited and contains part of a ship, then "X" will be returned. The symbol "X"
symbolizes that this cell of the ship is hit.
Once a cell that is part of a ship is visited, we want to inform the player whether they
hit or destroyed the ship. The isSunk method determines if the ship that crosses though
the cell is destroyed or just damaged.
Next, let us concentrate on the Ship class. The constructor of the class will need to place
the ship on the board. Of course, we have to be careful that the ship does not go outside
the board and that it does not overlap with another ship. We will represent a ship by its
starting coordinates, its direction (i.e., horizontal or vertical), and its size. We will also keep
a reference to the board so that we know where the ship can be placed. Our algorithm tries
to place the ship at a random position. However, if this position is not valid, then another
position is selected at random. The code for the constructor of the Ship class follows.
public class Ship {
private int startRow , startColumn ;
private boolean direction ;
private int size ;
private Board board ;
public Ship( int size , Board board)
{
this . board = board ;
this .size = size;
do
{
startRow = ( int )
(Math . random ( )
Board .BOARD SIZE) ;
startColumn = ( int )
(Math . random ( )
Board .BOARD SIZE) ;
di rect i on = (Math . random() > 0 . 5 )
? Bo a r d . VERTICAL : Bo a r d .
HORIZONTAL ;
 
Search WWH ::




Custom Search