Friday, June 10, 2011

A Turtle and his Pen

Pretty pictures are much more fun than words, and they give us something to watch to see if we have done the right thing. In our case, we watch a little arrow we call a turtle. The turtle draws a line wherever he goes. And the turtle goes wherever you tell him.

Let's start by drawing a square. We make it like this:
So first, we import our turtle code into our program. Then we make a turtle and put it in the variable t. A turtle has many functions. Two we use here are the fd() or forward and lt() or left functions. The numbers we put inside the parentheses tell the turtle how far to move or turn.

But we have to tell the turtle to do the same thing four times! Can't we just tell him to repeat it? Well, yes we can:
In this case, we tell the turtle to repeat using the for command. The range() function gives us a list of numbers from 1 to 4, and the turtle does the fd() and lt() below for each number.

Now let's make things more interesting. Say you wanted to make any shape and have the turtle draw it. We would have to do something like this:
Something different has happened here. The raw_input() function has been put inside the int() function. What's going on here? Well, raw_input() gets a number you type from the keyboard, and gives it to int(), which makes it a number and puts it in the variable s. That way, we can do math with s like dividing by using a /.

How do we make any shape. Well the turtle needs to turn all the way around, so it needs to go 360°. So we divide 360° by how many sides we have, and we want it to be about 400 units around, so we divide that by the number of sides too. Then we tell the turtle to move forward and turn left for all the sides we have.

No comments:

Post a Comment