Hardware Reference
In-Depth Information
instruction and remember the three colour values for red, green and blue. To define the
colours for this example program, type the following lines:
redColour = pygame.Color(255, 0, 0)
blackColour = pygame.Color(0, 0, 0)
whiteColour = pygame.Color(255, 255, 255)
greyColour = pygame.Color(150, 150, 150)
The next few lines initialise some of the game's variables so they're ready for use. This is an impor-
tant step, because if these variables are left blank when the game begins, Python won't know what
to do. Don't worry about what each variable does for now—just type in the following lines:
snakePosition = [100,100]
snakeSegments = [[100,100],[80,100],[60,100]]
raspberryPosition = [300,300]
raspberrySpawned = 1
direction = 'right'
changeDirection = direction
Notice that three of the variables— snakePosition , snakeSegments and raspberry-
Position —are set to a list of comma-separated values. This causes Python to create the
variables as lists —a number of different values stored in a single variable name. Later, you'll
see how you can access individual values stored in a list.
Next, you need to define a new function—a fragment of Python code which can be called
upon later in the program. Functions are useful for avoiding code repetition and making the
program easier to understand. If you have a particular set of instructions that are needed at
multiple points in the same program, using def to create a function means you'll only have
to type them once—and only have to change them in a single place if you alter the program
later. Type the following lines to define the gameOver function:
def gameOver():
gameOverFont = pygame.font.Font ↵
('freesansbold.ttf', 72)
gameOverSurf = gameOverFont.render ↵
('Game Over', True, greyColour)
gameOverRect = gameOverSurf.get_rect()
gameOverRect.midtop = (320, 10)
playSurface.blit(gameOverSurf, gameOverRect)
pygame.display.flip()
time.sleep(5)
pygame.quit()
sys.exit()
Search WWH ::




Custom Search