Hardware Reference
In-Depth Information
hese tell pygame to ill in the background of the playing surface in black, draw the snake's
head and body segments in white, and inally, draw a raspberry in red. he last line, pygame.
display.flip() , tells pygame to update the screen—without this instruction, items will
be invisible to the player. Every time you inish drawing objects onto the screen, remember
to use pygame.display.flip() so the user can see the changes.
Currently, it's impossible for the snake to die. A game where the player can never die would
rapidly get boring, so enter the following lines to set up some scenarios for the snake's death:
if snakePosition[0] > 620 or snakePosition[0] < 0:
gameOver()
if snakePosition[1] > 460 or snakePosition[1] < 0:
gameOver()
he irst if statement checks to see if the snake has gone of the playing surface vertically,
while the second if statement checks if the snake has gone of the playing surface horizon-
tally. In either case, it's bad news for the snake: the gameOver function, deined earlier in
the program, is called to print a message to the screen and quit the game. he snake should
also die if its head hits any portion of its body, so add the following lines:
for snakeBody in snakeSegments[1:]:
if snakePosition[0] == snakeBody[0] and Æ
snakePosition[1] == snakeBody[1]:
gameOver()
he for statement runs through each of the snake segments' locations, from the second list
entry to the end of the list, and compares it to the current position of the snake's head. It's
important to start the comparison at the second entry using snakeSegments[1:] and not
the irst. he irst entry is always set to the position of the head, and starting the comparison
here would result in instant death for the snake as soon as the game begins.
Finally, all that is required for the game to be complete is to control the speed using the fps-
Clock variable. Without the variable, which you created at the start of the program, the
game would run too quickly to play. Type in the following line to inish the program:
fpsClock.tick(20)
If you think the game is too easy or too slow, you can increase this number; or if the game is
too hard or too fast, decrease the number. Save the program as raspberrysnake.py , and
Search WWH ::




Custom Search