Raspberry Pi A User Manual page 202

Hide thumbs Also See for Raspberry Pi A:
Table of Contents

Advertisement

186
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—
Position
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
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
def gameOver():
P A R T I I I
P R O G R A M M I N G W I T H T H E R A S P B E R R Y P I
—are set to a list of comma-separated values. This causes Python to create the
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()
,
snakePosition
snakeSegments
to create a function means you'll only have
def
function:
gameOver
and
raspberry-

Hide quick links:

Advertisement

Table of Contents
loading

Related Products for Raspberry Pi Raspberry Pi A

This manual is also suitable for:

Raspberry pi b

Table of Contents