Lab Exercise 9: Making a Turtle
It would be nice to be able to mix turtle graphics and the Zelle graphics. So we're going to make our own turtle class that implements all of the standard turtle commands, but acts like a graphics object.
We're going to create a class called ZTurtle that stores the turtle state internally and implements forward, backward, right, left, and several other commands for modifying the turtle state.
Create a file called zturtle.py. Import the graphics and math
packages, then begin by starting a class definition for
First, we're going to map out the fields/state information a turtle
needs to keep. The turtle state information includes the following:
- Current heading
- Current position
- Current status of the pen (up, down)
- Current color
- Current width
Next, we're going to identify all the methods we want to write and
what their parameters ought to be. Some of the most important ones
- forward(self, distance) - moves the turtle forward by distance
- right(self, angle) - turns the turtle right by the given angle
- left(self, angle) - turns the turtle left by the given angle
- draw(self, win) - draws all of the lines into win
- undraw(self) - undraws all of the lines
- move(self, tx, ty) - moves all of the lines by (tx, ty)
- up(self) - raises the pen
- down(self) - lowers the pen
- Most of the functions are very simple to write (up, down, move, draw, undraw, right, left). For the right function, subtract angle from the current heading. For the left function, add it to the current heading. Go ahead and write these functions.
The forward function is a little more tricky, because it has to do
some geometry and take into account all of the turtle state
fields. The algorithm is as follows:
- Calculate the new location of the turtle, taking into account the
current position and orientation.
xnew = xold + distance * cos( heading )
ynew = yold - distance * sin( heading )
If the turtle is down:
- Create a line from (xold, yold) to (xnew, ynew)
- Set the width of the line
- Set the color of the line
- Append the line to the shapes list
- Update the stored location of the turtle
- Calculate the new location of the turtle, taking into account the current position and orientation.
- Once you have these functions written, write a test function that creates a window, creates a Turtle object, executes some turtle commands and then draws the turtle object. An octagon is a good way to start.
Now you have a turtle class that can draw stuff in a Zell graphics window. We'll start to make use of it next week with our L-system class.
Once you've finished the above exercise, keep going on the current project.