Java Reference
In-Depth Information
public static final boolean
VERTICAL =
false
;
public static final int
[ ] placement =
{
5,4,3,2,2,1,1
}
;
The first constant stores the size of the board, where the program only works with a
square board. The next two constants define the horizontal and vertical direction, while
the last constant lists the sizes of the ships that will be placed on the board. This design
is elegant because it allows us to easily change the board size or the ship sizes without
modifying any other code.
For every board, we will store the ships and cells that make up the board. Here is the
definition of the two variables:
Ship [] ships =
new
Ship [ placement . length ] ;
Cell[][] grid =
new
Cell [BOARDSIZE ] [ BOARD SIZE ] ;
Note that the number of ships is equal to the size of the
placement
array.
Next, we present the constructor of the
Board
class. As expected, it will simply initialize
the instance variables of the class (i.e., the variables
ships
and
grid
).
public class
Board
{
...
public
Board()
{
populateGrid() ;
populateShips () ;
}
public void
populateGrid()
{
for
(
int
row = 0; row
<
BOARD SIZE ;
row++)
{
for
(
int
col = 0; col
<
BOARD SIZE ;
c o l ++)
{
grid [row][ col ] =
new
Cell () ;
}
}
}
public void
populateShips ()
{
for
(
int
i=0; i
<
placement . length ;
i++)
{
ships [ i]=
new
Ship(placement [ i ] ,
this
);
}
}
}
The constructor is split into two methods. The
populateGrid
method creates the cells,
while the
populateShips
method creates the ships and adds them to the array of ships. The
for
loop in the
populateShips
method traverses the
placement
array. For each element of
the array, the method creates a ship with the required size and adds the ship to the
ships
array. Note that, as expected, the
new
keyword is called multiple times on the
ships
array.
It is called once to create the array and then again for each element of the array. When we
call the constructor of the
Ship
class, the second parameter is the
this
reference because
the
Ship
class needs access to the board object.
Next, we show the
toString
method of the
Board
class. It traverses the cells of the grid
and calls the
toString
method on each cell of the grid.
public
String toString()
{
String result =
" 0123456789\n ----------"
;
int
line = 0;
for
(Cell[] row: grid)
{
result+=
"\n"
;