To accompany this book, I have written a suite of modules called Swampy. One of these modules is TurtleWorld, which provides a set of functions for drawing lines by steering turtles around the screen.
You can download Swampy from http://thinkpython.com/swampy; follow the instructions there to install Swampy on your system.
Move into the directory that contains TurtleWorld.py, create a file named polygon.py and type in the following code:
from TurtleWorld import *
world = TurtleWorld()
bob = Turtle()
print bob
wait_for_user()
The first line is a variation of the import statement we saw before; instead of creating a module object, it imports the functions from the module directly, so you can access them without using dot notation.
The next lines create a TurtleWorld assigned to world and a Turtle assigned to bob. Printing bob yields something like:
<TurtleWorld.Turtle instance at 0xb7bfbf4c>
This means that bob refers to an instance of a Turtle as defined in module TurtleWorld. In this context, “instance” means a member of a set; this TurtleWorld is one of the set of possible TurtleWorlds.
wait_for_user tells TurtleWorld to wait for the user to do something, although in this case there’s not much for the user to do except close the window.
TurtleWorld provides several turtle-steering functions: fd and bk for forward and backward, and lt and rt for left and right turns. Also, each Turtle is holding a pen, which is either down or up; if the pen is down, the Turtle leaves a trail when it moves. The functions pu and pd stand for “pen up” and “pen down.”
To draw a right angle, add these lines to the program (after creating bob and before calling wait_for_user):
fd(bob, 100)
rt(bob)
fd(bob, 100)
The first line tells bob to take 100 steps forward. The second line tells him to turn right.
When you run this program, you should see bob move east and then south, leaving two line segments behind.
Now modify the program to draw a square. Don’t turn the page until you’ve got it working!