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

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

Then, all we have to do in our game loop is change picx and
picy by this new speed amount (instead of the constant amount 1 )
every time through the loop:


picx += speed
picy += speed


One pixel per frame seemed a bit too slow at 60 frames per
second in SmileyMove.py, so I’ve increased the speed to 5 to make
it move faster. But we’re still not bouncing off the right edge of the
screen; we just move off the screen quickly again, because the speed
variable doesn’t change when we hit the edge of the screen.
We can solve that final problem by adding our collision detection
logic—that is, our test to see if we’ve hit the imaginary boundary at
the left or right edges of the screen:


if picx <= 0 or picx + pic.get_width() >= 600:
speed = -speed


First, we’re checking both the left and right boundaries of the
screen by seeing if picx is trying to draw at a negative x-coordinate
value (off the left of the screen where x < 0) or if picx + pic.get_
width() totals more than the 600-pixel width of the screen (meaning
the picture’s starting x-coordinate plus its width have gone off the
right edge of the screen). If either of these happens, we know we’ve
gone too far and we need to change the direction we’re going in.
Notice the trick we’re using if either of those boundary tests
evaluates to True. By setting speed = -speed, we’re changing the
direction of the movement in our while loop by multiplying speed
by –1, or by making it the negative of itself. Think of it this way:
if we keep looping with speed equal to 5 until our picx plus the
image’s width hits the right edge of the screen at 600 pixels (picx +
pic.get_width() >= 600), setting speed = -speed will change speed from 5
to -5 (negative five). Then, whenever our picx and picy change in the
next pass through the loop, we’ll add -5 to our location. This is the
same as subtracting 5 from picx and picy, or moving left and up on
our screen. If this works, our smiley face will now bounce off the
lower-right corner of the screen and start traveling backward, back
up to (0, 0) at the upper-left corner of the screen.

Free download pdf