Raspberry Pi A User Manual page 206

Hide thumbs Also See for Raspberry Pi A:
Table of Contents

Advertisement

190
This uses the
current position of the snake. Each time Python reaches this line, it will increase the length
of the snake's body by one segment, and locate that segment at the current position of the
snake's head. To the player, it will look as though the snake is growing. However, you only
want this to happen when the snake eats a raspberry—otherwise the snake will just grow
and grow. Type the following lines:
The first instruction checks the X and Y coordinates of the snake's head to see if it matches
the X and Y coordinates of the raspberry—the target the player is chasing. If the values
match, the raspberry is considered to have been eaten by the snake—and the
rySpawned
has not been eaten:
The
removes it, making the list one item shorter. In the case of the
Python to delete the portion of the snake's body farthest away from the head. To the player,
it will look as though the entire snake has moved without growing—in reality, it grew at one
end and shrank at the other. Because of the
when a raspberry has not been eaten. If a raspberry has been eaten, the last entry in the list
doesn't get deleted—so the snake grows in size by one segment.
At this point in the program, it's possible that the player has eaten a raspberry. A game in
which only a single raspberry is available is boring, so type the following lines to add a new
raspberry back to the playing surface if the player has eaten the existing raspberry:
This section of code checks to see if the raspberry has been eaten by testing if the
rySpawned
surface using the
then multiplied by the size of a snake's segment—20 pixels wide and 20 pixels tall—to give
P A R T I I I
P R O G R A M M I N G W I T H T H E R A S P B E R R Y P I
instruction to insert a new value into the
insert
if snakePosition[0] == raspberryPosition[0] ↵
and snakePosition[1] == raspberryPosition[1]:
raspberrySpawned = 0
else:
snakeSegments.pop()
variable is set to
the earliest value from the
pop
instruction is simple but clever: it returns the oldest value from the list but also
pop
if raspberrySpawned == 0:
x = random.randrange(1,32)
y = random.randrange(1,24)
raspberryPosition = [int(x*20),int(y*20)]
raspberrySpawned = 1
variable is set to
module you imported at the start of the program. This location is
random
. The
instruction tells Python what to do if the raspberry
0
else
snakeSegments
statement, the
else
, and if so, the code picks a random location on the playing
0
list: the
snakeSegments
raspber-
list.
list, it tells
snakeSegment
instruction only runs
pop
raspber-

Hide quick links:

Advertisement

Table of Contents
loading

Related Products for Raspberry Pi Raspberry Pi A

This manual is also suitable for:

Raspberry pi b

Table of Contents