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 http://www.wiley.com/go/raspberrypiuserguide
. If you’re typing the code in by hand, look out for the 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 *
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) ...
Get Raspberry Pi User Guide 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.