Add and Count the Holes
Learn how to add holes to the terrain button and display the count of neighboring holes correctly.
We'll cover the following
Adding holes to the terrain and displaying them
Next, you will add holes to random terrain buttons on the grid.
- In the constructor, call
setHoles()
afterinitGUI()
.
Note: Do not click on the run button after just calling. The code will have a syntax error because setHoles()
does not exist yet.
...
public WatchYourStep() {
initGUI();
setHoles();
setTitle("Watch Your Step");
...
Let’s define the setHoles
method.
-
Add a private method called
setHoles()
. It should take no parameters and return nothing. -
Create a new
Random
object calledrand
for generating a random number. -
Add a loop to repeat for the number of holes to be created: Use a for loop and
NUMBEROFHOLES
. -
Create two integers called
pickRow
andpickCol
, each initialized by getting a differentrandom
number fromrand
. Use Random’snextInt()
method and pick a number between0
and one less thanGRIDSIZE
. -
While the terrain element at
pickRow
andpickCol
has a hole, userand
to pick new random numbers forpickRow
andpickCol
. Use TerrainButton’shasHole()
method and Random’snextInt()
method. -
After the
while
loop, set the hole for the terrain element atpickRow
andpickCol
totrue
. Use TerrainButton’ssetHole()
method. -
Reveal the terrain element just set to a hole, so you can see whether your code really hides holes in
10
squares. Use TerrainButton’sreveal()
method.
...
______________ setHoles() {
________ rand = ________________;
for (________________) {
______ pickRow = _________________;
______ pickCol = _________________;
while (____________________) {
pickRow = _______________;
pickCol = _______________;
}
terrain[____][____].____________;
terrain[____][____].____________;
}
}
...
Get hands-on with 1200+ tech skills courses.