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.
If the number of nested window levels is less than 1, do nothing.
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.
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.
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.
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); } }
// 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); }
public void moveToNext(double size) { System.out.println("moveToNext"); pu(); fd(size); lt(90); fd(size); rt(90); pd(); }
public void returnToStart(double size) { System.out.println("returnToStart"); pu(); rt(90); fd(size); rt(90); fd(size); rt(180); pd(); }