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:
- the
x
andy
point where the box is centered - the
size
of the largest box - the outermost
color1
, - the alternating
color2
- the
Canvas
where the drawing should appear
Here is a chart of available cs1graphics colors
Table of Contents
- Extra Recursion Practice home
- Fruitful recursion w/ Turtle graphics (from lab11)
- Predicting outcome of recursive functions (non-fruitful)
- More practice problems: Recursive Graphics
- More practice problems: More fruitful Turtle Recursion