Hardware Reference
In-Depth Information
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:
he irst 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. his 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. his
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. he irst check,
if
event.type == QUIT
, tells Python to execute the indented code below if pygame reports
a
QUIT
message (which happens when the user presses the Escape key). he two lines
beneath that should be familiar from the
gameOver
function: they tell pygame and Python
to close down and exit.
he line beginning
elif
is used to extend
if
loops. Short for
else if
, an
elif
instruction is
evaluated when a previous
if
instruction was found to be false. In this case, the
elif
instruction is used to see if pygame is reporting a
KEYDOWN
event, which is returned when
the user is pressing a key on the keyboard. As with the
if
instruction, code to be executed
when an
elif
is true should be indented by an additional four spaces plus whatever inden-
tation the
elif
instruction itself has. Type the following lines to give the
elif
instruction
something to do when the user presses a key:
if event.key == K_RIGHT or event.key == ord('d'):
changeDirection = 'right'
if event.key == K_LEFT or event.key == ord('a'):
changeDirection = 'left'
if event.key == K_UP or event.key == ord('w'):
changeDirection = 'up'
if event.key == K_DOWN or event.key == ord('s'):
changeDirection = 'down'
if event.key == K_ESCAPE:
pygame.event.post(pygame.event.Event(QUIT))