BFOIT

  Introduction to Programming  

Iteration and Animation


Introduction

We worked our way through defining procedures in the last lesson so that our programs could be built in small, understandable pieces.  The smaller your programs are, the less you type, and the better chance your program will do what you want it to do.  In this lesson, you are going to learn about another powerful mechanism for writing smaller programs: iteration.

As you write more and more TurtleTalk, you should notice that to do certain things your code repeats similar patterns.  Programming involves recognizing these patterns.  There are a couple of ways to reduce the amount of duplicate TurtleTalk commands your programs contain.  Iteration is one which we cover in this lesson. 

We'll end the lesson with an introduction to animation.  Animation is everywhere in the digital world.  On the index page for these lessons there is a Java applet that draws a maze and then solves it.  It shows off the solution via animation.  In this lesson you will learn how to perform simple animation.


Drawing a Circle, Step by Step, One Point at a Time

You might think that drawing a circle requires knowing geometry or trigonometry - subjects which you may not have had in school yet.  Don't worry if you haven't mastered these subjects, that's not going to stop you from getting the turtle to draw a circle in this lesson.  We'll figure out how to do it the same way we solve many programming puzzles - we'll start by working with things we know how to do.

Here are a couple of definitions of a circle:

A closed plane curve every point of which is equidistant from a fixed point within the curve (Webster's New Collegiate Dictionary).

A circle is the set of all points in a plane at a fixed distance from a fixed point in the plane (www.math.psu.edu).

Let's look at some pseudo-code that instructs the turtle to draw a bunch of points that are all the same distance from the center of TurtleWorld. 

Here is pseudo-code from an experienced programmer.

   1. pick up the pen so it's not leaving a trace
   2. move some number of steps forward, for example: 100
   3. put the pen down so it will draw
   4. move a few steps forward to make a little mark
   5. pick up the pen so it's not leaving a trace
   6. return to the center
   7. turn a bit to the right
   8. repeat steps 2 through 7 until the turtle is back to
      its original heading - it has rotated 360 degrees
  

Ok, it's up to you to convert this to TurtleTalk commands and see if it works. 

Here is the TG applet for you to use.

alt="Your browser understands the <APPLET> tag but isn't running the applet, for some reason." Your browser is completely ignoring the <APPLET> tag!
TurtleGraphics Applet

Tip: the left mouse buttom can be used to change the heights of the graphics and editing areas.  Hold the left mouse button down while on the separator bar between them and drag it up or down.  Give yourself more editing space when you are entering the instructions, less when you want to see the full results in the graphics area.

I think what you will find is that it works, but it is going to take a lot of typing.  A LOT of typing.  Too much typing. 

If you decided to to take the procedural abstraction approach you learned in the last lesson, you had to do a lot less typing.  Here's one way, showing what I mean.


   to pointOut100
     setpensize 20
     penup forward 90 pendown forward 20
     penup back 110
     end

   to main
     pointOut100 right 10
     pointOut100 right 10
     ...repeated 36 times...
     end

There is one TurtleTalk command in this code that you haven't seen (unless you've visited Appendix B) - the setpensize command.  It takes an integer as an input and sets the width of the line drawn by the pen to be this number of steps.  By setting the width of the pen to 20 steps and using it to draw a line 20 steps long, i get a big square, or... a big point!

But, there are often many ways to write a program to do something.


Walking in a Circle

Back in the TurtleTalk Commands lesson, after I introduced the language, I gave you the commands that drew a square.  It was then up to you to explore putting together TurtleTalk commands to draw a triangle, a pentagon, a hexagon and an octagon.

What does all of this have to do with drawing a circle?  Well, think about it... the more sides you added to your figures, the more closely they resemble a circle.  Watch for yourself.

It looks like we are on to something.  So, our first theory is that if we continue to increase the number of sides in our figure, eventually it will look like a circle.  My guess is that by the time you get up to 24 or 36 sides, we'll have a pretty good circle. 

Here are TurtleTalk commands that draw a triangle, a square, and a pentagon:

