User Interaction: Get into the Game 223
while keep_going:
for event in pygame.event.get():
if event.type == pygame.QUIT:
keep_going = False
if event.type == pygame.MOUSEBUTTONDOWN:
mousedown = True
if event.type == pygame.MOUSEBUTTONUP:
mousedown = False
screen.fill(BLACK)
u sprite_list.update()
v sprite_list.draw(screen)
clock.tick(60)
pygame.display.update()
if mousedown:
speedx = random.randint(-5, 5)
speedy = random.randint(-5, 5)
w newSmiley = Smiley(pygame.mouse.get_pos(),speedx,speedy)
x sprite_list.add(newSmiley)
pygame.quit()
The code for the game loop in SmileyExplosion.py is similar to
our drawing app DragDots.py, with a few notable changes. At u,
we’re calling the update() function on the list of smiley sprites
stored in sprite_list; this single line will call the update func-
tion to move every smiley face on the screen and check for edge
bounces. Similarly, the code at v will draw every smiley face on
the screen in its proper location. It takes only two lines of code to
animate and draw potentially hundreds of sprites—that’s a huge
time savings, and it’s just part of the power of sprite graphics in
Pygame.
In our mousedown drawing code, we generate a random speedx
and speedy for the horizontal and vertical speed of each new smiley
face, and at w, we create a new smiley face, newSmiley, by call-
ing the constructor for our class Smiley. Notice that we don’t have
to use the function name __init__(); rather, we use the name of
the class, Smiley, whenever we’re constructing or creating a new
object of the Smiley class or type. We pass the constructor func-
tion the position of the mouse, along with the random speed we
just created. Finally, at x, we take our newly created smiley face
sprite, newSmiley, and add it to our Group of sprites called sprite_list.
We’ve just created a fast, fluid, interactive animation for dozens
or even hundreds of smiley face sprite graphics, floating around the
screen like balloons of various sizes, traveling at random speeds