Teach Your Kids To Code: A Parent-friendly Guide to Python Programming

(vip2019) #1
Timers and Animation: What Would Disney Do? 185

while keep_going: # Game loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
keep_going = False
screen.blit(pic, (100,100))
pygame.display.update()

pygame.quit() # Exit

When you click the close window button, the display window
should close.
This code has all the basic components we’ll build on to make
our programs even more interactive. In the rest of this chapter and
in Chapter 9, we’ll add code to our game loop to respond to differ-
ent events (for example, making images on the screen move when
the user moves the mouse). Now let’s see how to create a program
that draws an animated bouncing ball!

Timing It Just Right: Move and Bounce


We already have the skills needed to create animation, or the illu-
sion of motion, by making one small change to our ShowPic.py
app. Instead of showing the smiley face image at a fixed location
every time through the game loop, what if we change that loca-
tion slightly every frame? By frame, I mean each pass through the
game loop. The term comes from one way people make animations:
they draw thousands of individual pictures, making each picture
slightly different from the one before it. One picture is considered
one frame. The animators then put all the pictures together on
a strip of film and run the film
through a projector. When the pic-
tures are shown one after another
very quickly, it looks like the char-
acters in the pictures are moving.
With a computer, we can cre-
ate the same effect by drawing a
picture on the screen, clearing the
screen, moving the picture slightly,
and then drawing it again. The
effect will look a bit like Figure 8-5.
Free download pdf