Triangle Square Pentagon
forward 100 forward 90 forward 80
right 120 right 90 right 72
forward 100 forward 90 forward 80
right 120 right 90 right 72
forward 100 forward 90 forward 80
right 120 right 90 right 72
  forward 90 forward 80
right 90 right 72
  forward 80
right 72
Table 4.1

Look how much is common to these three lists of TurtleTalk commands.  As I mentioned in the introduction, you need to discover patterns that appear in the programming process.

  1. the number of forward commands used to draw each of the figures is equal to the number of sides in the figure,
  2. the number of right commands used to draw each of the figures is equal to the number of corners in each figure,
  3. the number of steps we tell the turtle to move in every forward command for each figure are the same amounts (example: for the triangle, every forward command specifies 100 turtle steps),
  4. the number of degrees we tell the turtle to rotate in every right command for each figure are the same amounts (example: for the square, every right command specifies 90 degrees),

The only three things that are different in the lists are:

  1. the distance we tell the turtle to move,
  2. the number of degrees we turn the turtle between the forward commands, and
  3. the two extra commands (forward and right) it took to draw the square, and the four extra commands (again, forward and right) it took to draw the pentagon.

Either go back up to the TG applet or click here to start up a separate page with the applet on it.  Use one of these to type in procedures for the code in Table 4.1, i.e., define procedures tri100, sqr90, and pent80.  Invoke them to make sure they do what you think they should do.  Then, answer the following questions:

What happens if you change the number of turtle steps
specified on the forward commands?


What happens if you change the number of degrees
specified on the right commands?


What rules must be followed in order for the turtle
to end up just like it started, i.e., at the same
point in TurtleSpace,
pointing in the same direction as when it started?


Summary of Drawing a Circle with TurtleTalk

By now, you've completed the first phase in working through drawing a circle: Understanding the problem.  Now it is up to you to devise a plan you'll use to write a procedure that instructs the turtle to draw a circle.  You should now know two ways to get the turtle to draw a circle in the TurtleTalk language.  The problem is that both approaches take a LOT of typing.

The first way we approached the problem requires drawing points some distance from the center of the circle.  If you refer back to the pseudo-code for this approach, you will see that if we draw one point for each degree in a circle, it will take 2,161 TurtleTalk commands (assuming each step of pseudo-code translates into a single TurtleTalk command).  If you define a procedure that performs steps 2 - 7, you can reduce your program to 370 TurtleTalk commands.  By defining procedures that contain other procedures you can reduce total number of TurtleTalk commands.  But, there's got to be a better way.

For our other approach, where we have the turtle continually walk a bit forward and then turn a little bit, a regular polygon with 36 sides will take 72 TurtleTalk commands.  This is much less typing, but still too much...

There's a much better way to reduce the TurtleTalk commands needed; it's called iteration.  Let's learn about it now.


Iteration, aka Repeating Something

In the Summary of the "TurtleTalk Commands" lesson, I emphasized that the sequence that the steps in our programs get done in is extremely important.  In the TurtleGraphics applet (or TG application), TurtleTalk commands (the steps in your program) are executed left to right on each line after you press the [Enter] key. 

Well, TurtleTalk has a way of repeating the interpretation of a list of instructions.  The syntax of the TurtleTalk repeat command is:

   repeat       <number>       <List-of-Instructions>   

  1. the command name: "repeat"
  2. a number, and
  3. a <List-of-Instructions>

And, the syntax of a <List-of-Instructions> is:

   [       <TurtleTalk-Instructions>       ]   

  1. an open square bracket,
  2. TurtleTalk Instructions, and
  3. a close square bracket

For example, here are TurtleTalk repeat commands to draw a triangle and a square:

   repeat       3       [       forward 100 right 120       ]   
   repeat       4       [       forward 90 right 90       ]   


Watching Iteration in the Execution of TurtleTalk

Here is a small TurtleTalk program which draws a circle the way I first described.  It draws a bunch of fat points equally distant from the center.  Watch how the program gets executed, step by step.  Especially watch how repeat's count gets decremented after each time its List-of-Instructions is executed.

