CS111 Lab 6 Solutions -- NestedWindowWorld

Understanding the pattern

How is the pattern drawn?

We build a nested window pattern involving the specified levels of nesting of windows. We are given the initial size of the first window. Each additional level of nesting puts windows in the bottom left and top right corner.

What is the base case?

If the number of nested window levels is less than 1, do nothing.

How are consecutive calls to the pattern different?

buildDiagonallyNestedWindows(2) = window + buildDiagonallyNestedWindow(1, shrunk and in the two corners)
buildDiagonallyNestedWindows(3) = window + buildDiagonallyNestedWindow(2, shrunk and in the two corners)
buildDiagonallyNestedWindows(4) = window + buildDiagonallyNestedWindow(3, shrunk and in the two corners)
where window is a method that will draw an square.

How do we move into position to draw the next pattern call?

There are lots of possible solutions here. We don't have to move anywhere to draw the nested pattern in the bottom left corner. One thing we can do to move into position to draw the pattern in the upper right corner is to move to the middle of the window. To do this, we would move forward half the size, turn left 90 degrees, move forward half the size and then turn right 90 degrees to get into position ready to draw the second nested pattern.

How do we meet the invariant, if any?

Invariant: We need to start and end the pattern in the same place.
If we move to the next position in the way specified above, we could go back to the starting position and direction by turning right 90 degrees, going forward half the size, turning right 90 degrees, going forward half the size, and then turning right 180 degrees.

Writing code

Writing the main recursive pattern method: buildDiagonallyNestedWindows()

We assume we have methods (defined below) which answer each of the questions above.
public void buildDiagonallyNestedWindows(double size, int levels) {
  System.out.println("buildDiagonallyNestedWindows("+size+", "+levels+");");
  if (levels>0) {
    window(size);
    buildDiagonallyNestedWindows(size/2,levels-1);	
    moveToNext(size/2);
    buildDiagonallyNestedWindows(size/2, levels-1);
    returnToStart(size/2);
  }
}

Writing a support method (extra design for each level): window()

// build a window (a square) with sides of the specified size
public void window(double size) {
 System.out.println("window size "+size);
  fd(size);
  lt(90);
  fd(size);
  lt(90);
  fd(size);
  lt(90);
  fd(size);
  lt(90);	
}

Writing a support method (move to position for next level): moveToNext()

public void moveToNext(double size) {
 System.out.println("moveToNext");
  pu();
  fd(size);
  lt(90);
  fd(size);
  rt(90);
  pd();	
}

Writing a support method (meet invariant): returnToStart()

public void returnToStart(double size) {
  System.out.println("returnToStart");
  pu();
  rt(90);
  fd(size);
  rt(90);
  fd(size);
  rt(180);
  pd();
}