Java Reference
In-Depth Information
A
B
C
D
E
F
G
H
I
L
1
2
3
4
5
6
7
8
9
10
FIGURE 5.4:
Example Battleship board.
arrays has allowed us to shorten our code and make it more versatile. We can easily extend
the game and add more items to trade. At the same time, the code is more compact and
isolating errors is simpler. The menu is also more compact and more user friendly.
5.3 Two-Dimensional Arrays
You have probably played the popular game Battleship. The game was invented by
Clifford Von Wickler in the early 1900s. Each player has a ten-by-ten board on which they
can place different types of ships.
The board of a player can be represented as a two-dimensional array. The objective of
the game is to sink the ships of the other player. Look at Figure 5.4. All attacked spots are
marked with an “X”. You can see that the player was successful in sinking a patrol boat (a
two-cell ship) and significantly damaging a destroyer (a three-cell ship).
Consider the following definition.
boolean
board [ ] [ ] =
new boolean
[10][10];
This creates a two-dimensional array of Boolean values. Initially, a default value of false is
used for all the elements of the array. Note that the first index represents the number of
rows in the table, while the second index represents the number of columns in the table.
We will set an element of this array to true when there is a ship that crosses the cell.
Table 5.1 shows an example of representing a battleship on the board. Note that we will
use numbers instead of letters to identify the columns. In a two-dimensional array, the row
is represented first followed by the column. For example, B7 from Figure 5.4 corresponds
to the element at position (6,1) in Table 5.1. A position on the board is accessed using the
syntax: board[row][column]. For example, the battleship (a four-cell ship) that is shown on
the board in Table 5.1 can be described by the following sequence of statements.
board[3][3]=
true
;