Lab 11: Part 3: Recursive Graphics

Task 0. Study template file

Open lab11/recursiveGraphics.py and study the provided box function:

def box(x, y, size, color1, canvas):
    b = Rectangle(size, size, Point(x, y))
    b.setFillColor(color1)
    canvas.add(b)

This function draws a single box (Rectangle) of side length size, centered at (x, y), filled with the color color1. The resulting box is added to the given cs1graphics Canvas (canvas).

This function is then tested in the main block:

if __name__ == '__main__':

    # TEST FUNCTIONS HERE

    labcanvas = Canvas(500, 500, 'ivory', 'Example 1')
    box(100, 160, 200, 'green', labcanvas)
    box(300, 250, 200, 'red', labcanvas)
    box(50, 350, 75, 'blue', labcanvas)

Producing a graphic that looks like this:

Task 1. nested boxes

Write a recursive function makeNestedBoxes(x, y, size, color1, color2, canvas) that produces nested boxes of alternating colors.

The largest box is drawn first, filled with color1, and then the next box has a side length that is 10 smaller and is filled with color2, etc.

This pattern continues as long as the size of the box is greater than 10.

Your makeNestedBoxes function must be recursive.

Invocations to test your nested boxes:


if __name__ == '__main__':
    task2canvas = Canvas(500, 500, 'darkolivegreen')
    makeNestedBoxes(200, 400, 100, 'red', 'ivory', task2canvas)
    makeNestedBoxes(150, 100, 200, 'purple', 'gold', task2canvas)
    makeNestedBoxes(400, 200, 180, 'navy', 'lightskyblue', task2canvas)

Task 2. box pattern

Building upon the makeNestedBoxes function above, this task adds smaller versions of nested boxes at each of the four corners of every box.

The ratio of a box size to the corner box size is 1:3. The corner boxes can only be drawn when they have a size greater than or equal to 10. Your nestedBoxPattern function must be recursive.

Hint: start with only one corner box (e.g. upper left), and when that works, go back and add in the other 3 corner boxes.

The patterns above were generated by the following code:

if __name__ == '__main__':

    paper2 = Canvas(600, 600, 'white', 'paper2')
    nestedBoxPattern(300, 300, 400, 'navy', 'ivory', paper2)

    paper3 = Canvas(1500, 1500, 'black', 'paper3')
    nestedBoxPattern(750, 750, 500, 'deeppink', 'slategray', paper3)

nestedBoxPattern takes 6 parameters:

  1. the x and y point where the box is centered
  2. the size of the largest box
  3. the outermost color1,
  4. the alternating color2
  5. the Canvas where the drawing should appear

Here is a chart of available cs1graphics colors

Table of Contents