Here’s an animation using the turtle
module:
Python
import random
import turtle
WIDTH, HEIGHT = 600, 600
screen = turtle.Screen()
screen.tracer(0)
screen.setup(WIDTH, HEIGHT)
screen.bgcolor("black")
def run_animation(n_turtles=100):
SPEED = 1
# Create turtles
all_turtles = []
for _ in range(n_turtles):
the_turtle = turtle.Turtle()
the_turtle.shape("turtle")
the_turtle.color(
random.random(),
random.random(),
random.random(),
)
the_turtle.penup()
the_turtle.left(random.uniform(0, 360))
all_turtles.append(the_turtle)
# Move turtles with frame rate control
for _ in range(500):
for a_turtle in all_turtles:
a_turtle.forward(SPEED)
a_turtle.left(random.uniform(-10, 10))
screen.update()
run_animation(10)
turtle.done()
Don’t worry if you’re not familiar with this module. This code first sets up the screen and then runs a simple animation within the run_animation()
function.
This function creates a number of Turtle
objects and displays them as turtle sprites on the screen. Each one has a random color and faces a random direction.
The final part of run_animation()
moves each turtle forward and turns it by a random angle in each frame of the animation. There are 500
frames in this animation.
Run the code and try running it with 10
, 200
, and 1000
turtles in the animation by changing the argument you pass to run_animation()
.