/* jquery */ /* jquery accordion style*/ /* jquery init */

Learn Python - Tom And Tim Stomp

Creating turtle called Tom was fun. But why stick with just one turtle?

Let's write a program that creates a pair of turtles, Tom and Tim, and control them both at the same time. Here's what you'll see...

Let's get coding. Open a new file in your editor and save it as turtle-pair.py, then type in the code below:

from turtle import *

# create Tom
tom = Turtle()
tom.shape("turtle")
tom.color("red")
tom.pencolor("red")
tom.penup()

# create Tim
tim = Turtle()
tim.shape("turtle")
tim.color("blue")
tom.pencolor("blue")
tim.penup()

# starting positions
tom.forward(150)
tim.backward(150)

# stomp around
dist = 8
for i in range(30):
  tom.stamp()
  tim.stamp()
  dist += 2
  tom.forward(dist)
  tom.right(24)
  tim.forward(dist)
  tim.right(24)

exitonclick()

After the import statement we have two code blocks that create Tom and Tim. These turtles have different body and pen colours.

Next we send the turtles to their respective starting positions. Notice that while Tim moves forwards, Tom moves backwards. This gives each turtle their own space to move around in. Once again we'll use the penup command to stop the turtles drawing.

Now we come to the main movement loop.

Inside the loop we've used the stamp command to leave a coloured impression of our turtles on the screen. The 'stamping' loop moves the turtles in a circular motion. The every increasing step distance is specified by the dist variable. We add two to this value every time the loop repeats.

Save the code, run the program and watch Tim and Tom perform some synchronised stomping!

A post from my Learn Python on the Raspberry Pi tutorial.