Creating Algorithms to Draw Polygons

Do this on pencilcode.net

We will develop algorithms to draw polygons using turtle graphics. Turtle graphics were developed by Seymour Papert in 1967 to create algorithmic art by moving a geometric "turtle."

Five Basic Turtle Commands

With turtle graphics, you have the following Primitive functions:

pen red  Selects a line color for drawing (pen null to switch to no-color later).
fd 100  Moves the turtle forward by some pixels.
rt 90  Pivots the turtle right by some degrees.
lt 90  Pivots the turtle left by some degrees.
bk 100  Slides the turtle back by some pixels.

There are other turtle primitives, but these five are already enough to do a lot. Here is a house:

A Little Blue House

pen blue
fd 50
rt 90
bk 10
lt 45
fd 60
lt 90
bk 60
lt 45
fd 10
lt 90
fd 50

Warming Up: Create Your own Program

Go to pencilcode.net and create your own program to test out turtle graphics.

  1. Invent your own shape, using all five primitives.
    1. Figure out how to save your work under your own account.
    2. Give your program a meaningful name.
    3. What is the URL for your creation? ________________________________________________

Some tips:

Polygons: Square, Triangle, and Pentagon.

Now create programs to make a square, an equilateral triangle, and a regular pentagon. Save them using the names "square", "triangle" and "pentagon".

Since a square has four corners and four sides, it should take no more than 4+4=8 commands to draw a square after choosing a pen color. Similarly, a triangle should take no more than six steps after picking a pen, and a pentagon should take no more than ten steps after the pen.

# Purple square
pen purple   
fd 50        
rt 90        
             
             
             
             
             
             
# Orange triangle
pen orange   
fd 100       
             
             
             
             
             
pen orange
for [1..3]
  fd 100
  rt 120
# Green pentagon
pen green    
             
             
             
             
             
             
             
             
             
             

Even though our triangle has a smaller angle, the turtle must pivot a larger number of degrees to make that angle. The reason is that turtle motions are measured using exterior angles.

Read about exterior angles on Google if you do not remember what they are.

Exercises: (Review your geometry knowledge!)

  1. Write programs for the three regular polygons above, using only the primitives pen, fd and rt. Include final turns to return the turtle to its starting direction in each program.
  2. The interior angle of an equilateral triangle is 60°, but the turtle turns by an exterior angle. The measure of the exterior angle is: ________ degrees.
  3. The sum of all three exterior angles of an equilateral triangle is: _______ degrees.
  4. The sum of all four exterior angles of a square is: ________ degrees.
  5. The sum of all five exterior angles of a regular pentagon is: _______ degrees.
  6. The formula for an exterior angle of a regular polygon with N corners is: ___________

Simplifying an Algorithm with Loops

Remember that an algorithm can be written with Primitives, Control flow, Memory, and Arithmetic. So far we have been able to make fine drawings using only Primitives: why use anything else?

Here is a simple loop using for to demonstrate Control flow in CoffeeScript:

pen crimson
for [1..4]    # This line controls the indented block below.
  fd 50       # This indented line is repeated 4 times.
  rt 90       # This indented line is also repeated 4 times.

The result is a square again, but with a shorter program.

Indenting Under a for in CoffeeScript

The for keyword repeats a block of code once for each number in a range we provide. To use for we do the following:

  1. Indent the lines code to be repeated.
  2. At the top of the indented block, add (unindented) for [1..4] to repeat 4 times.
  3. Be sure to use square braces and two periods between 1 and 4.

In CoffeeScript, indenting is important! The program will not run correctly if you do not line up the indenting neatly.

Drawing Faster and Filling Shapes

Here are two more turtle primitives for solving common problems:

speed 10  speed 10 sets the turtle speed to 10 moves per second. speed Infinity works.
pen path 
fill purple 
pen path makes the turtle trace out an invisible path. Later, fill purple fills the invisible path with color.

Exercises:

  1. Which written description of a square is easier to understand: A, or B? _______
    1. "A shape with a side and a corner and an equal side and an equal corner and another equal side and another equal corner and another equal side and another equal corner."
    2. "A shape with four equal sides and corners."
  2. Use the for [1..n] technique to simplify your triangle and pentagon programs. How many lines of code are in each program now? _______
  3. Write a program to draw a regular polygon with 30 corners. Use speed 10.
    How many lines is your program? _______
  4. Save a program called "stopsign" that quickly draws a solid red octagon. Use speed Infinity and fill red.

Generalizing an Algorithm Using Variables

Variables can let us generalize an algorithm. Consider a polygon algorithm that defines a variable n to be the number of corners:

n = 6         # n is the number of corners.
k = plum      # k is the color
a = 60        # a is the size of an exterior angle.

speed Infinity
pen path
for [1..n]    # Loop n times:
  fd 50       # Move by 50 pixels.
  rt a        # Turn by a degrees.
fill k

Wherever the program needs to know the number of corners, it uses n instead of the number.

The code above defines three variables n, a, and k, and uses them instead of numbers and colors.

Using Arithmetic To Compute Side-Length

To draw a 10-sided polygon, we would just alter n to be 10 and a to be 36 degrees.

When we add more sides, the polygon gets too big to be useful. Instead of always using fd 50, it might be more convenient to specify the target perimeter, and automatically adjust the lengths based on the number of corners. Some simple arithmetic does the trick:

n = 10
k = skyblue
a = 36
p = 300       # p is the desired perimeter.

speed Infinity
pen path
for [1..n]
  fd p / n    # This will calculated to be 30.
  rt a
fill k

Exercises: Writing Elegant Algorithms for Polygons

  1. Create a program similar to the examples on this page, but eliminate the variable a and compute the needed angle automatically. Save the program as "polygon".
  2. Turning the turtle a total of 360 degrees returns it to its original direction. Make a similar program that turns the turtle a total of 2×360=720° instead. What shapes do you get with 3, 4, 5, and 7 corners?
3:5:
4:7: