O'Reilly logo

Raspberry Pi For Dummies by Mike Cook, Sean McManus

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Making the Bat Move

Now we have all our functions in place, our starting screen drawn, and all our variables set up. It’s time to make the game loop, which repeats until the game is won, lost, or abandoned by the player closing the window.

Each run through the loop checks for keypresses, moves the bat if required, moves the ball (including changing its direction if it should bounce), knocks out bricks if necessary, updates the screen, checks if the player has won, and then pauses briefly to match your desired game speed.

Here’s the shell of the main loop, with all the bat controls included, but with a gap left for the ball movement instructions to be added later:

#main game loop

while True:

for event in pygame.event.get():

oldbat=batx

if event.type == QUIT:

endgame()

if event.type==KEYDOWN:

if event.key==K_RIGHT:

batx=batx+1

elif event.key==K_LEFT:

batx=batx-1

if batx==0 or batx==20:

batx=oldbat

clearbat(oldbat)

drawbat(batx)

# ball movement goes here

pygame.display.update()

if havetheywon()==True:

gamewon()

fpsClock.tick(FPS)

The instruction while True sets the loop up to run forever and is a construct that’s often used for loops you want to repeat indefinitely. The first thing that happens inside the while loop is that there is a for loop that works through Pygame’s list of events, which are things that happened like key presses or clicks on the window’s Close button. Each time around the for loop, the program checks the next event in the list.

First, we ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required