Hardware Reference
In-Depth Information
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
his 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. his location is
then multiplied by the size of a snake's segment—20 pixels wide and 20 pixels tall—to give
Python a place on the playing ield to position the new raspberry. It's important that the
location of the raspberry is set randomly: this prevents the player from learning where the
raspberry will appear next. Finally, the raspberrySpawned variable is set back to 1 , to
make sure that there will only be a single raspberry on the playing surface at any given time.
Now you have the code required to make the snake move and grow, and cause raspberries to
be eaten and created—a process known in gaming as respawning . However, nothing is being
drawn to the screen. Type the following lines:
playSurface.fill(blackColour)
for position in snakeSegments:
pygame.draw.rect(playSurface,whiteColour,Rect Æ
(position[0], position[1], 20, 20)) Æ
pygame.draw.rect(playSurface,redColour,Rect Æ
(raspberryPosition[0], raspberryPosition[1], 20, 20))
pygame.display.flip()
Search WWH ::




Custom Search