Hardware Reference
In-Depth Information
Python a place on the playing field 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()
These lines tell pygame to fill in the background of the playing surface in black, draw the
snake's head and body segments in white, and finally, draw a raspberry in red. The last line,
pygame.display.flip() , tells pygame to update the screen—without this instruction,
items will be invisible to the player. Every time you finish 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()
The first if statement checks to see if the snake has gone off the playing surface vertically,
while the second if statement checks if the snake has gone off the playing surface horizon-
tally. In either case, it's bad news for the snake: the gameOver function, defined earlier in
the program, is called to print a message to the screen and quit the game. The 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()
Search WWH ::




Custom Search