alt="Your browser understands the <APPLET> tag but isn't running the applet, for some reason." Your browser is completely ignoring the <APPLET> tag!


Animation - Moving an Object Across the Graphics Window

Either go back up to the TG applet or use either a small popup TG applet or a a big popup TG applet to try out the following instructions.

    hideturtle setpensize 10 setpencolor 4
    repeat 15 [ fd 10 wait 500 setpencolor 7 bk 10 fd 10 setpencolor 4 ]
    repeat 15 [ bk 10 wait 500 setpencolor 7 fd 10 bk 10 setpencolor 4 ]
So, moving a 10x10 turtle-step box up/down the screen is just iteration of the steps:
  1. draw something,
  2. pause for some amount of time,
  3. erase what was drawn,

  4. move a bit, and go back to step 1.


Exercise: JumpinJack

Ok.  Figure 4.4 shows three different positions of a stick figure performing jumping jack exercises.

#1 #2 #3
Figure 4.4

Here is the TurtleTalk source code for JumpinJack #1.  It's up to you to write procedures: arms2, arms3, legs2, legs3, fig2, fig3 and then modify main such that it iterates through the three figures to animate Jack...


    to arms1
      setpensize 8
      forward 25
      right 45 forward 50 back 50
      left 90 forward 50 back 50
      right 45
      back 25
      end

    to body
      setpensize 16
      forward 60 back 80 forward 20
      end

    to head
      penup forward 45 pendown
      setpensize 10
      repeat 12 [forward 16 back 16 left 30]
      back 45
      end

    to legs1
      setpensize 8
      back 15
      right 135 forward 60 back 60
      right 90 forward 60 back 60
      left 225
      forward 15
      end

    to fig1
      head
      body
      arms1
      legs1
      end

    to main
      home hideturtle clean setheading 0
      fig1
      end

    main


Additional Exercises

  1. Write a program which draws a circle as a regular polygon with enough sides for it to appear to be a circle.  This is the second way I described how a circle can be drawn with TurtleTalk.
  2. Take a look at the arc in the following figure.  This particular arc is one quarter of a circle.  Now take a close look at the plant with a flower.  You've learned how to draw a circle in this lesson.  Now write a bunch of procedures which instruct the turtle to draw a plant that looks like the one in Figure 4.1b.

    a. Arc b. Plant With Flower
    Figure 4.1

  3. A solid-colored box can be drawn as a bunch of parallel lines.  Draw a box that is 100 turtle steps on each side and filled in a solid red color.  Figure 4.2 shows the desired results.

    Figure 4.2 (Solid-red Box - 100 TurtleSteps on a Side)

  4. Write a bunch of procedures which draw a brick wall.  Like the previous exercise, the heart of your program will be two procedures which draw a brick and a half-brick.  These should be used in two procedures, one draws a line of whole bricks and the other draws a line starting and ending with a half brick.  Put it all together with a main procedure.  See Figure 4.3 for an example of the expected drawing.
  5. Figure 4.3 (Brick Wall)


Summary

Iteration - repeating something a some number of times - is a powerful way to reduce the size of a computer program.  The something may not be obvious when you start programming; it can be a pattern you recognize when you are typing in your programs.  So, look closely for patterns in the code you write.  As you get more and more experience writing programs, you'll start to think about iteration as a basic building block of programming.

Drawing a circle as a 72-sided regular polygon takes 144 TurtleTalk commands without using iteration.  But, putting 2 TurtleTalk commands inside a repeat TurtleTalk command will achieve the same results!


New TurtleTalk Procedures Used In This Lesson
Name Input(s) Description Example
REPEAT count
instructionList
The instructionList input is performed the number of times specified by the count input. REPEAT 4 [ FD 100 RT 90 ]
SETPENSIZE
SETPS
number Sets the width of the turtle's pen, which determines the thickness of the trace it leaves, the line it draws. SETPS 5
WAIT number Performing instructions is suspended for the number of milliseconds (1/1000s of a second). WAIT 1000


Back to Table of Contents
Back to previous Lesson ( TurtleTalk Procedures )
On to next Lesson ( TurtleTalk Procedure Inputs )