Hardware Reference
In-Depth Information
This uses the insert instruction to insert a new value into the snakeSegments list: 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:
if snakePosition[0] == raspberryPosition[0] ↵
and snakePosition[1] == raspberryPosition[1]:
raspberrySpawned = 0
else:
snakeSegments.pop()
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 raspber-
rySpawned variable is set to 0 . he else instruction tells Python what to do if the raspberry
has not been eaten: pop the earliest value from the snakeSegments list.
he pop instruction is simple but clever: it returns the oldest value from the list but also
removes it, making the list one item shorter. In the case of the snakeSegment list, it tells
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 else statement, the pop instruction only runs
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:
if raspberrySpawned == 0:
x = random.randrange(1,32)
y = random.randrange(1,24)
raspberryPosition = [int(x*20),int(y*20)]
raspberrySpawned = 1
This section of code checks to see if the raspberry has been eaten by testing if the raspber-
rySpawned variable is set to 0 , and if so, the code picks a random location on the playing
surface using the random module you imported at the start of the program. This location is
then multiplied by the size of a snake's segment—20 pixels wide and 20 pixels tall—to give
Search WWH ::




Custom Search