Java Reference
In-Depth Information
Enter guess:
Note that in the above example the ship that was destroyed covered the cells (5,5)
and (6,5). There was also a different ship that was going through the cell (5,6). There are
different versions of the game that create different numbers and types of ships. We will
assume that the array
placement
contains the type of ship that we want to build on the
board. For example, if
placement =
, then this means that we will create
one ship of 5 cells, one ship of 4 cells, one ship of 3 cells, two ships of 2 cells, and two ships
of 1 cell. The numbers in the array do not have to be ordered.
We will create a
Main
class that contains the
main
method. In addition, we will create a
class for the
Board
,the
Ship
,andthe
Cell
(every board consists of a 10x10 grid of cells).
Let us start with the
Cell
class. In other words, this time we will follow a
bottom-up
design
. We will start with the most rudimentary class and build other classes from it. For
every cell, we need to keep track of whether the cell is visited or not. As our example output
suggests, we are going to display a cell differently depending on whether it is visited or not
and depending on whether it is part of a ship or not. If a cell that is visited is part of a
ship, then we want to inform the user whether the ship is damaged or destroyed. Therefore,
for every cell we will also keep a reference to the ship that crosses through the cell. If the
cell is not part of a ship, then the ship variable will be equal to
null
. This means that the
value for the ship object will not be assigned.
{
5,4,3,2,2,1,1
}
Consider the
C
class. Writing:
C object;
will define the variable
object
to be of
type
C
. The initial value of the variable
object
will be equal to
null
. This means
that it does not reference anything. Later on, we can assign a value to the variable,
for example:
object = new C()
.Ifatanypointwedonotwantthevariabletopoint
to the object, then we can write
object = null
. If there are no more references to
the object, it will be automatically deleted by the garbage collector.
Here is an example implementation of the
Cell
class.
public class
Cell
{
private
Ship ship ;
private boolean
isVisited =
false
;
{
public void
visit()
isVisited =
true
;
}
public boolean
isVisited()
{
return
isVisited ;
}
public boolean
isPartOfShip()
{
return
(ship !=
null
);
}
public void
putShip(Ship ship)
{
this
.ship = ship;
}
public
String toString()
{
if
(! isVisited)
{
return
"O"
;