Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1
ScreenSize variable:

Click here to view code image


ScreenSize = ScreenWidth,ScreenHeight = 1000,700
By adding ScreenWidth and ScreenHeight in the middle of the variable
assignment, you essentially create two additional variables in one assignment
statement! These variables are needed in the next small change to the game script.


  1. To keep the image on the screen, change the ImageOffset variable at the
    appropriate time. To do this, under the .move method for the Surface object
    GameImageLocation, add the following lines:


Click here to view code image


if GameImageLocation.left < 0 or GameImageLocation.right > ScreenWidth:
ImageOffset[0] = -ImageOffset[0]
if GameImageLocation.top < 0 or GameImageLocation.bottom > ScreenHeight:
ImageOffset[1] = -ImageOffset[1]
In essence, this little tweak causes the Raspberry Pi image to go the opposite
direction whenever it “hits” an edge of the game screen.


  1. Test your changes to the game script by exiting the editor, typing python3
    py3prog/script1902.py, and pressing Enter. You should see the Raspberry
    Pi image move and appear to bounce off the screen edges. Click anywhere in the
    game screen with your mouse to play a sound and end the game.

  2. Open script1902.py in a script editor again. To get a feel for what is meant by
    changing the image’s “speed,” change the ImageOffset variable as follows:
    ImageOffset=[50,50]

  3. Test the speed change to the game script by exiting the editor, typing python3
    py3prog/script1902.py, and pressing Enter. You should see the Raspberry
    Pi image move “faster” than it did before. Click anywhere in the game screen with
    your mouse to play a sound and end the game.

  4. Again open script1902.py in a script editor and change the ImageOffset
    variable back to its original setting, as follows:
    ImageOffset=[10,10]

  5. Add a collide point to force the user to click the Raspberry Pi image in order to end
    the game. To do this, change the for loop construct concerning the event so it looks
    as follows:


Click here to view code image


for event in pygame.event.get():
if event.type in (QUIT,MOUSEBUTTONDOWN):
if GameImageLocation.collidepoint(pygame.mouse.get_pos()):
ClickSound.play()
pygame.time.delay(300)
sys.exit()


  1. Test the collide point in the game script by exiting the editor, typing python3
    py3prog/script1902.py, and pressing Enter. Use your mouse to click
    anywhere in the game screen except on the Raspberry Pi image. Nothing should
    happen. Finally, click somewhere on the Raspberry Pi image to play a sound and end

Free download pdf