Appendix A

Python Recipes

THE FOLLOWING RECIPES provide the program code for Example 3 and Example 4 in Chapter 12, “An Introduction to Python”, and a sample solution for the combined input-output program suggested in Chapter 15, “The GPIO Port”. Each recipe is also available for download from the Raspberry Pi User Guide website at www.wiley.com/go/raspberrypiuserguide3e. If you’re typing the code by hand, look out for the ↵ symbol, which indicates that the line is wrapped because of 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 of a line that doesn’t have a symbol present.

Raspberry Snake (Chapter 12, Example 3)

#!/usr/bin/env python# Raspberry Snake# Written by Gareth Halfacree for the Raspberry Pi User Guideimport pygame, sys, time, randomfrom pygame.locals import *pygame.init()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 = 1direction = 'right'changeDirection = directiondef gameOver():    gameOverFont = pygame.font.Font('freesansbold.ttf', 72)    gameOverSurf = gameOverFont.render ↵    ('Game Over', True, greyColour)    gameOverRect = gameOverSurf.get_rect()    gameOverRect.midtop ...

Get Raspberry Pi User Guide, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.