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 14, “The GPIO Port”. Each recipe is also available for download from the Raspberry Pi User Guide website at www.wiley.com/go/raspberrypiuserguide4e. If you’re typing the code by hand, look out for the image 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 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 *

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 = 1

direction = 'right'

changeDirection = direction

def gameOver():

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

gameOverSurf ...

Get Raspberry Pi User Guide, 4th 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.