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

(vip2019) #1

190 Chapter 8


SmileyMove.py

import pygame # Setup
pygame.init()
screen = pygame.display.set_mode([600,600])
keep_going = True
pic = pygame.image.load("CrazySmile.bmp")
colorkey = pic.get_at((0,0))
pic.set_colorkey(colorkey)
picx = 0
picy = 0
BLACK = (0,0,0)
timer = pygame.time.Clock() # Timer for animation

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

screen.fill(BLACK) # Clear screen
screen.blit(pic, (picx,picy))
pygame.display.update()
timer.tick(60) # Limit to 60 frames per second

pygame.quit() # Exit

The remaining problem is that the smiley still goes all the way
off the screen in a few seconds. That’s not very entertaining. Let’s
change our program to keep the smiley face on the screen, bounc-
ing from corner to corner.

Bouncing a Smiley Off a Wall


We’ve added motion from one frame to the next by changing the
position of the image we were drawing on each pass through our
game loop. We saw how to regulate the speed of that animation
by adding a Clock object and telling it how many times per second
to tick(). In this section, we’ll see how to keep our smiley on the
screen. The effect will look a bit like Figure 8-6, with the smiley
appearing to bounce back and forth between two corners of the
drawing window.
Free download pdf