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

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

while keep_going: # Game loop
for event in pygame.event.get():
u if event.type == pygame.QUIT:
keep_going = False


Our game loop will keep running as long as keep_going is True.
Inside the loop, we immediately check for events from the user. In
advanced games, the user can trigger a lot of events at the same
time, like pressing the down arrow on the keyboard while moving
the mouse left and scrolling the mouse wheel.
In this simple program, the only event we’re listening for is
whether the user clicked the close window button to quit the pro-
gram. We check for this at u. If the user triggered the pygame.QUIT
event by trying to close the window, we want to tell our game loop
to exit. We do this by setting keep_going to False.
We still need to draw our picture to the screen and update the
drawing window to make sure everything appears on the screen,
so we’ll add these two final lines to our game loop:

screen.blit(pic, (100,100))
pygame.display.update()

The blit() method draws pic, the image that we’ve loaded
from disk (our smiley face), onto our display surface, screen. We’ll
use blit() when we want to copy pixels from one surface (like the
image we loaded from disk) onto another (like the drawing win-
dow). Here, we need to use blit() because the pygame.image.load()
function works differently than the pygame.draw.circle() function we
used earlier to draw our green dot. All pygame.draw functions accept
a surface as an argument, so by
passing screen to pygame.draw
.circle(), we were able to have
pygame.draw.circle() draw to our
display window. But pygame.image
.load() doesn’t take a surface as an
argument; instead, it automatically
creates a new, separate surface
for your image. The image won’t
appear on the original drawing
screen unless you use blit().
Free download pdf