Turtle Animation
More Than One Turtle
You can create as many turtles as you like. Each turtle has its own position, direction and color:
Example
Two turtles:
import turtle
red = turtle.Turtle()
red.color("red")
blue = turtle.Turtle()
blue.color("blue")
blue.left(90)
red.forward(100)
blue.forward(100)
turtle.done()
Result:
Each turtle is stored in its own variable, red and blue.
Move by Itself
Use ontimer() to run a function after a number of milliseconds. If the function sets a new timer for itself, it keeps running:
Example
A turtle that walks in a circle by itself:
import turtle
t = turtle.Turtle()
screen = turtle.Screen()
def move():
t.forward(5)
t.left(5)
screen.ontimer(move, 50)
move()
turtle.done()
Result:
After about 2 seconds:
move() moves the turtle a little, and asks to be run again after 50 milliseconds.
That is about 20 times per second, which looks like smooth movement.
Draw Everything at Once
Use tracer(0) to turn off the animation, and update() to show the finished drawing:
Example
Draw 36 lines at once:
import turtle
t = turtle.Turtle()
screen = turtle.Screen()
screen.tracer(0)
for i in range(36):
t.forward(120)
t.backward(120)
t.left(10)
screen.update()
turtle.done()
Result:
For big drawings, this is faster than speed(0), because the window is only updated once, at the end.
A Turtle Race
This example puts it together: two turtles, a function that creates them, and random steps from the random module:
Example
Race two turtles:
import turtle
import random
def racer(color, y):
t = turtle.Turtle()
t.color(color)
t.shape("turtle")
t.penup()
t.goto(-150, y)
t.pendown()
return t
red = racer("red", 30)
blue = racer("blue", -30)
for i in range(25):
red.forward(random.randint(1, 10))
blue.forward(random.randint(1, 10))
turtle.done()
Result:
Your race will look different, because the steps are random:
racer() creates a turtle, moves it to the start line, and returns it.
In each round of the loop, both turtles move forward a random number of pixels, from 1 to 10.
Run it a few times, and see which turtle wins!