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.
- 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.
- 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. - 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] - 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. - Again open script1902.py in a script editor and change the ImageOffset
variable back to its original setting, as follows:
ImageOffset=[10,10] - 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()
- 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