CS111 Lab 6 Solutions -- InvertedTrianglesWorld

Understanding the pattern

How is the pattern drawn?

We build an inverted triangle pattern involving the specified number of equilateral triangles. We are given the initial size of the first triangle. Successive triangles have sides which are half the length of the surrounding triangle. Successive triangles are inverted and placed inside the surrounding triangle to touch it at three points.

What is the base case?

If the number of triangles is less than 1, do nothing.

How are consecutive calls to the pattern different?

invertTriangles(2) = equiTriangle + invertTriangles(1, inverted and size shrunk by half)
invertTriangles(3) = equiTriangle + invertTriangles(2, inverted and size shrunk by half)
invertTriangles(4) = equiTriangle + invertTriangles(3, inverted and size shrunk by half)
where equiTriangle is a method that will draw an equilateral triangle.

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

There are lots of possible solutions here. One thing we can do is to move half the size forward and then turn left 60 degrees.

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 need to turn right 60 degrees and move half the size backward to get back to the starting position.

Writing code

Writing the main recursive pattern method: invertTriangles()

We assume we have methods (defined below) which answer each of the questions above.
public void invertTriangles (double size, int number) {
  System.out.println("invertTriangles("+size+", "+number+");");
  if (number>0) {                       // base case
    equiTriangle(size);                 // draw the outer triangle
    moveToNextTriangle(size/2);         // move in position to draw the next triangle pattern
    invertTriangles(size/2, number-1);  // draw next pattern
    returnToStart(size/2);              // meet invariant: start and end in same place
  }
}

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

// draws an equilateral triangle with sides of the specified size
public void equiTriangle (double size) {
  System.out.println("equiTriangle size "+size);
  fd(size);
  lt(120);
  fd(size);
  lt(120);
  fd(size);
  lt(120);	
}

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

public void moveToNextTriangle (double distance) {
  System.out.println("moveToNextTriangle");
  fd(distance);
  lt(60);
}

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

public void returnToStart (double distance) {
  System.out.println("returnToStart");
  rt(60);
  bd(distance);
}