Skip to main content

Section 21.4 Lessons from a Triangle

OK, let’s look at what we have learned from writing a drawTriangle and drawOctagon function. The first thing you had to figure out was that you needed to modify the parameter to the range function based on the number of sides in the polygon. The next thing, and this may have been the most challenging part for you was to figure out how much to turn each time. The following table summarizes what you probably learned very nicely. If you didn’t, look at the table and then go back to the previous page and see if you can finish drawTriangle and drawOctagon.
Table 21.4.1.
Shape Sides range() Angle
Triangle 3 3 360/3 = 120
Square 4 4 360/4 = 90
Octagon 8 8 360/8 = 45
Looking at the table above you can really see that there is a pattern. If you know the number of sides you want, the rest can be figured out from there. This leads us to the next problem solving stage of this exercise, generalization. Why write a separate function for every kind of polygon when you can just write a single function that can be used to draw many different polygons?
Our new function drawPolygon will have three parameters, a turtle and the length of the side just like we have in the previous functions, but now we will add an additional parameter: numSides.
Here’s the starting point for the drawPolygon function, see if you can fill in the details on your own.
You have attempted 1 of 2 activities on this page.