Add and Count the Holes

Learn how to add holes to the terrain button and display the count of neighboring holes correctly.

Adding holes to the terrain and displaying them

Next, you will add holes to random terrain buttons on the grid.

  1. In the constructor, call setHoles() after initGUI().

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.

  1. Add a private method called setHoles(). It should take no parameters and return nothing.

  2. Create a new Random object called rand for generating a random number.

  3. Add a loop to repeat for the number of holes to be created: Use a for loop and NUMBEROFHOLES.

  4. Create two integers called pickRow and pickCol, each initialized by getting a different random number from rand. Use Random’s nextInt() method and pick a number between 0 and one less than GRIDSIZE.

  5. While the terrain element at pickRow and pickCol has a hole, use rand to pick new random numbers for pickRow and pickCol. Use TerrainButton’s hasHole() method and Random’s nextInt() method.

  6. After the while loop, set the hole for the terrain element at pickRow and pickCol to true. Use TerrainButton’s setHole() method.

  7. Reveal the terrain element just set to a hole, so you can see whether your code really hides holes in 10 squares. Use TerrainButton’s reveal() method.

    ...
 
  ______________ setHoles() {
    ________ rand = ________________;
    for (________________) {
      ______ pickRow = _________________;
      ______ pickCol = _________________;
      while (____________________) {
        pickRow = _______________;
        pickCol = _______________;
      }
      terrain[____][____].____________;
      terrain[____][____].____________;
    }
  }
    ...

Get hands-on with 1200+ tech skills courses.