To accompany this book, I have written a package called Swampy. You can download Swampy from http://thinkpython.com/swampy; follow the instructions there to install Swampy on your system.
A package is a collection of modules; one of the modules in Swampy is TurtleWorld, which provides a set of functions for drawing lines by steering turtles around the screen.
If Swampy is installed as a package on your system, you can import TurtleWorld like this:
from swampy.TurtleWorld import *
If you downloaded the Swampy modules but did not install them as a package, you can either work in the directory that contains the Swampy ﬁles, or add that directory to Python’s search path. Then you can import TurtleWorld like this:
from TurtleWorld import *
The details of the installation process and setting Python’s search path depend on your system, so rather than include those details here, I will try to maintain current information for several systems at http://www.greenteapress.com/thinkpython/swampy/
Create a ﬁle named mypolygon.py and type in the following code:
from swampy.TurtleWorld import * world = TurtleWorld() bob = Turtle() print bob wait for user()
The ﬁrst line imports everything from the TurtleWorld module in the swampy package.
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 deﬁned in module TurtleWorld. In this context, “instance” means a member of a set; this Turtle is one of the set of possible Turtles.
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) lt(bob) fd(bob, 100)
The ﬁrst line tells bob to take 100 steps forward. The second line tells him to turn left.
When you run this program, you should see bob move east and then north, leaving two line segments behind.
Now modify the program to draw a square. Don’t go on until you’ve got it working!