Java Reference
In-Depth Information
}
while
(! board . isFree (startRow , startColumn , direction , size ) ) ;
board . populate (startRow , startColumn , direction , size ,
this
);
}
...
}
The constants
HORIZONTAL
,
VERTICAL
,and
BOARD SIZE
will be defined in the
Board
class. Remember that constants are written in all capital letters. The first two constants
contain opposite Boolean values, while the third constant stores the size of the board (i.e.,
10 in our case). The
isFree
method of the
Board
class tests whether the ship can be placed
at the specified location. The
populate
method of the
Board
class places the ship on the
board. Note that the parameters of the ship and the
this
reference are sent as parameters
to the
populate
method of the
Board
class. The reason is that the
Board
class needs a
reference to the ship. It will give this reference to the cells of the board.
The constructor chooses a random start row, start column, and direction. Note that
we have two choices for the direction. Remember that
Math.random()
returns a random
number between 0 and 1. If this number is greater than 0.5, then we use the vertical
direction. Otherwise, we use the horizontal direction. The loop keeps executing until we are
able to successfully place the ship on the board (i.e., the
isFree
method returns true).
Next, we will introduce one more method to the
Ship
class. It is named
isSunk
and it
tests whether the ship is sunk (i.e., all its cells are visited).
public class
Ship
{
private int
startRow , startColumn ;
private boolean
direction ;
private int
size ;
Board board ;
...
public boolean
isSunk()
{
if
( d i r e c t i o n == Bo a r d . VERTICAL)
{
for
(
int
row = startRow , column = startColumn ;
row
<
= startRow + size
−
1 ;
row++)
{
if
(!board. isVisited(row, column))
{
return false
;
}
}
}
else
{
for
(
int
row = startRow , column = startColumn ;
column
<
= startColumn + size
−
1 ;
co lumn++)
{
if
(!board. isVisited(row, column))
{
return false
;
}
}
return true
;
}
}
The
isVisited
method of the
Board
class will check if the cell in question is visited.
The above method goes through all cells of the ship. If one of the cells is not visited, then
the method returns
false
(i.e., the ship is not sunk). Otherwise, the method returns
true
.
Next, let us consider the
Board
class. In it, we will have the following constants.
public static final int
BOARD SIZE = 10;
public static final boolean
HORIZONTAL =
true
;