Java Reference
In-Depth Information
for ( int newRow = row ; newRow < =row+size 1 ; newRow++) {
grid [newRow] [ column ] . putShip( ship) ;
public void visit( int row , int column) {
grid[row][column]. visit();
public boolean isAllMarked()
for (Cell[] row : grid) {
for (Cell element : row) {
if (element . isPartOfShip () && ! element . isVisited () )
return false ;
return true ;
public boolean isPartOfShip( int row , int column) {
return (grid [row][ column ]. isPartOfShip()) ;
public boolean isVisited( int row , int column) {
return grid[row][column]. isVisited();
public boolean isSunkAt( int row , int column) {
return grid [row] [ column ] . isSunk() ;
} Note that the main method of our program will create a single board object and interact
with it. Therefore, the Board class provides methods to access the ships and cells of the
board. Following the need-to-know principle, the Board class does not provide direct access
to its ships and cells. As a general rule, a class should not return any of its internal objects
because this will expose them to the outside world and practically nullify the information
isolation principle. Remember that once someone has a reference to an object, then they
will have access to all of its public methods.
The visit method simply marks a cell as visited. The isAllMarked method is respon-
sible for checking whether all the ships are sunk. When this condition becomes true ,the
game can end. The method examines all the cells of the board. If a cell contains part of a
ship that is not visited, then obviously not all ships are sunk and the method returns false .
If all the ship cells are visited, then the method returns true .The isFree method checks
to see if a ship can be placed at the specified location. Instead of directly accessing the cells
of the grid, it calls the getElement method, which ensures that the current cell is inside
the grid. This prevents an ArrayIndexOutOfBounds exception from occurring. The latter
occurs when we try to access an element of an array that does not exist. It is the job of the
getElement method to ensure that the coordinates of the cell are in the board. If they are
not, then the method will return null , which means that the requested cell does not exist.
The populateShip method simply places a ship on the board by marking the appropriate
cells of the grid. The isVisited method checks to see if the cell is visited.
Lastly, let us examine the main method of the Main class.
import java . util . ;
Search WWH ::

Custom Search