Hardware Reference
In-Depth Information
multiple points in the same program, using def to create a function means you'll only have
to type them once—and only have to change them in a single place if you alter the program
later. Type the following lines to deine the gameOver function:
def gameOver():
gameOverFont = pygame.font.Font Æ
('freesansbold.ttf', 72)
gameOverSurf = gameOverFont.render Æ
('Game Over', True, greyColour)
gameOverRect = gameOverSurf.get_rect()
gameOverRect.midtop = (320, 10)
playSurface.blit(gameOverSurf, gameOverRect)
pygame.display.flip()
time.sleep(5)
pygame.quit()
sys.exit()
As with loops, the code for a function should be indented. Every line after the def instruc-
tion should have four spaces at the start—if you're using IDLE, these spaces will be inserted
automatically, but if you're using a text editor, you will need to insert the spaces yourself.
After the inal line of the function— sys.exit() —you can stop indenting.
he gameOver function uses a selection of pygame's commands to perform a simple task:
write the words Game Over to the screen in a large font, pause for 5 seconds, and then quit
both pygame and Python itself. It may seem strange to set up the instructions for quitting
the game before the game has even begun, but functions should always be deined before
they are called. Python won't execute these instructions until it is told to do so using the
newly-created gameOver instruction.
With the beginning of the program complete, it's time to start the main section. his takes
place in an ininite loop—a while loop that never exits. his is so that the game can con-
tinue to run until the player dies by hitting a wall or eating his or her own tail. Begin the main
loop with the following line:
while True:
Without anything to evaluate, Python will check to see if True is true. Because that's always
the case, the loop will continue to run forever—or, at least until you tell Python to quit out
of the loop by calling the gameOver function.
Search WWH ::




Custom Search