8.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 that the turtle turns.

Any time we want to make a regular polygon, we need the turns to all sum up to \(360\). In the triangle example \(3 * 120 = 360\) and in the pentagon example \(5 * 72 = 360\).

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.

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.

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.

Once you have figured out the procedure, add it to the program below:

You have attempted of activities on this page