Hardware Reference
In-Depth Information
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 final 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 defined 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. This takes
place in an infinite loop—a while loop that never exits. This 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.
Continue the program with the following lines, paying attention to the indentation levels:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
The first line, which comes right after the while loop begins, should be indented four spaces—
but it's a loop of its own, using a for instruction to check for pygame events like key presses. As a
result, the line under that needs to be indented an additional four spaces for a total of eight—but
that line, too, is a loop, using an if instruction to check whether the user has pressed a key. As a
result, the next line— pygame.quit() —is indented an additional four spaces for a total of 12
spaces. This logical progression of indentation tells Python where each loop begins and ends,
which is important: if the wrong number of spaces is used, the program won't work correctly. This
is why using a development environment like IDLE, which attempts to automatically indent code
where required, can be easier than using a plain text editor to create Python programs.
An if loop tells Python to check to see if a particular evaluation is true. The first check, if
event.type == QUIT , tells Python to execute the indented code below if pygame reports
Search WWH ::




Custom Search