Hardware Reference
In-Depth Information
hese instructions modify the value of the
changeDirection
variable, used to control the
direction the player's snake is travelling during the game. Using
or
with an
if
statement
allows more than one evaluation to be made. In this case, it provides two ways of controlling
the snake: the player can use the cursor keys, or the W, A, S and D keys to make the snake go
up, right, down or left. Until a key is pressed, the snake travels to the right according to the
value set for
changeDirection
at the start of the program.
If you look back at the variables you initialised at the start of the program, you'll see that
there's another variable called
direction
. his is used alongside
changeDirection
to see
if the instruction the user has given is valid. he snake should not be allowed to turn imme-
diately back on itself—if it does, the snake dies and the game is over. To prevent this from
happening, the direction requested by the player—stored in
changeDirection
—is com-
pared to the current direction in which the snake is travelling—stored in
direction
. If
they are opposite directions, the instruction is ignored and the snake continues in the same
direction as before. Type the following lines to set up the comparisons:
if changeDirection == 'right' and not Æ
direction == 'left':
direction = changeDirection
if changeDirection == 'left' and not Æ
direction == 'right':
direction = changeDirection
if changeDirection == 'up' and not Æ
direction == 'down':
direction = changeDirection
if changeDirection == 'down' and not Æ
direction == 'up':
direction = changeDirection
With the user's input checked to make sure it makes sense, the snake—which appears on the
screen as a series of blocks—can be moved. During each turn, the snake moves a distance equal
to the size of one of its blocky segments. With each segment measuring 20 pixels, you can tell
pygame to move the snake a single segment in any direction. Type in the following code:
if direction == 'right':
snakePosition[0] += 20
if direction == 'left':
snakePosition[0] -= 20
if direction == 'up':
snakePosition[1] -= 20
if direction == 'down':
snakePosition[1] += 20