Section 20.3 A Regular Polygon Recipe
You undoubtedly have recognized that there are some similarities to drawing shapes like the square or hexagon. It turns out there is a general pattern to drawing any regular (all sides are the same length and all angles are the same size) geometric shape.
Let’s look at a few more examples. Here’s a triangle:
And here’s a pentagon:
Notice that the only code that is “inside” the for
loop (indented after it) are the parts we want to repeat. We only want to end_fill
once, so it is not indented. It is not part of the code that is repeated.
The only two things that are different between the two programs are the number of repetitions in the loop and the angle the turtle turns.
Any time we want to make a regular polygon, we need the turns to all sum up to \(360\text{.}\) In the triangle example \(3
* 120 = 360\) and in the pentagon example \(5 * 72 = 360\text{.}\)
Change the ??
in line 7 below to the amount to turn each time to draw a 12-sided polygon (called a dodecagon). If you get it right the turtle will draw a 12-sided closed polygon.
Checkpoint 20.3.1.
How much does mia
need to turn in the program above to create a closed dodecagon (12-sided figure)? Only one of these works.
15
This one will not close
30
Exactly! 12 * 30 = 360
12
No, 12 * 12 is 144, which is not a multiple of 360
90
This one will generate a square, three times. 12 * 90 = 1080 = 360 * 3
Now that we have identified a pattern, it is a bit silly to write separate functions like square
and dodecagon
for all the shapes. They are all basically the same and we don’t like repeating ourselves.
In this case, the way to avoid repeating ourselves is to make an abstraction - a procedure that can draw any polygon
. It will take parameters to control how many sides there are and how long to make each side.
Checkpoint 20.3.2.
Arrange the blocks in the correct order and indentation to make the polygon
procedure. This procedure will use begin_fill
and end_fill
to make the shapes be colored.
Those commands do not need to be repeated - we only want to use each one once - so make sure they are not
You will not need to use all of them.
def polygon(turtleName, sides, size)
---
turtleName.begin_fill()
---
for s in range(sides):
---
for s in range(size) #paired
---
turtleName.forward(size)
---
turtleName.forward(sides) #paired
---
turtleName.left(360 / sides)
---
turtleName.turn(sides / 360) #paired
---
turtleName.end_fill()
Once you have figured out the procedure, add it to the program below:
You have attempted
of
activities on this page.