You are previewing Raspberry Pi User Guide.

Raspberry Pi User Guide

Cover of Raspberry Pi User Guide by Gareth Halfacree... Published by John Wiley & Sons

Appendix A: Python Recipes

The following recipes provide the program code for Example 3 and Example 4 in Chapter 11, “An Introduction to Python”, and a sample solution for the combined input-output program suggested in Chapter 12, “Hardware Hacking”. Each recipe is also available for download from the Raspberry Pi User Guide website at If you’re typing the code in by hand, look out for the turnover.jpg symbol: this indicates that the line is wrapped due to space constraints in the book. If you see the symbol at the end of a line, don’t press Enter until you reach the end that doesn’t have a symbol present.

Raspberry Snake (Chapter 11, Example 3)

#!/usr/bin/env python

# Raspberry Snake

# Written by Gareth Halfacree for the Raspberry Pi User Guide

import pygame, sys, time, random

from pygame.locals import *


fpsClock = pygame.time.Clock()

playSurface = pygame.display.set_mode((640, 480))

pygame.display.set_caption(‘Raspberry Snake’)

redColour = pygame.Color(255, 0, 0)

blackColour = pygame.Color(0, 0, 0)

whiteColour = pygame.Color(255, 255, 255)

greyColour = pygame.Color(150, 150, 150)

snakePosition = [100,100]

snakeSegments = [[100,100],[80,100],[60,100]]

raspberryPosition = [300,300]

raspberrySpawned = 1

direction = ‘right’

changeDirection = direction

def gameOver():

    gameOverFont = pygame.font.Font(‘freesansbold.ttf’, 72) ...

The best content for your career. Discover unlimited learning on demand for around $1/day.