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

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

new version of the program as SmileyMove.py (the final version is
shown on page 190).

import pygame # Setup
pygame.init()
u screen = pygame.display.set_mode([600,600])
keep_going = True
pic = pygame.image.load("CrazySmile.bmp")
v colorkey = pic.get_at((0,0))
w pic.set_colorkey(colorkey)
picx = 0
picy = 0

noTe The lines at v and w are an optional fix for a minor issue. If the
CrazySmile.bmp image looks like it has square black corners on
your screen, you can include these two lines to make sure those
corners look transparent.


Notice that we’ve also changed our window screen to 600×600
pixels to make the window square at u. The game loop will begin
the same way it did in ShowPic.py, but we’ll add code to change
the picx and picy variables by 1 pixel every time the loop runs:

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

picx += 1 # Move the picture
picy += 1

The += operator adds something to the variable on the left
side (picx and picy), so with += 1, we’ve told the computer we want
to change the x- and y-coordinates of the picture, (picx, picy), by
1 pixel every time through the loop.
Finally, we need to copy the image onto the screen at the new
location, update the display, and tell our program what to do to exit:

screen.blit(pic, (picx, picy))
pygame.display.update()
pygame.quit() # Exit

If you run those lines, you’ll see our image take off! In fact,
you’ll have to look fast because it will move right off the screen.
Free download pdf