196 Chapter 8
But that’s not all! Because our if statement is also checking
for the left screen boundary (picx <= 0), when our smiley face looks
like it has hit the left side of the screen, it will change speed to
-speed again. If speed is -5, this will change it to -(-5), or +5. So if
our negative speed variable was causing us to move to the left and
up 5 pixels every frame, once we hit picx <= 0 at the left edge of
the screen, speed = -speed will turn speed back to positive 5 , and the
smiley image will start moving to the right and down again, in the
positive x- and y-directions.
Putting it all Together
Try version 1.0 of our app, SmileyBounce1.py, to see the smiley face
bounce from the upper-left corner of the window to the lower-right
corner and back again, never leaving the drawing screen.
SmileyBounce1.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()
speed = 5
while keep_going: # Game loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
keep_going = False
picx += speed
picy += speed
if picx <= 0 or picx + pic.get_width() >= 600:
speed = -speed
screen.fill(BLACK)
screen.blit(pic, (picx,picy))
pygame.display.update()
timer.tick(60)
pygame.quit() # Exit