0% found this document useful (0 votes)
264 views164 pages

Ultimate Guide To Raspberry Pi - 2014 UK

Guide for Raspberry Pi

Uploaded by

Spiros Apostolou
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
264 views164 pages

Ultimate Guide To Raspberry Pi - 2014 UK

Guide for Raspberry Pi

Uploaded by

Spiros Apostolou
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 164

U|t|mate Cu|de to

kaspberry Pi
Learn regramm|ng frem scratch
Perfect fer every age, frem 8 te 88!
0reate yeur ewn games and rejects
N
E
N
&
E
X
P
k
N
0
E
0
l

u
||d
ye
u
r
e
w
n
'M
a
rs
E
x
|e
re
r'
re
b
e
t!
U|t|mate Gu|de to Raspberry P|
3
I`m a child o the rst home-computing reolution. Back in the 1980s, I learned
to program on a ZX Spectrum plugged into a portable colour 1V, using a
cassette deck or saing and loading games. Since the mid-1990s, much o my
liing has been earned by using the skills I began learning on that primitie,
rubber-keyed chunk o plastic.
1he Raspberry Pi brings the same opportunities to today`s would-be
programmers. A ully working computer the size o a credit card that you can buy
or less than _30, the Pi is the ideal platorm or learning about programming
eerything rom games to robots.
Ra.berr, Pi for egivver. aims to help you get started as a coder by encouraging
you to create your own programs. Don`t worry i you don`t hae a Raspberry Pi
yet, our adice applies to \indows users too., \e coer just the theory you must
know and then put those concepts to work in building two games - one simple
and one more complex.
\hy games Because they`re a great way to learn programming: they`re
un, you get to play them, and they include all the ingredients common to most
coding projects, rom sotware utilities to robotic control. 1hey can also lead to a
great career as a games programmer.
But the real power o the Raspberry Pi is in its ability to connect with the
real world - and this, along with its compact size, low cost and modest power
requirements, makes it ideal or both mobile and remote purposes.
So in this book we also show you how to create an independent weather
station that can be sited anywhere that has power and \i-li. It`s a great thing to
do, and could open your mind to all sorts o possibilities. low about sending
the Pi into space, using it as a CC1V controller, conguring it as the brains o a
robot, or een using it to control home appliances
So let`s get started. lasten your seat belt and welcome to the world o coders,
tinkerers, makers and rocket scientists.
Kevin Partner

U|t|mate Gu|de to Raspberry P|


4
Chapter 2: What |s programm|ng?
18
1his chapter demysties the
world o programming. \e`ll
explain the basic concepts and
show you what a keen beginner can achiee
with the inestment o time. \e`ll also
proide a tour o the tools that will soon
become your natural home. lere, we`ll
also get you typing in your rst ew lines o
code. Don`t panic! It isn`t nearly as scary as
it might sound.
Chapter 1: The Raspberry P| story
6
1here isn`t a handy manual that`s
supplied with the Raspberry Pi,
so here we coer the basics. \e
explain what the Raspberry Pi consists o
and how to set it up - rom downloading
the operating system to hooking it up in
your ront room. \e`ll also reeal how
to set up and install all the sotware you`ll
need to help you work through the rest o
this guide.
Chapter 3: Programm|ng |n Python
36
Python is a brilliant rst
programming language to
learn: similar to Lnglish,
it`s ery easy to understand, yet packs
in a surprising amount o power. Many
proessional programmers use Python
eery day. lere, we introduce the language
by explaining the thinking behind it - and
object-oriented programming - and how it
works in practice.
Oontents
U|t|mate Gu|de to Raspberry P|
5
Chapter 5: Creat|ng a po||shed game

Now you`e mastered the


basics, it`s time to stretch
your skills. In this chapter,
we add our own ruity spin to a match-three-
style game. \hat`s more, we`ll gie it the
proessional polish and graphical eatures that
paying customers demand.
Chapter 4: Des|gn|ng a game

Now you know the undamentals,


it`s time to get creatie: we take
you, step by step, through the
creation o a real game. By the end o this
chapter, you`ll hae written an addictie little
shooting game that lets you and your riends
blast ruit out o existence.
Chapter 6: P| |n the sky

\e set up our ery own


weather station, complete
with a built-in computer!
In this ery real-world project, we explain
eerything you need - including a bird nesting
box - and reeal how you can hook up to a
third-party online serice such as Dropbox.
Chapter 7: Bu||d a robot

In this new chapter,


we stretch your skills
urther and show you
how you can use the Raspberry Pi to put
together a robot inspired by the Mars
Curiosity Roer.
U|t|mate Gu|de to Raspberry P|
6
In the year 2006, the Computer Laboratory at the Uniersity o Cambridge
had a problem. lewer and ewer students were applying to study computer
science at the establishment, and the skill leels o those who did apply
were declining year on year. \hereas, in the past, undergraduates had
typically arried at the uniersity with some coding experience, by the mid-
noughties most knew much more about PowerPoint than they did about
programming.
1his was partly due to a switch in emphasis at school towards teaching
oce applications and web design rather than how to program, but it was
also because the earlier generation o home computers had been replaced by
games consoles. \hy did that matter Because a ZX Spectrum, BBC Model B
or Commodore 64 could be used to play games create sotware. 1he
PlayStation and Xbox, or all their technological superiority, are sealed units
with no way or the aerage user to create their own games.
Perhaps the biggest problem, howeer, is caused by the way in which the
The Raspberry P| story
Chapter One
P
h
o
t
o
g
r
a
p
h
y
,
D
a
n
n
y
B
i
r
d
;
r
e
p
r
o
,
J
a
n
C
i
h
a
k
U|t|mate Gu|de to Raspberry P|
7
internet has become part o eeryday lie. 1he aerage household now has
at least one computer, usually a laptop, which they use or eerything rom
banking through online shopping to social networking and playing games. 1he
idea o handing oer this now critical piece o kit to an inexperienced student
o programming lls the rest o the amily with ear - what i their experiments
led to a problem with their internet banking or, worse, lacebook \hat i their
prospectie programmer wanted to use it or hours at a time \hat would they
use or their Ocado shop
1here`s another problem with modern laptops - they`re simply oer-the-top
or learning to program on. Oer-powered, distracting and complicated, today`s
operating systems are a million miles away rom the blinking cursor o the classic
home computer.
So, led by then-director o studies Lben Upton, the group that would one
day become the Raspberry Pi loundation set itsel the target o encouraging
1,000 new computer science students across the UK. Since they couldn`t directly
re-write the syllabus taught in schools, they decided to ocus on what they
do - so they began work on a new type o computer that would be easy to
program and, critically, cheap to buy.
last-orward to lebruary 2012 and, ater a six-year journey, component
suppliers larnell and RS Llectronics opened their websites or pre-orders
o the Raspberry Pi. Although the project had been started with the aim o
producing 1,000 units per year, initial interest was such that 10,000 were planned
or production in 2012. \ithin minutes o going lie with their Raspberry Pi
order pages, both websites had collapsed under the sheer weight o trac
and the initial allocation had disappeared in a wisp o smoke. A ew days later,
100,000 pre-orders had been taken, with more than two million units sold by the
end o 2013.
1he oundation has also launched an een cheaper ersion, called the Model
A, which has the adantage o requiring less power. loweer, this guide ocuses
mainly on the more general-purpose Model B.
The perfect p|atform for |earn|ng programm|ng
1he Raspberry Pi has been designed rom the ground up to proide the ideal
enironment in which to learn programming - whether that`s simply or the un
o it or as the start o a career in coding. It`s cheap, compact and rugged, and it
also comes with most o the tools you need to create your own programs built
into its deault sotware.
It may not be as ast as the amily laptop, but think about this: the computer
controlling the Mars Curiosity roer currently trundling across the surace o the
red planet is less powerul than a _30 Raspberry Pi. I NASA`s chip can power a
space probe, just imagine what you can do with your Pi.
U|t|mate Gu|de to Raspberry P|
8
What |s the Raspberry P|?
1he rst thing you`ll notice when you clap eyes on a Raspberry Pi is that it`s
tiny - the size o a credit card. 1hen you`ll notice that it has no case - it`s
simply a printed circuit board. Despite its diminutie size and leath Robinson
appearance, howeer, the Pi is a completely unctional computer. And it costs
around _30. Let`s take a look at what makes it tick.
Brains
A single chip 1, contains memory, the central processing unit and graphics chip.
CPU (Central Processing Unit or Processor)
1he Raspberry Pi uses a mobile phone chip designed by ARM - the company
that designs the processors used in the majority o smartphones and tablets,
including those sold by Apple. 1he ersion used in the Pi is slower than you`ll
nd in an iPad, or example, but it`s ast enough to do the job it`s intended or.
GPU (Graphics Processing Unit)
Unlike the relatiely pedestrian CPU, the Graphics Processing Unit on the Pi is
equialent to a top-o-the-line mobile deice. It can run 3D games and play high-
denition ideo indeed, one o the most common uses or the Pi is as a ery
cheap media centre,. \ith the right sotware, a 1V and a broadband link you
hae iPlayer, \ou1ube and other internet ideo serices at your ngertips.
6. 2 x USB
7. Ethernet
Micro-USB
power connector
8. GPlO pins
5. RCA video
3. HDMl
2. SD card
1. 512MB RAM,
CPU & GPU
Camera connector
DSl connector
4. Stereo
audio jack
U|t|mate Gu|de to Raspberry P|
9
Memory
1he Pi comes with 512MB o Random Access Memory RAM, - plenty or the
uses we`re going to put it to. It also comes with an SD card slot 2, - exactly the
same as that used by many digital cameras - which takes the place o the hard
disk ound in most laptops. Programs are stored on the SD card and, once the Pi
is powered on, these are copied into the much aster RAM until the computer is
turned o, when the RAM is cleared. One great conenience o the Pi is that you
can turn it rom a media player to a desktop computer simply by swapping out
the SD card - much easier than remoing a laptop`s hard disk!
Sound and vision
One o the design requirements or the Raspberry Pi was that it should be easy to
hook up to existing equipment, so it includes an lDMI port 3, or connecting
to a 1V or computer monitor. lDMI carries both picture and sound, so i you
use a monitor, you may need to plug a set o speakers into the stereo audio jack
4,. I your monitor doesn`t hae an lDMI socket, you can buy a cheap adaptor
to conert it to DVI - just bear in mind that you won`t be able to use a monitor
that has only a VGA connector.
I you`re really stuck, you can use the RCA ideo jack 5, to connect to
the composite ideo input on an old-ashioned CR1 1V. loweer, this was
added mainly to allow the Pi to be used in the 1hird \orld where 1Vs are more
common than monitors - the picture quality is poor.
Connections
1he Raspberry Pi comes with two USB ports 6, that you can use to connect a
keyboard, mouse, \i-li dongle or any compatible peripheral. \ou`ll probably
want to buy a USB hub to allow you to plug in multiple deices at once - just
make sure it has a separate power adaptor, the Pi`s ports supply only a low oltage.
\ou can connect the Raspberry Pi directly to your router or a wired network
ia the standard Lthernet port 7, - this gies the astest and most reliable
connection to the internet.
Pi Pins
So ar, eerything we`e described apart rom the SD card, is pretty standard
to all computers. loweer, the Pi has some extra capabilities not ound on your
common or garden laptop. 1he most important o these are the General Purpose
Input Output GPIO, pins 8,, which oer arious ways to control deices and
receie input rom sensors and such like. loweer, misusing these pins can
bake your Pi so it`s best to use one o the many add-on boards that allow you to
experiment saely. \e coer some o the options later.
1he Pi also includes a connector or a camera module and a DSI connector
or connecting the Pi to certain specialist displays such as mobile phone screens.
U|t|mate Gu|de to Raspberry P|
10
The poss|b|||t|es
So, this is a small, cheap computer
with no moving parts and the
ability to connect with the outside
world. Put another way, imagine
having the power of a laptop
without its bulk or its fragility.
With a Raspberry Pi you can take
computing almost anywhere -
think about the possibilities.
Hook it up to a webcam, attach
it to a weather balloon and take
pictures from near space. See hffp://WWW.aspbeyp1.og/
ach1ves/1620 - the Raspberry Pi survived falling 40km through the
atmosphere when the balloon burst
Attach temperature, humidity and air-pressure sensors to create an
intelligent weather station
Create a media centre for the car or home
Build it into a bird box, along with infrared trip sensors and a webcam,
to record the nesting season. See hffp://WWW.youfube.com/
Wafch?v=-JpbI8Cndo
Put together a very cheap internet radio
Use it as the brains of a robot...as well as a general-purpose (if a little
slowj computer. For less than 30!
And that's just the beginning.
Focus On
Where can I get one?
1he Raspberry Pi loundation selected
Premier larnell hffp://cpc.fane11.
com, and RS Llectronics hffp://
uk.s-on11ne.com/Web/
genea1D1sp1ay.hfm1?1d=aspbey
p1, to be its ocial suppliers, so we
recommend buying direct rom them.
\hilst units are also aailable on eBay,
Amazon and through some retailers,
you`re likely to get the lowest price and the latest models by going direct.
As an example, in September 2012, when the oundation launched a slightly
Take pictures of Earth from near
space using a Raspberry Pi
RS Electronics is one of the two authorised suppliers of
Raspberry Pi units in the UK
U|t|mate Gu|de to Raspberry P|
11
reised ersion o the Pi that included double the memory o the original model,
customers o larnell and RS Llectronics automatically receied the new ersion.
I you don`t hae an SD card already then you may want to add one to your
order when you buy your Pi - that way you`ll know it`s compatible although the
ast majority o bog-standard cards work ne,. Lither way, a 4GB-8GB card is
about the right size.
\e recommend that you buy one with the operating system OS,
already installed. 1his is because the Raspberry Pi is designed to be a hands on`
computer and you`ll learn a lot more about how things work by installing the
OS yoursel. Sooner rather than later you`ll want to upgrade the OS, so it makes
sense to amiliarise yoursel with the process right at the outset. It isn`t dicult
and you`ll also sae yoursel a ew pounds.
Sett|ng up your Raspberry P|
Once the jiy bag containing your tiny new computer lands on the mat, you
hae a little work to do beore you can connect it to a display and boot it up. 1he
Raspberry Pi uses a standard SD card instead o the hard disk you`ll nd in most
laptops, and your rst job is to install the sotware needed to run the computer
onto the SD card. It`s not dicult, just ollow the steps.
Raspb|an
There wouldn't be much point in a 30
computer if you were then required
to install an expensive OS on it (such
as Windows or Apple's OS Xj to get
it to work. This, and the fact that no
version of Windows or OS X will work
on the ARM chip of the Pi, means that
the various OSes created for it are all
based on the free and open-source Linux.
The foundation recommends Raspbian, a version of Debian that's a
popular distribution of Linux. lf this sounds like gobbledygook, don't worry
- if you've used Windows, you'll fnd Raspbian pretty familiar.
You can even install Linux versions of many of the programs you're
familiar with including LibreOffce for Microsoft-compatible word
processing and spreadsheet work, and even the Chrome browser - we'll
cover how to do this shortly. You'd be hard-pressed to fnd any computing
activity for which mature, competent software doesn't exist for Raspbian.
Focus On
U|t|mate Gu|de to Raspberry P|
12
Step 1: Prepare your SD card
1. \ou`ll need a \indows-based computer or this. I your computer has an SD
card slot, then go right ahead and insert your 4GB- card. I not, you`ll need
to use an adaptor.
Red Alert: I you use an external hard drie, then disconnect it now
so there`s no risk o accidentally picking the wrong drie letter when you
reormat the SD card.
2. 1o ormat the SD card, go to hffps://WWW.sdcad.og/doWn1oads/
fomaffe4/eu1aW1ndoWs/, accept the licence agreement and download
the SD lormatter to your computer. Go to your Downloads older, right-
click the ZIP le you downloaded and extract it. Now double-click SL1UP.LXL
and ollow the steps to install SD lormatter..
3. Start SD lormatter and use it to ormat your SD card.
4. Now head to hffp://WWW.aspbeyp1.og/doWn1oads and right-
click the link next to image` under onine and network install`.
Select sae link as` and sae the NOOBS image to your computer`s
Downloads older. Right-click the ZIP le and extract it, then double-click
the NOOBS older you`e just created and copy the les that are inside it
to your SD card.
5. Place the SD card in the Raspberry Pi as shown in the diagram below.
HDMl - Tv/Monitor
Mobile phone
charger (or similarj
Ethernet - Router
USB - Keyboard USB - Mouse
U|t|mate Gu|de to Raspberry P|
13
Stage 2: Hook up your Raspberry P|
1. Connect the lDMI lead to your teleision or monitor hint: i your
monitor doesn`t hae lDMI but does hae DVI, you can buy a cheap
adaptor,. Now, connect the keyboard and mouse to the USB ports and
the Lthernet port to your internet router or network. I you don`t plan to
use the Raspberry Pi near your router, you can use a compatible \i-li dongle
a good example being the Ldimax L\-811UN,.
2. Connect the power, and ater a ew moments, the NOOBS enironment
starts up and presents you with a menu o all the dierent operating
systems you can install on your Raspberry Pi. In most cases you should
use Raspian, so select it and click Install. 1his will begin a process that will
install Raspian on your SD card - it will take around 30 minutes. Once
it`s complete, click OK and the Pi will reboot, ultimately presenting a
conguration menu.
Choose option 3 to select Lnable Boot to Desktop,Scratch` and then
choose the second option Desktop Log in`, which will make the Raspberry
Pi boot into the desktop iew automatically. Select option oerclock` and
set the alue to modest`, since this will speed up the Raspberry Pi a little
without drawing any extra power. Select option 8 to go to the Adanced
Settings and use option 4 to enable SSl - this will make it possible to
connect to your Pi oer a network rom your main computer. Now select
linish and reboot the Pi.
Raspian should be your operating system of choice. Once it has installed, the Raspberry Pi will reboot to
present the screen you see above. Although this confguration screen may look dauntingly technical, the
options we require are actually quite simple to set
U|t|mate Gu|de to Raspberry P|
14
3. All being well, your Raspberry Pi will reboot into a desktop iew that, on the
surace at least, is pretty amiliar. At the bottom-let you`ll see the equialent
o \indows `s Start button, or accessing the sotware that`s pre-installed
on the Raspberry Pi. Next to the Start button is an icon that launches the lile
Manager, which works in a similar way to the \indows lile Lxplorer.
4. \ou`ll also notice an icon labelled LX1erminal`, which, when double-
clicked, launches a window containing the text p10aspbeyp1 in green at
the top let. \e`ll use this window to type arious commands - don`t worry,
you`ll only eer need to learn a ew.
Stage 3: F|nd and |nsta|| software
1he Raspberry Pi comes with a basic
range o sotware, but one o the benets
o a Linux-based system is a huge library
o additional ree programs.
linding and installing sotware or
the Raspberry Pi is ery dierent to its
\indows equialent, howeer. Rather
than running a setup program, with Linux
you use a package manager` and in many
cases this is done by typing in commands.
Don`t panic, it`s easy! \e`ll show you how
ia the terminal rst because most online
examples use this approach.
lnstalling software via the terminal isn't
at all diffcult once you know how
The Pi desktop is easy to get started with, especially if you're familiar with Windows
U|t|mate Gu|de to Raspberry P|
15
Lach distribution o Linux comes with a library o optional sotware, called
Package Repositories. \ou can think o the initial setup as a starting point, to
which you can then add sotware rom the repositories to suit your purpose.
lor a general-purpose computer, you`d probably want to install an oce
suite such as LibreOce a ersion o OpenOce,, and the Chromium browser
the open-source ersion o Google Chrome,. In this case, we`re going to install
Chromium and then ocus mainly on installing a programming editor. At arious
points throughout the book, we`ll add extra packages.
1. Let`s begin by installing Chromium. Double-click LX1erminal and type:
sudo apf-gef updafe
...ollowed by the Lnter key. 1his probably looks incomprehensible, so let`s
take it step by step. 1he rst command, sudo, tells Linux that you want
to run the rest o the commands as a super-user`. 1his is similar to the
Administrator user in \indows - it gies permission to change the system.
W|re|ess
As a general rule, Linux distributions have poorer support for wireless
networking than Windows PCs or Macs, since not all manufacturers write
Linux drivers for their products. This also applies to wireless keyboards
and mice, so you must make sure that a device is compatible with your
Raspberry Pi before purchasing. You can fnd a list of supported devices
at hffp://e11nux.og/kP1ve1f1edPe1phea1s. The Edimax
EW-7811UN Wi-Fi dongle is a good choice for most situations because,
as well as being compatible, it performs well despite its diminutive size.
To install, plug it into the Raspberry Pi before
switching on the PC. Once booted up, double-click
the "Wi-Fi Confg" icon on the desktop and choose the
Manage Networks tab. Now click
the Add button and you should see
a list of nearby wireless networks.
Select yours by double-clicking it
and then complete the Network
Properties dialog box - remembering
to enter your wireless password into
the PSK feld. Now click Add and you
should fnd you're connected.
Focus On
To install, plug
switching on the P
the "Wi-Fi Confg"
U|t|mate Gu|de to Raspberry P|
16
1his can be dangerous i not used properly, so, we hae to explicitly type
sudo to conrm we want to do so. apf is short or Adanced Packaging
1ool` and this is the program that installs our sotware. gef is the utility
within apt that does this - it packages.
linally update` tells apt-get to download the latest list o packages: you
should always update apt-get beore trying to install sotware.
2. Now, to actually install Chromium we can type:
sudo apf-gef 1nsfa11 chom1um
...and Lnter. 1his time we tell apt-get to install` a named package. \our
terminal window will now ll up with lines o text explaining what it`s doing
as the sotware automatically installs. \hen it`s done, Chromium will be
aailable rom the Internet submenu o the Start button. 1o place an icon on
the desktop, right-click the icon in the submenu and select Add to desktop`.
3. 1his is all ery well, but how do you know what to install and what the
package name is One way is to Google oce sotware or Raspberry Pi`,
but another is to install a graphical package manager. 1ype:
sudo apf-gef 1nsfa11 synapf1c
1his will download and install the Synaptic Package Manager. Once this is
done, you will nd it by clicking the Start button and choosing the Other
submenu. Click Synaptic and you`ll be asked to type your password which,
unless you`e changed it, will be raspberry`,. \ou`ll now see a window
containing all the packages aailable to the Raspberry Pi, organised by type.
4. \e`re going to use Synaptic to install a code editor called Geany. On the let
side o the Synaptic window, scroll down to the Deelopment category. Now
scroll through the right-hand window until you nd Geany. In act, you need
to click the package geany-common rst, then select Mark or Installation,
beore doing the same with the geany package. Once you`e done this, click
the Apply button to install it. 1his is straightorward, but remember the
equialent command in the terminal would be:
sudo apf-gef 1nsfa11 geany
...which is clearly much quicker. So, i you know the package name, you
should use the command line approach, i you want to browse, choose
Synaptic. \hy not gie it a go and install LibreOce
U|t|mate Gu|de to Raspberry P|
17
The |p s|de
\ou now hae a ully working Pi, ready and raring to go. But while you think
about all the possibilities opening up beore you, bear in mind the ollowing.
The Pi is slow. I you`re used to the snappiness o a modern computer,
using heayweight sotware such as LibreOce will eel like wading through
treacle. \ou`ll notice a delay o a couple o seconds ater you double-click an
icon beore anything seems to happen, or example. 1his is partly because an SD
card isn`t as ast as a modern hard disk when it comes to reading les, as well as
renecting the speed o the processor. Once your word processor has ully loaded,
you`ll probably nd the perormance perectly acceptable. Some games will work
well on the Pi too - 3D shoot-em-up Quake was amously ported across ery
early on. loweer, the Pi is not designed or playing high-end games, so don`t
imagine it will replace an Xbox or that purpose.
Linux is not Windows/OS X. Although the Raspberry Pi desktop
looks supercially similar to \indows, underneath the surace there are
many dierences. \ou can achiee in Raspbian just about anything you could
accomplish in \indows or OS X - but allow yoursel extra time or research.
Not all hardware will work. Partly because the Pi runs a ariety o Linux
and partly because it uses an ARM chip, some keyboards, mice, printers, \i-li
dongles and other peripherals won`t work. \ou should always check the list o
approed hardware or, i buying online, check the reiews to see i others state
the product works with the Raspberry Pi.
laing said all that, most people will consider these limitations a small price
to pay or a tiny, portable, durable computer costing around _30 that can open
up a huge range o creatie possibilities.
You can install whatever software takes your fancy - and it's all free!
U|t|mate Gu|de to Raspberry P|
18
Mention the word programming` to most people and one o two images will
pop into their minds - the 1-shirted hacker wreaking haoc with sensitie
goernment serers, or lines o incomprehensible code streaming down a screen.
Not surprisingly, real programming is nothing like either.
\ikipedia denes programming as the process o designing, writing, testing,
debugging, and maintaining the source code o computer programs`, which
is a bit like saying that running is something you do when you run. O course,
programming means to write code - but what does that code do \hat is the
point o creating it
1he act is that eery single electronic deice you might come across in your
daily lie is controlled by code that was written by a programmer. It`s barely an
exaggeration to say that programming is what makes the modern world go round.
By learning how to code, then, you are equipping yoursel with the knowledge
and skills you need to take an actie part in shaping the enironment you and
others lie in.
What |s programm|ng?
Chapter Two
P
h
o
t
o
g
r
a
p
h
y
,
D
a
n
n
y
B
i
r
d
;
r
e
p
r
o
,
J
a
n
C
i
h
a
k
U|t|mate Gu|de to Raspberry P|
19
\hilst that might sound a little grand or abstract, just remember that a
person, or a team o people, created the code that runs the microwae you use to
make cheesy beans or supper, the uel injection system that gets you rom A to
B, and the set-top box you use to watch your time-shited 1V programmes - as
well as the more obious code you encounter on your computer, games console
or smartphone.
Someone must write the instructions that make these deices carry out their
useul unctions and, despite what you might imagine, you don`t need to be a
genius to code. Aboe all else, programming inoles two main skills: creatie
imagination and the ability to think in a logical, structured way. It certainly
doesn`t inole remembering eery obscure command o eery coding language
that`s Google`s job,. Programming is a process in the same sense as planning a
presentation, cooking a complex meal or coming up with next season`s lantasy
lootball strategy. It`s like soling a puzzle and it`s one o the most enjoyable and
creatie things you`ll eer do.
Don`t beliee me Just hae a little patience and you`ll soon discoer the
thrill o taking control o your computer rather than eeling a slae to it. 1his is
at the heart o programming: haing an impact in the real world whether that`s
on a PC screen, smartphone or a hacked-together robot trundling ater the dog.
1his impact can be proound and, when the penny drops, you`ll realise that
programming rees you rom being a passenger in this technological world and
proides the toolkit to take hold o the wheel or yoursel.
Sett|ng your s|ghts
\ith such a wealth o possibilities it`s important to think about what want
to achiee with your programming skills. laing a practical goal in mind will
help make sense o what you`re learning, as well as proiding an opportunity to
practise and get a sense o real achieement. 1he best adice is to ollow your
interests and choose a project you`ll
enjoy. \hether or not you want to
become a proessional programmer,
by ocusing on something that you`ll
enjoy or its own sake, you`ll become
better quicker. 1he people at the top
o the industry, earning the signicant
pay cheques by creating the sotware
The Lost City is a premium game for
smartphones and tablets created by indie
programmer Joe Kauffman. lt has been
installed around 500,000 times on Android
devices alone
U|t|mate Gu|de to Raspberry P|
20
that runs the banks and major businesses, or example, almost always began this
way - and many continue to code or un in their spare time.
So what is achieable or a keen beginner willing to inest some time, eort
and brainpower to learn programming skills
Making games
Most coders begin by creating games because most like playing games. \hether
you realise it or not, when you play a game you`re gaining an understanding o
how games work. Crucially, this means you know what you`re aiming or when
deeloping your own game.
1he games category coers eerything rom basic word-guessing puzzles
through 2D platorm adentures to immersie rst-person extraaganzas such
as the Call o Duty series. As a new programmer, you`ll begin at the simple end
beore settling on your aourite orm, many people choose arcade puzzlers or
point-and-click adentures, or example, because these can be created in small
teams or een by coders working alone. \hateer your ultimate ambition, games
are a great way to learn programming.
Mobile apps
1he market or smartphone and tablet apps has become hugely popular in the
past ew years, especially amongst indie` deelopers that`s you,. One reason or
this is that mobile deices represent the astest growing category o internet-
connected hardware. Len more importantly, each main platorm iOS, Android,
BlackBerry and \indows, is sered by marketplaces that make it easy or
indiidual deelopers to publish their work. \ou don`t need to sign a deal with
a major distributor such as LA Games to get your masterpiece into the hands o
your audience: you can create it and publish it direct, at minimal cost.
1hat`s not to say it`s all plain-sailing. Despite what you might hear, mobile
app deelopment is no gray train. But it is the leading modern platorm and
a good sector to learn in i you`re looking or a career in programming.
Web development
By creating applications that run on a web serer, you potentially gain all the
benets o deeloping apps or mobile deices as well as haing your sotware
aailable to the billions o users o standard PCs. \hilst there are many situations
where a natie app is a better choice games being one,, it`s oten most eectie
to put the code on the web and hae people access it ia a browser.
Much o this programming goes unnoticed, but it`s there lurking in the
background eery time you order something rom Amazon or post a status
update on lacebook. Anything that happens on the web beyond sering up static
web pages is programming. 1o see an example o just how stunning this can be,
take a look at hffp://WWW.mov1kanf1evo.com.
U|t|mate Gu|de to Raspberry P|
21
PC applications
1here`s still a big market or
sotware that users download
and run on their computers.
1his can include utilities,
games, educational sotware
and creatie programs such as
music editors and art packages.
In practice, this usually means
that you spot a problem that
needs soling and, i you
can`t nd a good pre-existing
solution to it, you write your
own program. \ou`d be amazed
at the tiny niches some o this
sotware seres - there are, or
example, seeral explosion
generator` applications that
satisy the need or arcade game
deelopers to blow up enemy
spaceships in spectacular style.
1ypically, the coder hacks together a solution to their own problem and
then, i they think there would be an audience or it, spends time adding an
eectie user interace windows, dialogue boxes and buttons, beore releasing
it or general use. It`s also common to contribute the code to the open-source
community, which means that anyone can amend and update it. Done in an
organised way, this can result in a much better, more widely used program - or
which you receie the main credit. Very good or your CV!
Controlling your home
\ith the Raspberry Pi and related technologies such as the Arduino WWW.
adu1no.cc,, it`s become much simpler to program real-world objects as well
as traditional computers. 1here`s nothing quite as cool as connecting with your
enironment, whether that`s keeping tabs on your energy bills, watching a robot
you`e made rom an old remote control toy make its way around the liing
room noor, or taking pictures rom a weather balloon. 1he range o possibilities
is innite and it`s in this area that the Raspberry Pi has a big adantage oer a
laptop, say - its diminutie size, modest power requirements, robustness and,
aboe all, low cost make it ideal or real-world projects.
And that`s only the beginning. As you deelop your programming skills,
you`ll notice more opportunities to put them to work. So, enough explanation:
now it`s time to tool up and get cracking.
Core Temp is a utility program that lives up to its name: it monitors
the internal temperature of a PC's components
U|t|mate Gu|de to Raspberry P|
22
What do you need?
I you want to be a coder, you`ll need both hardware and sotware to get started.
1he good news is that the hardware is cheap - and the sotware is ree. By using
a ersion o Linux as the operating system, you can learn to code on a low-cost
computer such as the Raspberry Pi or a repurposed laptop or desktop that`s now
too slow to run \indows. Popular Linux ariants such as Raspbian, Debian and
Ubuntu are ree, as is most o the sotware you can run on them - including
many o the most popular programming languages.
Parlez-vous Python?
1he rst decision you need to make is which programming language to
learn. 1here are hundreds to choose rom, but a good choice would be one
that`s widely used, easy to learn, applicable to lots o programming tasks,
and similar enough to other languages to make it easy to spread your wings
later. It should also be ree to download and use. At b1f.1y/
f1obe1ndex you`ll nd a table o languages in order
o their popularity, in terms o jobs and online
resources. 1he only candidate that meets all our
criteria is Python. lere`s why:
It's widely used. Python appears in the
top ten o the 1IOBL index at the time
o writing,, which means that many skilled
engineers use it and there are many jobs or
Python programmers. Plus, there are plenty o
resources to help learn it, including this book.
It's easy to learn. 1he Raspberry Pi loundation chose Python as
its recommended programming language or this reason. One way to
describe a language is to say how high leel` it is: broadly speaking,
the more Lnglish-like it looks, the more high leel it`s considered. 1ake
a look at the ollowing code. It shows how to simply make the words
lello \orld!` appear on-screen, and it`s written in C, a ery widely used
but low-leel language:
#1nc1ude <sfd1o.h>
1nf ma1n{1nf agc, cha "agv|]}
{
p1nff{"he11o Wo1d!\n"}
efun 0
}
U|t|mate Gu|de to Raspberry P|
23
Don`t worry i you didn`t ollow that - it`s clear that there`s a considerable
learning cure inoled in understanding C, let alone creating it or yoursel.
Now, or comparison, let`s look at another section o code that does exactly
the same thing, only this time written in Python:
p1nf {"he11o Wo1d!"}
Not only is this Python example much closer to Lnglish, and thereore easier
to understand, it`s also much shorter - in this case reducing six lines o low-
leel C into a single concise instruction. 1his is another characteristic eature
o high-leel languages.
It's exible. \ou`e probably heard o BASIC, which is another well-known
and easy-to-learn language. loweer, these days BASIC isn`t as popular as it
used to be. Visual Basic is the only dialect that appears in the top ten and it`s
restricted to \indows computers, the commercial ersion is also relatiely
expensie. Python, on the other hand, can be used on \indows, Mac and
Linux computers, as well as on many other platorms. It`s also able to access
libraries o code created in C and C--.
It's a good rst language. 1he concepts that underpin Python are similar
to those ound in other popular languages. So once you`e learned to code
in Python, you`ll nd it much easier to get to grips with almost any other
mainstream language.
And i you need any other reason. it`s named ater Monty Python!
Python squared
There are two families of Python in common use: 2.x and 3.x. This
probably seems odd, as it's usually the case that when a new version of
any software is released (Python 3 was released in 2008j users tend to
upgrade. However, one of Python's great strengths is the huge library of
add-ons created by the Python community and some of these are written
in version 2, making them incompatible with the latest version.
The differences between versions 2 and 3 aren't huge so, in this
book, we're focusing on Python 2.7 - the version that comes installed by
default in Raspbian at the time of writing this book. This means we can
use just about every available Python library but still move interchangeably
between it and version 3 when the time comes.
Focus On
U|t|mate Gu|de to Raspberry P|
24
Tools of the trade
Len though you already own a Raspberry
Pi, it`s oten more conenient to deelop
on another, more powerul computer
and then moe the code across to the Pi.
Len i you`e set up the Pi in your liing
room, hidden it in a shed or built it into a
toy robot, this can be a conenient way to
work, since it`s ery easy to connect to the
Pi across a network.
1he good news is that an old laptop -
or a modern PC or Mac - will do ne or
Pi deelopment. loweer, whilst Python
is aailable or all the main operating systems, its natural home is Linux. I you`re
using \indows or OS X, it`s a good idea to install a Linux distribution alongside
your existing operating system - or, een better, set up a dedicated computer.
Ubuntu
I you`re using a Raspberry Pi, you should already be set up with Raspbian. \hat
i you want to stick with your existing PC \ou can install Python or \indows,
but we recommend using Linux as the basis o your programming enironment.
\hy \ell, it`s Python`s natural enironment and i you intend to do any serious
coding you`ll almost certainly encounter Linux at some point, especially i you
deelop or the internet.
On top o this, Linux is or tinkering, it`s a much more open OS than
either \indows or OS X, and has an actie community proiding all the bits and
pieces you need to create great programs. \ou can also nd plenty o generous
and enthusiastic adice.
lor most people, Ubuntu is the best Linux distribution to choose. It`s based
on Debian like Raspbian, but is more user riendly. It`s the most widely used and
most actiely deeloped ersion o Linux. \ou can also install it in seeral ways,
depending on your situation.
1. Wipeout. I you want to repurpose an old laptop then your best bet is
probably to wipe whateer ersion o \indows is already on it and replace
it with Ubuntu haing backed up any documents you want to keep,. 1o do
this, go to WWW.ubunfu.com/doWn1oad/deskfop and download the newest
32-bit ersion. 1he download is in the orm o an ISO le, which you can
either burn to DVD double-click it and ollow the prompts, or transer to a
USB nash drie. \hen you`re ready to install it on the target computer, insert
the DVD or nash drie and ollow the prompts. lull instructions are on the
Ubuntu downloads page.
Wubi allows you to install the Ubuntu favour of Linux
alongside Windows, but we recommend installing it on a
dedicated computer
U|t|mate Gu|de to Raspberry P|
25
2. Sibling rivalry. Another option is to install Ubuntu alongside \indows
so you can use both. 1o do this, download the \UBI \indows installer
rom WWW.ubunfu.com/doWn1oad/deskfop/W1ndoWs-1nsfa11e. 1his is a
standard \indows program that downloads and runs the Ubuntu setup. As
part o the process, your hard disk is diided up into sections so that Ubuntu
and \indows can co-exist, make sure you hae backed up your PC beore
starting. Once Ubuntu is successully installed, you`ll choose which OS to
use when you boot up your computer. It`s also easy to uninstall Ubuntu rom
within \indows.
3. Virtually Ubuntu. Perhaps the most nexible option is to set up Ubuntu as
a irtual machine` VM, running in \indows. A VM is a sotware program
that pretends it`s a hardware computer running your chosen operating system
in this case, Ubuntu,. 1he great benet o this approach is that i something
were to go wrong, you could ery quickly wipe it and start again. 1o create a
VM, you need sotware such as Oracle`s VirtualBox WWW.v1fua1box.og/
W1k1/DoWn1oads,. Once your irtualisation sotware is installed, you can set
up a VM and then load the Ubuntu ISO le into it. In act, you can create as
many VMs or which you hae space, allowing you to try out any number o
dierent ersions o Linux.
O the three approaches, using \UBI to install alongside \indows is the
simplest, whereas the VM option is the most nexible but requires more
technical condence.
Python on W|ndows
Windows is the only major operating system that doesn't come with
Python built in. lf, for whatever reason, you're forced to work in Windows,
you should download the Windows installer at WWW.pyfhon.og/gef1f.
Choose the latest version of Python 2.7. Don't choose a 64-bit version
(you'll see the number "64" in the descriptionj since this would make it
incompatible with many important libraries.
Focus On
To set up Python on Windows, choose the latest installer (2.7.3 at the time of writingj.
Don't choose the 64-bit version, shown on the second line
U|t|mate Gu|de to Raspberry P|
26
The programmer's too|k|t
1here are three things you`ll need or most coding tasks: a programming
language, an editor, and - i your project is going to make use o graphics and
sound - a set o sotware tools or creating and editing these resources.
Programming language
1he Raspberry Pi comes with Python 2. built in. 1his is the nal ersion o the
Python 2 amily and the code examples in this book are aimed at ersion 2..
\hen the educational ersion o the Raspberry Pi is released, it`s possible that it
will deault to Python 3, but it will almost certainly also include ersion 2. - and
this is the one we recommend you use. \e`ll coer how to make sure you`re
targeting the right ersion below.
Lditor
Computer programs are usually text les, which means you can edit them
using any word processor or text editor. loweer, by using an IDL Integrated
Deelopment Lnironment, rather than, or example, Leapad the Raspberry
Pi`s equialent o \indows Notepad,, you get access to all sorts o tools that
help with your programming.
Raspbian includes two ersions o an editor called IDLL - one or Python
2. and one or Python 3 - but it`s rather too basic or conenient programming.
lor that reason, we`e created the examples in this book using a more adanced
editor called Geany. I you ollowed the walkthrough in part 1 to set up your
Raspberry Pi, then you`e probably already installed Geany. I not, simply open
up LX1erminal and type:
sudo apf-gef updafe
sudo apf-gef 1nsfa11 geany
...and press Lnter. 1he rst line ensures the list o packages on your Raspberry Pi
is up to date, the second line perorms the actual install. I you`re using \indows,
go to WWW.geany.og/DoWn1oad/ke1eases and select the latest ersion o the
lull Installer.
Media
Many projects require custom graphics, and or games you`ll probably need
to create or edit your own sound eects. As with text editors, there are many
choices aailable to Linux users but the gloriously named GNU Image
Manipulation Program`, or GIMP to its adherents, is the most ully eatured and
best supported. lor sound editing, the best choice is Audacity. Oer the page,
we`ll describe how to nd and install them both.
U|t|mate Gu|de to Raspberry P|
27
Geany
1. Too|bar
The Geany toolbar contains shortcuts for moving quickly through your
code, picking and inserting colours and letting you test-run your program
with a single click.
2. Code Exp|orer
The left-hand pane displays information about the program you're
currently working on, including easy access to its main parts.
3. Cod|ng W|ndow
This is where you'll be spending most of your time. Geany includes:
Code suggestion - the editor guesses what you're typing and offers to
fnish for you;
ln-built reference - when you type the name of a Python statement, it
shows what that function expects to follow it and how it works;
Syntax colouring - "syntax" refers to the words and numbers that
make up your code, and by automatically applying different colours to
different types of syntax, Geany makes code easy to read and debug.
4. Message W|ndow
Geany displays messages and status reports in this window. You can also
select the Terminal tab to get quick access to the LXTerminal.
Focus On
U|t|mate Gu|de to Raspberry P|
28
GIMP
1o install GIMP on your Raspberry Pi,
start up Synaptic Package Manager and
nd g1mp in the Graphics category. Select
this and also g1mp-dafa then click Apply.
Alternatiely, rom LX1erminal, enter the
ollowing line:
sudo apf-gef updafe
sudo apf-gef 1nsfa11 g1mp
Once installed, you`ll nd an icon to run
GIMP in the Graphics older o your Start
menu. Since GIMP is a processor-intensie
application, it will run airly slowly on your
Raspberry Pi, but it`s perectly usable. 1o
get the best perormance, shut down any
other applications beore running it. \indows users can download the installer
rom hffp://g1mp-W1n.soucefoge.nef/sfab1e.hfm1.
\hicheer OS you`re using, you`ll nd GIMP reasonably amiliar i you`e used
any other photo-editing package, whether that`s \indows Paint or Photoshop.
\ou can nd out more about GIMP at WWW.g1mp.og.
Audacity
Most games include sound eects and, een i you use pre-existing resources, the
chances are you`ll need to edit them to t your project sooner or later. Audacity
is a basic sound-editing package that includes all the eatures most people require
- or ree. In Synaptic, you`ll nd Audacity in the Multimedia category, again, you
need to make sure that both audac1fy and audac1fy-dafa are selected beore
you click Apply. 1o install ia LX1erminal:
sudo apf-gef updafe
sudo apf-gef 1nsfa11 audac1fy
Bear in mind that i you`e only just
installed GIMP, you don`t need to run the
update command again.
Once installed, you`ll nd Audacity in
the Sound & Video section o your Start
menu. \ou can nd more inormation and
download links or \indows and Mac at
hffp://audac1fy.soucefoge.nef.
GlMP contains all the image editing and creation tools you're
likely to need
Audacity is an easy-to-use but capable sound editor
U|t|mate Gu|de to Raspberry P|
29
Let's get crack|ng
1he nal step beore we get into coding is to check that your Python
enironment is working as expected. Rather than bashing out the bog-standard
hello world` program, we`re going to create a real-time clock or your desktop.
1his is not only more interesting and useul, it will also test whether you hae
two o the most important Python libraries installed and working, as well as
Python itsel.
1. Connect your Pi and load up the desktop. Open Geany by going to the
Programming older o the Start menu.
2. Click lile, New and then immediately
sae it as clock.py`. 1he py`
extension tells Geany you`re creating
a Python le and switches on its built-
in help and syntax colouring. Now,
go to the Ldit menu in Geany and
click Preerences. Pick the Lditor tab
on the let ollowed by the Display
tab along the top, then click next
to Show white space` to ll in the
checkbox. 1his means that all spaces
and tabs are marked in the editor
window, which is helpul when typing
and editing Python code.
lf everything is going to plan, our test program
should display a working clock on the screen
U|t|mate Gu|de to Raspberry P|
30
3. 1ype the code rom the listing below into Geany:
Be ery careul to copy the code exactly, including every punctuation
mark, and make sure you put line breaks in the correct places. Be particularly
careul to use the tab key at the start o lines where needed, to indent your
code exactly as it`s shown in the listing. I you preer, you can download the
le rom WWW.p11ab.nef/code.
Although what you`e just typed in probably looks like gobbledygook
at the moment, you can see immediately how little code is needed to create
a real, working application. lor now, we`re just testing that your setup is
working so, once you`e typed eerything in and checked it or errors,
click the Cog icon on the Geany toolbar to run the app. All being well,
ater a short pause, your clock will pop up and start ticking away. I so,
congratulations: you`e demonstrated that Geany, Python and the Pygame
module are working together.
I the clock doesn`t appear, don`t despair - it`s common or programs
not to work rst time. 1ake a look at the LX1erminal window, because it will
contain a message that can help you diagnose the problem. More oten than
not, the cause will be a mistake you`e made in typing the code, but another
possible problem could be Python complaining that it`s missing the Pygame
module. I it is, and you`re using a Raspberry Pi, the chances are that your
machine has been set to run Python 3 by deault. 1his is an easy problem
to x: go to the Build menu in Geany and select Set Build Commands`. In
the eld next to Lxecute`, remoe the number 3 to set it to run the older
ersion o Python.
4. Once the clock is working, you know Python is correctly installed and
working on your Raspberry Pi. Congratulations: you now hae eerything
you need to begin your career as a programmer. Let`s go.
1mpof f1me,pygame
pygame.1n1f{}
fheIonf=pygame.fonf.Ionf{None,72}
c1ock = pygame.f1me.C1ock{}
sceen = pygame.d1sp1ay.sefmode{|320, 200]}
pygame.d1sp1ay.sefcapf1on{`P1 11me`}
Wh11e 1ue:
c1ock.f1ck{1}
fhe11me=f1me.sfff1me{"xh:xM:x5",f1me.1oca1f1me{}}
f1me1exf=fheIonf.ende{sf{fhe11me}, 1ue,{255,255,255},{0,0,0}}
sceen.b11f{f1me1exf,{0,60}}
pygame.d1sp1ay.updafe{}
U|t|mate Gu|de to Raspberry P|
31
Programm|ng - from the |ns|de out
Computers, microcontrollers and other electronic deices are used or such a
wide range o tasks that you might imagine they share ery little in common.
loweer, whether they`re running on an Xbox, inside the dashboard o a car or
controlling the Curiosity Mars Roer on the surace o the planet, most programs
work in a undamentally similar way: they take input, apply some sort o logic to
it and then output the results.
Some ery simple programs do this once each time they`re run - or
example, a calculator - but most applications go through this loop many times
per second. As a programmer, then, almost eery process you`ll eer hae to
work with will all into one o these three categories - and knowing how they
work makes understanding how code is put together much simpler. Let`s look
at a ew examples to see how this works
in practice.
A VAT calculator (yawn!)
\es, it`s boring but somebody has to write
programs to carry out useul, mundane
tasks such as this. A VA1 calculator
would ask the user to type in an amount,
it would then work out the VA1 on that
amount and add that to the original alue
to arrie at a total. linally, the program
would display the result on-screen.
In this case, then, the amount
entered by the user is the input, the VA1
calculation is the logic, and displaying the
result on-screen is the output. Bear in mind that the output could just as easily be
to a printer or een a speech synthesiser, howeer, i that was the case, neither o
the rst two parts would be aected. \hilst this might make little dierence on a
tiny app such as this, but on large corporate systems splitting the code into these
three purposes makes it possible or dierent programmers to work on each and
or the application to be easily ported rom desktop to web to mobile.
Iorza Motorsport for Xbox
1his is more like it! In a driing game, the player uses a controller or steering
wheel as input and the console then translates the directional changes and applies
them to its calculations o the car`s position using its logic code. Once it has done
this, it generates and displays the output in the orm o graphics on the screen.
Gien the rame rate o a modern console game, this is happening many times
per second - not just or the isuals, but or the sound eects too. In that case,
Any program can be broken down into its key elements -
and doing so makes things much easier to understand
U|t|mate Gu|de to Raspberry P|
32
the input might be the controller buttons assigned to acceleration and braking,
the logic inoles applying the correct physics to the Xbox`s model o the game
world, and the output - along with the isual elements - includes the sound o a
thrashed engine or screaming brakes.
Mars Rover
Right now, around 225 million miles away, a robot
the size o a lord liesta is wending its way across the
surace o Mars. Controlling the Curiosity Mars Roer
is a computer less powerul than a Raspberry Pi.
1his computer, the RAD50, created by a subsidiary
o British company BAL Systems, contains oer
2 million lines o code written in C although Python
was used to create testing scripts,.
1his code controls eerything rom sensing the
enironment to naigating the Roer through the
Martian landscape. Since radio waes take more
than 12 minutes to trael between Mission Control
and Mars, the Roer can`t be drien like a remote-
control car. So it includes sotware that uses its
cameras input, to determine where rocks and other
obstructions are, calculates a sae path logic, and
turns the wheels output,. Bear in mind that human
beings wrote the code, and they started programming
with as little knowledge as you may hae right now.
Clock
linally, remember the tiny clock app we created in the last section It took
the current system clock time as input, conerted it to a human-readable orm
logic, and displayed it on-screen output,.
Under the m|croscope
So most programs take input, process that inormation using logic and then
output it in some orm, we can use this inormation when we design and write
our applications. lor example, let`s say you`e decided to create an old-school
arcade game. In your mind`s eye you see dierent ruit alling rom the top o
the screen, some o them raspberries. 1he player uses a laser-gun that moes
across the bottom o the screen attempting to shoot the raspberries but miss all
the other ruit. \ithout some sort o model in mind, you`d struggle to work out
where to begin and how to organise your thoughts. 1he ILO model gies you a
template to help get started.
l
m
a
g
e
,
N
A
S
A
/
J
P
L
-
C
a
l
t
e
c
h
/
M
a
l
i
n
S
p
a
c
e
S
c
i
e
n
c
e
S
y
s
t
e
m
s
U|t|mate Gu|de to Raspberry P|
33
Input
Let`s begin by thinking about what inputs the game will take rom the user.
During the game, the player needs a way o controlling the laser gun, so we need
to decide i that`s going to be achieed ia keyboard, mouse or touch. 1he choice
depends largely on the platorm we`re aiming at. In the case o the Raspberry Pi,
keyboard is best, so we`re going to track the let and right arrow keys, along with
the spacebar or ring laser bolts. \hy space Because it`s the conention. low
do you know By playing games. I you eer needed an excuse or trying out as
many games as possible you can now do it in the name o research! Other inputs
will include buttons or starting, choosing leels, exiting and help.
Output
1hink about how the user will experience the game. lirst they`ll see the ruit,
laser and bullets appear on-screen and then moe. So we`ll need to write code or
displaying these graphical elements and animating them. 1he player also needs
to see a score and any other status inormation - perhaps a time limit and basic
instructions - so we`ll need a way to display inormation in text ormat. And then
we`ll need to write code to play the obligatory bleeps o the classic arcade game.
But output isn`t just what the player sees or hears. I we want to store the
players` high scores, we need to sae the data somewhere. 1his is output een
though it isn`t isible to the user.
Logic
\hilst the player might notice the quality o graphics and animations, or how
well the laser gun responds to their keyboard presses, ar more eort will go into
the behind-the-scenes tasks our program must carry out to make sure the game
works as intended. Logic is the glue that links input to output: without it you
might hae alling ruit and rising bullets but no way o connecting the two.
In most cases, you`ll nd yoursel spending the majority o your time
writing logic code. lor example, we must constantly send new co-ordinates or
all the objects on the screen to the output code so it can accurately renect their
positions. \e must check or collisions, and when one is detected we must react
accordingly by updating the output and scores - as well as checking whether the
game has nished. By breaking all these jobs down into smaller and smaller steps,
you eentually end up at the leel o the single programming task.
Mirror mirror
Most programs interact with a user in some way. In a game, it`s the user that`s
proiding the input in the rst place. In act, the player and the program become
part o a cycle: the user sees the ruit descending input,, decides where to moe
the laser gun logic,, and presses the keys accordingly output,. Put another way,
the output o your computer program becomes the player`s input, and ice ersa.
U|t|mate Gu|de to Raspberry P|
34
I you`re designing a program that interacts with a user in this way, you must
take account o the whole system. It`s not enough to think about the best way or
the code to accept input, you must also consider how the player can best proide
it. lor example, when choosing the best keys or moing the gun let and right, it
may be more conenient rom a programming point o iew to choose A and B
- but it makes much more sense or the user to use the let and right arrow keys.
\e`e all used apps that hae clearly been designed or the conenience o the
programmer - remember that rustration when you come to create your own.
Modu|ar|se
So you`e split the tasks your program needs to perorm into input, logic and
output: how does this translate into the real world o creating your game It does
this by helping you to work out how to organise your code. Imagine slicing a pie
into equal parts. \ou could begin by cutting it into thirds, and then continuing to
hale until you reach the optimum size. Input, logic and output are these thirds,
which you then diide up into smaller units o programming. In Python these
units are called Modules, lunctions and Objects.

1o create a Python program, you type code into an editor and sae it. 1he saed
le is a module so, in a way, eery Python program could be called a module,
een our tiny clock. loweer, typing all your code into a single le is rarely a
good idea unless the app is ery simple. More typically, you create a main script
le, then split the rest o the code into separate les, each o which is a module.
lt's important to think in terms of how your code serves the user's needs and desires
User Program
U|t|mate Gu|de to Raspberry P|
35
lor example, you might create a module or handling the display, one or saing
the score and reading it back, and another to listen or the user`s key presses.
\ou would then make the code in those modules aailable to the main script by
importing` them. 1ake a look again at the rst line o the clock code:
1mpof f1me,pygame
As you`e probably guessed, f1me and pygame are modules. f1me is built into
all Python installations and is, in eect, part o the standard language, whereas
pygame is a specialised module that helps in the deelopment o games.
Importing your own modules is done in exactly the same way.
Iunctions
Modules diide into unctions: blocks o code that perorm a specic task and
hae their own unique name. lor example, in the display` module or our game,
we might hae a unction or drawing a bullet, another or painting the animated
background, and a third or exploding the ruit. \ithin these unctions you`ll nd
our actual lines o code - so unctions are the smallest subdiision.
Objects
Python is an object-oriented programming OOP, language. 1his means the code
that controls how parts o a program works is contained within those parts - as
opposed to the procedural approach used by languages such as BASIC, which
keep eerything in a big central le. OOP makes it easier to build and maintain
code, and it means we can eortlessly create multiple copies o objects.
lor example, think about a game o Space Inaders. 1he inaders themseles
are identical to each other and moe let, right and down the screen. 1he
procedural approach would be to draw each inader separately, one at a time, and
keep track in memory o which one is where, whether it`s been destroyed or has
reached the bottom o the screen.
1he object-oriented approach is to write code or one inader this is called
a Class, so that it keeps track o its own position and status, and then to create
as many copies called Instances, o that class as necessary. Once they`re up and
running, they each run independently.
As a rule, OOP means less code oerall, programming that is much easier
to understand as you know that any code within the Inader class relates to the
aliens,, and, because o this simplicity, ewer bugs and better perormance.
So, a Python program is usually made up o modules containing
unctions and classes which also contain unctions,. Despite their somewhat
intimidating names, modules, unctions and classes are simply ways o organising
code, and they`re there to make lie easier. \ith that behind us, it`s time to die
into Python.
U|t|mate Gu|de to Raspberry P|
36
So, you`e set up the Raspberry Pi and you`e got a basic grasp o the principles
o programming under your belt. It`s time to start learning the practical skills
needed to create Python programmes.
In this section o the book you`ll nd many code samples. 1hese are all
short and I strongly recommend you type them in: doing so will help you gain
amiliarity with the structure o a Python program, and gie you practice in using
an editor and running programs. \ou can also download the ull code rom the
book`s companion website: WWW.p11ab.nef.
Don`t worry i you struggle with some o the concepts introduced in this
section, we`re going to coer a lot o ground quickly so we can moe onto
programming larger, more rewarding projects as quickly as possible. \hether
you`re aware o it or not, i you ollow the examples, most o what you need
to know will sink in and you`ll then hae plenty o opportunity to see how the
undamentals o Python work in action as we build the code or our projects in
the ollowing sections o the book.
Programm|ng |n Python
Chapter Three
P
h
o
t
o
g
r
a
p
h
y
,
D
a
n
n
y
B
i
r
d
;
r
e
p
r
o
,
J
a
n
C
i
h
a
k
U|t|mate Gu|de to Raspberry P|
37
Introduc|ng Python
All programming languages hae the same broad purpose: to proide a way or
humans to control deices powered by a microprocessor. \ith most languages,
code made up o letters, numbers and symbols is typed into an editor line by line
beore being run by the computer.
Python is a high-leel language because the code itsel is relatiely Lnglish-
like. Indeed, any competent programmer looking at a well-designed Python
application should be able to work out what it is trying to achiee, whether or
not they hae eer learned the language itsel. 1his makes Python a good rst
language and an excellent choice or a wide range o purposes. But how does it
compare with Lnglish, or example
Eng||sh Python
Books Programs Books and programs tend to be about
one thing - whether that's a story or a
game.
Chapters Modules Books are split into chapters and
programs into modules - the difference
is that chapters are designed to be read
in order whereas modules can be used
multiple times.
Pages Functions Chapters are subdivided into pages
but, again, they are presented in a linear
order. Modules are made up of functions,
each responsible for a specifc task.
Paragraphs Blocks Usually blocks of code, within functions,
are processed in the order they appear,
just like paragraphs on a page.
Lines Lines Each line of a book contains one thought
or idea - each line of a program contains
one complete action.
Words,
numbers and
punctuation
etc
Statements,
commands,
operators and
separators etc
The nuts and bolts of both human and
computer languages. To become a
French speaker, you must learn French
words, and how they are put together
using grammar. To write Python code,
you learn the various statements that
have meaning in the language, and how
they are put together in meaningful ways.
U|t|mate Gu|de to Raspberry P|
38
So, both human and machine
languages hae much in common. Perhaps
the biggest dierence is that while you
don`t hae to speak perect German to
make yoursel understood to a natie,
computers are entirely unorgiing:
i you don`t get your language 100
correct, they won`t understand what you
mean. 1his is because, at their digital
hearts, computers understand only two
conditions - 1 and 0, right and wrong
- so there can be none o the ambiguity
or guesswork o human communication.
lortunately, Python is much easier to
learn than lrench, or example, when you
get it wrong, only you and your Raspberry
Pi will know. And the Pi won`t tell.

Python is what`s known as an ivterretea language. 1his means that when you
want to run a program you`e written, it must be saed as a text le and passed
to another program called the Python Interpreter, which reads in your code
and conerts it, on a line-by-line basis, into low-leel code that the computer
understands. \ou can contrast this with C, which is a coviea language: with C,
beore your code can be run, it`s entirely conerted into a machine-readable orm
that doesn`t need an interpreter.
All things being equal, compiled code runs more quickly than its interpreted
equialent, because it`s ready to go when it`s loaded, Python needs to rst load
its runtime engine - that is, the sotware the PC needs to run to conert the
language rom high leel to low leel - and then read in the text les and then,
nally, run the program.
\ou might wonder why, in that case, we hae interpreted languages. lirst,
because the dierence in speed is, or most real-world purposes, undetectable
on modern hardware een the Raspberry Pi,. Sure, i you wanted to create a 3D
engine or a rst-person ideo game, you`d write it in C or C--, rather than
Python to get the best possible perormance, but most games - and most other
programs - run perectly through a runtime engine.
Another important benet o an interpreted language is that it eliminates
a step rom the deelopment process. \ith Python you can write code, sae it
and immediately run it to see whether it works. \ith C, you must write, sae and
compile beore you get results. 1he more code you write, the longer this process
takes and the more time you sae with Python.
Python indentation makes it easy to
see which code is part of which block
U|t|mate Gu|de to Raspberry P|
39
\e`e described in the last chapter how the work a computer program does
can be diided into input, logic and output processes. In practice, this means
that Python programs tend to be made up o seeral text les that are usually
saed with a .py extension. In most cases there is a central le, normally called
main.py, which is the starting point: this is the text le that the interpreter is
instructed to run.
1he other les are linked to main.py using the import statement and, i you
could slow down the interpreter to human reading speed, you`d be able to watch
as it jumps in and out o those other les in response to your commands, but
always returning back to main.py. Geany makes all this simple because it has a
button on the toolbar or running the project - just make sure you hae main.py
in the edit window when you click!
The Python ph||osophy
Very ew programmers stick to a single language, and as you gain experience o
programming, you`ll notice that dierent languages seem to hae personalities`
o their own. Quite oten, you`ll nd you come to preer one language oer
another because its personality appeals to you - so it`s good news that Python
is easy to like.
As you`d expect rom a language that takes its name rom a 1V comedy
series, Python doesn`t take itsel too seriously. Some languages seem to hoard
their secrets and so attract ans who take great pride in oercoming their
limitations: the harder it is to get something done, the more they seem to like it.
Python takes the opposite approach and this has helped to build a community
o ans eager to help others get into the language.
The Zen of Python
J. There is one right way to do it. Some languages encourage you to nd
your own way o achieing something, proiding many dierent methods.
\hilst Python has plenty o nexibility when it comes to organising your code
which is your business,, when it comes to writing indiidual lines o code to
carry out a task there`s usually a single best way to go about it. I it eels as
though you`re going around the houses to get something done, there`s almost
certainly a better way.
2. Always choose simple over complex and complex over complicated.
Python is built to make it easy or you to write simple code. 1his is good
because it reduces bugs and makes it simpler to maintain your program -
whether you`re doing it or someone else. I you can`t make it simple then
make it complex, but keep it clear rather than complicated.
U|t|mate Gu|de to Raspberry P|
40
3. Get it done. Python is an incredibly productie language. It takes a
remarkably small amount o code to achiee useul results. \hereas
programmers using other languages boast about how many lines o code
their application contains, Python programmers brag about how ew lines
it took.
4. Organise for readability. As we`ll see, Python includes many ways o
putting code into blocks to get things done. \ou can also put blocks within
blocks within blocks, but this leads to code that`s dicult to understand.
I this happens when writing Python code, think about how you can put the
sub-blocks elsewhere into modules, unctions or objects or example, so
that the main code remains simple to read.
S. Have fun. \hereas coding in some languages can eel as though you`re
wading through treacle to do the simplest things - Objectie-C and Jaa,
I`m looking at you - using Python is a joy. I you don`t hae un writing
programs using Python then you might want to reconsider taking up
programming. As with any new skill learning to program is a challenge,
but Python makes it as simple as possible whilst doing its best to demand
little and delier plenty.
No cur|y braces
lf you've seen programming code at any point, you've probably seen curly
braces used to divide code into blocks. When the interpreter reaches an
opening curly brace - "{" - it knows that everything that follows belongs
together, until it gets to a closing brace. The problem with this approach is
that you end up with a lot of curly braces!
Traditionally, programmers have used tab indenting to make a visual
link: in other words, all the code that's indented by one tab stop belongs
together. However, most languages use the braces to group code, so
using tab stops is purely optional and anything that's optional tends to get
forgotten by busy programmers. The end result is a mess of braces that
can be very diffcult to understand.
Python solves this problem by not using curly braces at all, but relying
entirely on indentation. ln other words, if you don't organise your code to
be easy to read, it won't work; but code that does work, by defnition, is
readable. Remember, then, to take care with indenting. lt becomes natural
very quickly but it's also the biggest single source of errors by new coders,
especially those transferring across from another language.
Focus On
U|t|mate Gu|de to Raspberry P|
41
Python bas|cs: statements and express|ons
\e`e looked at how programs are split, like a book, into smaller and smaller
subdiisions. \hen you`re planning a noel, you need to think about the oerall
plot, character and setting - but actually writing the book is done one word at a
time, building up sentences, paragraphs, pages and chapters. Planning a program
inoles thinking about what you want to achiee through input-logic-output and
how that`s renected in its modules, objects and unctions, but it boils down to
typing code letter by letter into an editor.
1he programming equialent o the sentence is a .tatevevt - the smallest
chunk o code that makes sense on its own. Statements are usually made up o
seeral expressions, which are similar to erbs in that they get things done. 1hey
achiee this by creating and using ob;ect., whether these are built into Python or
created separately perhaps by you,.
One o the main adantages o Python oer lower-leel languages is the
range o pre-existing objects you can draw upon. I you were a C programmer
you`d spend much o your time manually setting up objects, using Python allows
you to bypass much o this and get on with making something useul quickly.
Start up Geany
\e`re going to look at some simple code, and the best possible way or you to
learn is to ollow along. 1o do this, start up Geany and click the 1erminal tab in
the Message window at the bottom. I you don`t see the Message window, click
the View menu, and select Show Message \indow` option. I 1erminal is not
amongst the tabs and you`re using Linux, then open up a terminal window and
type the ollowing line to install it.
sudo apf-gef 1nsfa11 11bvfe9
Now, restart Geany and the tab should appear. I it doesn`t then use
LX1erminal on the Raspberry Pi, or the 1erminal app in other orms o Linux.
I you`re using \indows, you`ll need to run the command prompt.
In all cases, now type python` into the 1erminal tab or window, to start
the Python interpreter. \ou should get a message reporting which ersion o
Python is running, ollowed by the prompt >>>, which indicates that it`s waiting
or input. \hat`s happening here is that you are talking directly to the interpreter
rather than loading a text le into it. 1his means you can try things out instantly,
which is what we`re going to do now.
Note: in the code snippets that ollow, i we want you to type code into the
interpreter ia the terminal,command prompt, we`ll start the line with >>>. Lines
that don`t begin with the cherons represent text the interpreter is printing` out
and should not be typed.
U|t|mate Gu|de to Raspberry P|
42

In basic algebra, you swap numbers or letters to help sole problems. lor
example:
3 ~ 6
In this case, is equal to 2. Variables work in a similar way - they act as
containers or alues. 1hese alues can be numbers, letters or een objects - the
ariable works as a conenient way o working on a alue and passing it rom
place to place.
Let`s look at this by re-writing the aboe code as it might appear in a real
program. Go to the 1erminal tab in Geany or a running terminal or command
prompt, and type the ollowing lines, pressing Lnter ater each don`t type
the cherons!,:
>>> a=2
>>> p1nf{a " 3}
6
1he rst line creates a ariable called a and gies it a alue o 2. 1he second
line is a that contains an object p1nf, and an expression a " 3,.
\hat makes the last part an expression is that it returns a alue that it
lt's easy to explore how variables work in Python using Geany's Terminal tab
U|t|mate Gu|de to Raspberry P|
43
has calculated. In this case, Python multiplies the ariable a which contains
a alue o 2 as set in the preious line, by 3 giing a result o 6. Note that in
programming, we use the asterisk to indicate multiplication.
1he result is sent to the p1nf object which, as you`ll hae guessed already,
simply writes the alue to the message window. \ou should see the number
appear on the next line.
lere`s a ariation:
>>> a = 2
>>> b = 3
>>> p1nf{a " b}
6
\ou`ll see the number 6 appear again, just as beore. 1his time two ariables
were multiplied together.
Let`s try a simple VA1 calculator. 1ype the ollowing and press Lnter:
>>>befoevA1=aW1npuf{"Add vA1 fo fh1s: "}
aW1npuf is a Python unction that asks the user to type something in. In
this case, we add a message asking them to tell us what gure they want us to add
VA1 to. 1his gure is then assigned to the ariable befoevA1.
\hen you see the prompt, type a number or example, 100, and press Lnter.
1hen type the ollowing, pressing Lnter ater each line:
>>>affevA1=oaf{befoevA1}"1.2
>>>p1nf{affevA1}
1he second line creates a new ariable, affevA1, which is the result o
befoevA1 the number you typed in, multiplied by 1.2 which has the eect o
adding 20, and, nally, we print this new alue out on the next line.
lt's possible to carry out some quite sophisticated calculations in Terminal view, so you can
try out different mathematical operations
U|t|mate Gu|de to Raspberry P|
44
Now, that`s all ery well but what i we wanted to use this program again
Commands typed into the interpreter will be erased rom memory when you
shut down your computer or Geany, we`re going to start creating les or our
programs so we can keep and reuse them.
In Geany, select lile|New don`t select a template, and type the ollowing
line including the # symbol,
#my f1sf pogam
Now sae the le to a location o your choice, making sure you add the
extension .py to the end o the le name. \ou should notice that your single line
has turned red. 1his is because any line that begins with the # symbol is ignored
by Python - it`s used to make comments in your code so that when you come
back to it you can understand what you were doing. Geany knows you`re writing
Python code because you added .py to the le name, so it`s turned the line red to
indicate a comment.
Retype all the lines o the VA1 calculator into Geany. Notice that, as you
type the rst ew characters o aW1npuf, Geany oers an autocomplete - press
Lnter to accept. It also shows you what inormation aW1npuf expects you to
type in - this can be useul to help you learn the specic commands and also
reduces bugs.
Once you`e typed each line, sae the le and then click the Lxecute button
on the Geany toolbar the cogs,. Ater a short delay, LX1erminal will pop up and
your prompt will appear. 1ype a number and Python will tell you what the total
including VA1 would be.
Now that the program has been saed, you can run it as many times as you
like by loading it into Geany and clicking Lxecute.
U|t|mate Gu|de to Raspberry P|
45
Data
\e`e seen that we can use ariables as containers and then do things with them.
\e`e used numbers in the example so ar, but Python proides seeral types
that you`ll be using a lot. lere are the most important:
Numbers
\hich o the ollowing are numbers
3290, 3290.123, 3290e3, 3290`
\e can nd out by making use o the act that Python is a .trovg, t,ea
language. 1his means that i you try to multiply two ariables that aren`t both
numbers, or example, it will report an error. PlP, which is another popular
programming language, would do its best to work out what you meant - but this
can oten result in bugs. Go back to the Geany 1erminal tab and type:
>>> a=3290 p1nf{a"5}
16450
Python prints the answer we`d expect. Notice that semi-colon It`s there to
allow us to put two statements on one line. Other languages use the semi-colon
at the end o eery line. In Python, we use it only when we want to use multiple
statements on a single line.
Var|ab|e names
You have plenty of fexibility about what you call your variables. You can
use any letter and number (although the frst character of a variable can't
be a number - "1ucy" is invalid, for examplej and also the underscore
character. There are a few words that Python uses itself, such as "else",
which you can't use. Don't worry too much, though, it will soon tell you!
The Python community uses some conventions which, in the main,
we'll follow in this book. ln the end, however, whatever system you use
needs to make sense to you. You can't use spaces in variable names as
they must all be one word.
One way to get around this is to use the underscore character;
another is to capitalise the frst letter of words after the frst - this is called
camelCase. lt's up to you whether you believe that myva1ab1e is a better
name than myva1ab1e; Python doesn't mind - both are more readable
than myva1ab1e though. For now, just try to be consistent.
Focus On
U|t|mate Gu|de to Raspberry P|
46
Now let`s try the next one:
>>> a=3290.123 p1nf{a"5}
16450.615
1his time, the number has a decimal point - in Python, numbers ormatted
in this way are called foat., because they hae a noating decimal point. Numbers
without points are called ivteger.. lloats take up a little more memory than
integers, so use them only i you need the extra precision. Note that when two
number types are multiplied the noating point 3290.123 and the integer 5,,
Python shows the answer in the most precise orm - in this case, as a noat.
Back to the terminal:
>>>a=3290e3 p1nf{a"5}
16450000.0
1his is another type o noating point number, except that this time we used
e3 at the end: this is a conenient way o signiying 3,290 x 10
3
or, to put it
another way, 3,290,000.
Now try:
>>>a="3290" p1nf{a"5}
32903290329032903290
1hat was unexpected! But completely logical - to Python. By putting quotes
around the number, you told Python that the characters 3290 were intended
to be treated as a .trivg rather than a number. A string is a sequence o letters,
numbers and symbols intended to be treated as text. \hen you multiply a string,
as we did here, Python thinks you want multiple copies so it just repeats them.
1o see Python throw a real wobbler, try this slightly dierent ersion with a
plus rather than a multiplication symbol,:
>>>a="3290" p1nf{a+5}
\hat happens Python shows an error message. 1his is because the + symbol
is interpreted in dierent ways depending on whether it`s dealing with numbers
- where it means to add the numbers together arithmetically - or strings, where
it means glue the second onto the end o the rst. So, "aspbey" + "p1"
becomes "aspbey p1", but aced with the expression "aspbey" +
3.141592 the number pi,, Python is unable to perorm the operation and will
simply return an error.
U|t|mate Gu|de to Raspberry P|
47
Although Python has seeral other number types, most o the time you`ll
stick to integers and noats. As you`e seen, to perorm arithmetic on numbers,
we use the " to represent multiplied by` and - to indicate addition. \e
can also process numbers in dierent ways using built-in unctions and modules
- the most useul being the mafh module.
\e`ll come across all o these later but, as a taster, here`s a list o the main
operators and unctions you`ll come across:
Operator/funct|on What |t does Examp|e
+ Numerical addition >>> a=9 b=a+5 p1nf b
14
- Numerical
subtraction
>>> a=9 b=a-5 p1nf b
4
* Multiply by >>> a=9 b=a"5 p1nf b
45
/ Divided by >>> a=9.0 b=a/5 p1nf b
1.
% Modulus (the
remainder of
a divisionj
>>> a=9 b=ax5 p1nf b
4
int Convert to an
integer
>>>a=9.0 b=a/5 p1nf
1nf{b}
1
round Round to the
nearest foat
>>>a=9.0 b=a/5 p1nf
ound{b}
2.0
foat Convert to a foat >>>a=9 b=oaf{a}/5 p1nf b
1.
O these, modulus is probably the only one that`s not immediately obious.
1hat`s partly because the percentage sign is commonly used to mean something
quite dierent. 1he term may also be unamiliar: it simply means the remainder
that`s let ater perorming a diision. So, 112 gies a result o 1, because 2 goes
into 11 e times with 1 let oer.
\ou`d be surprised at how oten this is used in programming: it`s excellent
or nding out i a number is odd or een, because any een number diided by 2
will hae a modulus o 0, whereas any odd number diided by 2 always results in
a modulus o 1. \ou might use this when shading the rows o a table alternately,
or example.
1he math module includes some additional useul and interesting unctions,
too. Python has two types o built-in unction: those such as round that can be
used as i they were part o the language, and those such as mafh.oo that can
U|t|mate Gu|de to Raspberry P|
48
only be used i the appropriate module is imported rst. Don`t worry, it`s ery
simple - take a look at these. Remember, they`re still all one line:
Funct|on What |t does Examp|e
math.foor Always rounds down to
the nearest integer
>>>1mpof mafh a=9.0 b=a/5
p1nf mafh.oo{b}
1.0
math.ceil Always rounds up to
the nearest integer
>>>1mpof mafh a=9.0 b=a/5
p1nf mafh.ce11{b}
2.0
math.pi Stores the value of pi >>>1mpof mafh p1nf mafh.p1
3.14159265359

String ariables are used to store things such as usernames, text we`re going to
display on-screen or example, the prompt we used earlier with aW1npuf,,
and other elements we might want to work with, such as database entries. 1o
tell Python you want a ariable to be a string, you can enclose the text in either
double or single quotes - it makes no dierence rom the interpreter`s point o
iew. 1hese are equally alid:
>>>myName="1ey"
>>>myName=`1ey`
1he only thing you need to look out or is to use the same marks at the start
and end o the string. I you try to use double quotes at the start and single at
the end, Python will return an error. I the phrase itsel includes speech marks or
apostrophes, simply use the other punctuation mark to enclose it:
>>>myName="1ey`s 1e1f1cs"
>>>myName=`1ey "1e1f1c" 1av1s"
It's maths - but don't pan|cII
lf the idea of having to deal with maths brings you out in a cold sweat,
there's good news. Far from being the diffcult-to-grasp subject you
might have found it at school, maths is at the heart of all computer
programming, so you'll get to see its practical use. Plus, the vast majority
of the maths-related programming you'll ever have to do is based on
simple arithmetic.
Focus On
U|t|mate Gu|de to Raspberry P|
49
In other words, i the string contains apostrophes, you simply need to
surround it with double quotes, and ice ersa. Gien that apostrophes and
single quotes turn up in text more oten than speech marks, it makes sense to
use double quotes by deault.
lold on - what i a piece o text contains both In this case, simply
add a backslash in ront o the character you`e used to enclose the string
where it appears within the text. 1his tells Python that the character is to be
taken literally. lor example, here`s how we might signal to Python that the
internal apostrophe in a phrase is to be treated as part o our string, and not as an
end-marker:
>>>myName=`1ey\`s fhe "1e1f1c" 1av1s`
Things to do with strings
Once you`e loaded some text into your ariable to create a string, Python allows
you to process it in all sorts o weird and wonderul ways. Python thinks o
strings as being similar to Scrabble tiles - each character on its own tile - which
makes it really easy to get at any letter or number, as well as dead simple to split
the string into bits. 1here are dozens o unctions designed to handle strings, but
the selection below will gie you an idea o how such unctions work and how
they might be used:
Funct|on What |t does Examp|e
len Tells us how long a
string is (including
spacesj
>>>p1nf 1en{"1ey 1av1s"}
12
+ Add (concatenatej
two strings together
>>>p1nf "1ey " + "1av1s"
1ey 1av1s
String[position| Return the character
at that position in
the string (the frst
position is zeroj
>>>a="1ey 1av1s" p1nf
a|0]
1
String[p1:p2| Return all the
characters between
two positions
>>>a="1ey 1av1s" p1nf
a|5:12]
1av1s
replace(old,newj Replaces an existing
set of characters with
another
>>>a="1ey 1av1s" p1nf
a.ep1ace{"av","ad"}
1ey 1ad1s
split Splits a string into
parts
>>>a="1ey 1av1s" p1nf
a.sp11f{}
|`1ey`, `1av1s`]
U|t|mate Gu|de to Raspberry P|
50

Strings and numbers contain single alues: Python`s 11sf object lets you store
multiple alues in one ariable. Imagine, or example, you had a database o
names such as 1erry 1rais` and you wanted to write to eeryone using their
rst name only. 1he names could be stored in a list object, then pulled out one at
a time so that the split, unction could be used to etch the rst name rom each.
lere`s how we might dene that list o names. Note that because the line
is longer than our margins can accommodate, we`e used the symbol >` to
indicate that the code spills oer to the next line. Don`t press Return when you
see this symbol, but keep typing to the end o the next line.
>>>11sfofnames=|`AndeW Anf`,`Cha11e Ch11ds`,`Maf1na >
Mongoose`,`Pefe Pubook`,`1ey 1av1s`,`vea ve1fy`]
Once this list is entered, to pull out 1ey we could do this:
>>>fh1sname=11sfofnames|4]
>>>p1nf "Iu11 name="+fh1sname
Iu11 name=1ey 1av1s
1o isolate just his rst name:
>>>f1sfname=fh1sname.sp11f{}|0]
>>>p1nf "I1sf name="+f1sfname
I1sf name=1ey
In Python - and most other computer languages - when you`re selecting
elements rom inside a ariable, the numbering starts with 0, not 1 as you might
expect. 1his number is called an and the item it etches is called an .
In the case o a string, speciying a single index gies you one character
rom the string as its element, with a list, you get the whole element. So, "1ey
1av1s"|0] would return 1` the rst character, whereas 11sfofnames|0]
would gie you Andrew Ant`.
A list can contain a mix o ariables, including other lists. lor example, or a
calendar diided into the weeks o the year, each week could be a list containing
the dates. 1his is how that would look or the beginning o 2013:
>>>yea2013=||31,1,2,3,4,5,6],|7,,9,10,11,12,13],|14,15,16, >
17,1,19,20],|21,22,23,24,25,26,27],|2,29,30,31,1,2,3]]
>>>Week=yea2013|1]
>>>p1nf Week
|7, , 9, 10, 11, 12, 13]
U|t|mate Gu|de to Raspberry P|
51
Note how each o the ve.tea lists is contained within square brackets. 1he
second line etches the dates or the second week in January remember, list
indexes start with 0,, that is, a list within a list. \ou could extract the date or
\ednesday o that week with Week|2].
As you can see, lists allow you to pack a lot o data into a single ariable.
Don`t worry i they seem a little complex right now. \e`ll be using lists a lot
and you`ll soon get to grips with them.
Dictionaries
\ou can think o dictionaries as super-lists. Like lists, they`re collections o other
objects, unlike lists, each element is gien its own name so you can access the
ariable directly. 1ry this:
>>> fam11y={`fafhe`:`1ey`, `mofhe`:`vea`, >
`daughfe`:`Jane`, `son`:`Jack`}
>>> p1nf fam11y|`fafhe`]
1ey
As you can see, each pair is gien a name and a alue. \e can then pull out
any dictionary element by using that name. As you`d expect, this means that each
name must be used only once per dictionary. \ou`ll also notice that dictionaries
use curly braces to indicate when they start and end, whereas lists use square
brackets - this is how Python knows which o the two you mean to create.
\ou can change the contents o both lists and dictionaries during a program.
I you typed in the amily example aboe, you could change it like this:
>>>fam11y|`son`]=`Jak`
>>>p1nf fam11y|`son`]
Jak
\ou don`t hae to use itera alues when you create a dictionary or list - you
can use a ariable instead.
>>>son="Jake"
>>>fam11y|`son`]=son
>>>p1nf fam11y|`son`]
Jake
1his time, we created a new ariable called son and assigned it a string
alue Jake`. \e can then use the ariable to eed into the amily dictionary.
Not particularly useul as it stands, but imagine i we were reading a database
o amilies: we`d then be able to change the son ariable to the name o each
U|t|mate Gu|de to Raspberry P|
52
son without haing to type them manually. A nal useul thing to know is that
you can add a new entry to a dictionary ater it`s been created. In this case, let`s
add grandparents:
>>>fam11y|`gandad`]=`Cy11`
>>>fam11y|`ganny`]=`Ld1fh`
>>>p1nf fam11y
{`daughfe`: `Jane`, `gandad`: `Cy11`, `mofhe`: `vea`, >
`fafhe`: `1ey`, `son`: `Jake`, `ganny`: `Ld1fh`}

Remember those little plastic balls that presented a random answer to your
questions when you shook them Let`s create our own ortune teller in Python
- in just a ew lines o code. \e`re going to want to run this more than once, so
re up Geany and type in the listing. Remember that the > on line 2 tells you to
keep typing, rather than pressing Return to start a new line.
1mpof andom
fofunes=|`Yes`,`Pobab1y`,`Cefa1n1y`,`Ouf1ook pom1s1ng`, >
`Nof sue`,`Ask aga1n`,`Doubffu1`,`No`]
hoWmanyfofunes=1en{fofunes}
aW1npuf{`1h1nk of a quesf1on, pess Lnfe fo fhe ansWe`}
Wh1chfofune=andom.and1nf{0,hoWmanyfofunes-1}
p1nf fofunes|Wh1chfofune]
1he code begins by importing the andom module, which will produce the
random numbers that allow us to pick an unpredictable answer each time the
program is run. On the ollowing line we create a list containing all eight o the
possible answers - eel ree to change them as you wish!
Arrays
lf you've ever used another programming language, you'll probably have
come across a||ays. ln that case, you may have already worked out that
||sts and d|ct|ona||es are the equivalent Python structures. Where you
might have used a standard array sorted by index in PHP, for example,
you use the ||st in Python. D|ct|ona||es are the equivalent of assoc|at|ve
a||ays in other languages. lf you've never programmed before, just bear
this in mind when you look at the documentation for other languages - this
is one aspect in which Python is quite unusual.
Focus On
U|t|mate Gu|de to Raspberry P|
53
On the next line we use the 1en unction to nd out how many answers
there are. 1his might seem unnecessary because we could simply count them
{hoWmanyfofunes=}, but by doing it this way we can add and remoe
answers at any point without aecting the rest o the code.
1he ollowing line uses the aW1npuf statement to pause the program,
displays the prompt and waits or the user to press the Lnter key.
Next, we use the and1nf unction to generate a number. Notice the
brackets ater and1nf 1hose are there to pass to randint. Parameters
are the bits o inormation the unction needs to work. In this case, we`re telling
randint to generate a number between 0 and hoWmanyfofunes-1. Gien that
there are eight ortunes in our example, this means and1nf will gie us a number
between zero and seen. \e need this because, in case you`e orgotten, the rst
item in a list has an index o 0, not 1 as you might expect. 1hereore, the last one
has an index o , not 8. Don`t worry i you nd this a little rustrating: the zero-
based indexing o lists and other similar objects catches out the most experienced
programmers rom time to time.
linally, on the last line o the program, we print the element rom fofunes
that has the index generated by and1nf.
Run the program a couple o times by clicking the cogs to make sure the
randomness is working, you should receie a dierent answer pretty much eery
time though it`s to be expected that things will repeat occasionally - that`s the
nature o randomness,. Also hae a go at changing the text in the answers and
adding or remoing some.
Congratulations! \ou hae just written your most adanced computer
program yet - a ortune-telling genie, in only six lines o code!
U|t|mate Gu|de to Raspberry P|
54
Mak|ng dec|s|ons and gett|ng th|ngs done
Oer 200 years ago, Joseph Jacquard demonstrated a new mechanical loom with
a unique eature: it used punched cards to control the pattern o the textile. Lach
card contained seeral rows o holes in specic locations. As the card was ed
through, row by row, small rods detected whether there was a hole. I there was,
that particular thread would be used, i not, it wouldn`t.
Since each row in Jacquard`s system oered 25-30 positions or holes, ery
complex patterns could be created with minimal human inolement. Loading up
another set o cards yielded a completely dierent pattern.
1his inention building on earlier work by others, was such an ecient way
to create textiles that it`s still in wide use today. It also gae rise to two important
concepts that ormed the oundation o computing: the idea that you can
program a series o operations in adance and, secondly, that a machine can be
gien more than one purpose by simply changing its sotware` or paperware`
in this case,.
Another similarity between Jacquard`s system and modern computing
becomes apparent i you take one row rom a set o Jacquard cards, and
represent a hole with a 1 and the absence o a hole with 0. \ou might get
a sequence like this: 1111100110000011001110011111111. In other words,
Jacquard used a 19th-century implementation o binary notation - the language`
l
m
a
g
e
:
S
t
e
v
e
K
i
m
b
e
r
l
e
y
(
h
t
t
p
:
/
/
e
n
.
w
i
k
i
p
e
d
i
a
.
o
r
g
/
w
i
k
i
/
F
i
l
e
:
L
o
o
m
.
j
p
g
j
A loom powered by punched cards in modern-day use in lndia
U|t|mate Gu|de to Raspberry P|
55
at the heart o all digital computers. 1he looms used mechanics in place o
programming languages but, essentially, they worked in a similar way. I a 1 was
encountered in any particular position, a certain action was taken, i it wasn`t then
either a dierent action was taken or nothing happened.
Jacquard`s system had only one ariable type a binary number,, whereas
Python has many including its equialent o the binary type, namely the
Boolean,. \e`e coered the most important o these - numbers, strings, lists
and dictionaries. Now it`s time to moe onto the coding equialent o the
mechanics that decide what to do with those ariables.
If-then-else
1he ability to make decisions based on the contents o ariables and then take
actions depending on the results is what separates computers rom calculators,
and iftbeve.e is the most important decision-making structure. In the case o the
Jacquard loom, each position on the card where there might be a hole is a simple
i-statement. In Lnglish, this could be written as:
lf fhee`s a ho1e hee use b1ue fhead,
ofheW1se use ye11oW fhead.
In Python, that statement might be represented as:
1f ho1e==1:
fhead=b1ue
e1se:
fhead=ye11oW
1he rst thing you`ll notice is how clear this code is - we mentioned in
chapter 2 how easy Python is to understand - and this sort o readability is one
o the main aims o the language. \e begin with the 1f keyword, and we ollow
this with the covaitiov that`s being tested.
In this case, i the ho1e ariable a number, is equal to 1 then the program
moes immediately to the next line. \ou`ll notice that this line is indented and
Python will now carry out all lines at that indentation in this case, there is only
one,. I the hole ariable is vot 1 then the interpreter skips down to the line
containing e1se and executes the code beneath it.
Python uses a colon to indicate the start o a block o code and then
continues until the indentation changes. In practice what this means is that you
add the colon, then hit the Lnter key to start a new line. \ou then hit tab once
Geany does this automatically ater a colon, and type your rst line - eery other
line that`s also tabbed once will be executed one ater another. 1he interpreter
will stop when it spots a dierent indentation.
U|t|mate Gu|de to Raspberry P|
56
1his is really important - Python is the only mainstream language that relies
entirely on indentation to mark blocks o code. 1he benet o this is that your
code is much clearer, as we explained earlier, but it takes a little getting used to.
Let`s look at a slightly more inoled chunk o code to help you understand.
Don`t type in the line numbers - these are just or our reerence. \e`e also let
some blank lines and colour-coded the dierent sections o this program, to help
you ollow the structure.
1npufname=aW1npuf{"Whaf 1s you name?"}
name1engfh=1en{1npufname}
aveagename1engfh=5
1f name1engfh>aveagename1engfh:
esu1f="1onge"
conuncf1on="fhan"
e11f name1engfh<aveagename1engfh:
esu1f="shofe"
conuncf1on="fhan"
e1se:
esu1f="fhe same"
conuncf1on="1engfh as"
esponse=1npufname+", you name 1s "+esu1f+" >
"+conuncf1on+" "+"aveage"
p1nf esponse
1his program asks the user to type in their name. It then works out how
many characters their name contains. 1he 1f block compares this with the
aerage length o a rst name the aveagename1engfh ariable, and puts
together a response depending on the result.
At line 5 - the start o the red section - the length o the user`s name is
compared to the aerage. I their name length is greater than the aerage we use
the mathematical symbol,, then the ollowing code in red is carried out. Once
Python reaches the end o the red text, it jumps out o the 1f statement and
straight down to line 15.
I their name length is not greater than aerage, the interpreter skips the red
text and then ealuates line 8. e11f is short or else i` - in other words, now
check whether this is true`. lere, we ask i their name length is e.. tbav , the
aerage. I it is, the code in blue is carried out, then Python jumps to line 15.
I the user`s name is neither larger nor smaller than the aerage, it must be
the same length. So, we use e1se as a catch-all: it means i none o the others
is true, then do this`. Note that Python will only arrie at this line i it hasn`t
1
2
3
4
5
6
7

9
10
11
12
13
14
15
16
U|t|mate Gu|de to Raspberry P|
57
already been dierted by one o the other 1f statements. 1his time it will carry
out the instructions in green beore jumping to line 15. Gie it a try with names
o dierent lengths to make sure it works.
\e`e now met three dierent ways to compare two ariables: equals ~~,,
less than , and greater than ,. 1he complete list o commonly used covari.ov
oerator. is shown here:
Operator What does |t do? Examp|e
== Are the two values the same? 1f a==b:
< ls the frst value |ess than the second? 1f a<b:
> ls the frst value more than the second? 1f a>b:
>= ls the frst value greater than or equa| to the
second?
1f a>=b:
<= ls the frst value |ess than or equa| to the second? 1f a<=b:
!=
or
<>
ls the frst value not equa| to the second? 1f a!=b:
In other words, when used in an 1f statement, i the answer to the question
is ,e. then Python executes the code immediately ollowing. I not, it skips to
the next block. linally, in case you were wondering, we use == rather than = or
equals` in conditional statements because Python assigns alues to ariables
using =. \atch out or this - it`ll trip you up sooner or later!
Repeating yourself
Using only iftbeve.e structures leads to ery short programs. Remember our
ortune teller app Lery time you wanted to ask a new question, you were orced
to run the program again. 1he Jacquard Loom, conersely, kept on going because
the cards were constantly ed into the machine ia a loop mechanism, otherwise
it would hae only created one line o thread.
Similarly, we can create loops in our programs, to run sections o code
multiple times. Almost eery useul Python program will include loops.
Ior..in
I you want to do something a specic number o times, the fo loop is the tool
to pick. Let`s take a look at a ery simple fo loop in action:
1npufname=aW1npuf{"Whaf 1s you name?"}
fo c 1n 1npufname:
p1nf c
U|t|mate Gu|de to Raspberry P|
58
Gie it a go. Create a Python le in Geany, type in those three lines and run
it. \hen prompted, enter your name. \ou`ll nd that Python then prints each
character o your name one at a time, each on a separate line.
1he structure o a fo loop is this:
fo |1feafo] 1n |co11ecf1on]:
Coectiov means any ariable that can be split into parts. Lists and dictionaries
are oten used but, in this example, it`s a string. terator is just the name we gie to
each bit as it`s pulled out. Put into Lnglish, our example would be or each letter
in input_name`, and it means that the next line will be repeated until it gets to
the end o the collection the name you typed in, in this example,.
So, let`s say you typed Jo Bloggs` at the prompt. Collection is thereore
Jo Bloggs` and the loop will start. 1he alue o our iterator will be J` to begin
with and so the print line will output that letter. Python now checks to see i
we`e reached the end o the collection and, since we haen`t, moes to the next
letter and prints o`. Bear in mind that i there were seeral lines ater the fo
statement, Python would execute them all as part o the loop - until it got to a
line that wasn`t in the same tab position, at which point it would go back to the
fo and start again.
\hat do you think would happen i you were to replace the rst line with the
code below Gie it a try.
1npufname={"Jo", "81oggs"}
\ou should nd that, this time, Python prints Jo` on one line and Bloggs`
on the next, rather than each word on its own line. \hy Because 1npufname
is now a list, not a string, so the iterator is now each element in the list, not the
indiidual characters in the string. In act, it`s much more common to iterate oer
a list than a string, largely because lists are so useul.
I you`e studied any other programming language, you`e probably come
across a fo structure that iterates a xed number o times. In BASIC this would
be written as fo n=1 fo 10, which would create a loop that ran ten times.
\hilst this might seem simpler, in practice you nearly always iterate through a
collection, so the Python approach is much more ecient. I you do need to
loop a xed number o times - or example, i you wanted to create a specic
number o objects - the Python equialent o that BASIC statement would be:
fo n 1n ange{10}:
Again, below this statement, simply place the code you want to be run ten
times in this case,, indented by one tab stop.
U|t|mate Gu|de to Raspberry P|
59

Most Python programs, especially games, include the Wh11e loop. In Lnglish,
this loop means while a particular condition is satised, keep looping`. lor
example, in a game you`ll usually hae a main loop that keeps repeating until the
Lscape key is pressed:
1mpof andom
useo11=aW1npuf{"Whaf numbe d1d you o11?"}
myo11=0
hoWmanyo11s=0
Wh11e myo11 != 1nf{useo11}:
myo11=andom.and1nf{1,6}
hoWmanyo11s+=1
p1nf myo11
p1nf "1f fook "+sf{hoWmanyo11s}+" o11s"
1his little program asks you to roll a die and input the number. It then works
out how many rolls it took to get the same number on aerage it should be
around six,. As you can see, we need to begin by importing the andom module.
\e also create two number ariables and set them to zero.
\hen Python gets to the Wh11e loop, it checks its alue or myo11
remember, we set it to zero when we created it, and compares that to the
number you entered. 1he != comparison means does not equal` so, i myo11
does equal the user`s number then Python will moe into the block. Since
you will hae typed a number rom one to six, myo11 will not equal useo11
the rst time, so Python will always run the loop at least once.
\e then set myo11 to a randomly generated number between one and
six to simulate our die roll. On the next line we increase the hoWmanyo11s
ariable by one to keep track o the number o rolls it took to get the same
number the user rolled. 1he += characters are used as a shorthand to increase
, that alue by one.
\e then print the randomly generated die roll, and Python jumps back to the
Wh11e line. 1his time myo11 will not be zero, it will be a number rom one to
six. Python checks whether this randomly generated number matches whateer
the user typed in earlier. I it doesn`t, it moes into the loop again. 1his continues
until they do match, each time generating and printing out a new random
number. \hen it does match, Python jumps to the nal line and prints out the
number o attempts it took.
\ou`ll notice that the Wh11e statement includes the 1nf unction. 1his is
because, when we use aW1npuf, the user`s input is treated as a string, een i
U|t|mate Gu|de to Raspberry P|
60
they`e typed in numbers. Python can`t compare a number with a string een i
that string contains only digits,, so we use the 1nf unction to conert the string
into an integer a number without a decimal point, that the Wh11e statement can
use to compare. Similarly, on the nal line, we use the sf unction to turn the
hoWmanyo11s number ariable into a string so it can be incorporated into the
print statement.
Decisions, loops, nesting and breaks
Loops and iftbeve.e structures are at their most powerul when they work
together. \ou can also create loops within loops this is called ve.tivg, and is
within is - and any combination o both. Indeed, a program o any complexity
at all will inole these sorts o combinations and it can be tricky to work out
where you are at any one time.
But this is where Python`s clear structure pays o: you know that all lines at
the same tab stop are at the same leel. 1his is much easier than the approach
other languages use o employing curly braces - in that case, unless you`e been
hyper-careul making sure your tabs line up, you`ll end up counting braces to see
where you are. In Python, i you don`t line up your tabs, the program won`t work
so you`re orced to get it right. 1his is a good thing!
Occasionally, you will want to break out o a loop beore it has completed.
I you`d created a Space Inaders-type game, or example, and were using a
Wh11e loop to update the position o the inaders seeral times a second, you
might want to exit to another part o the program i the user pressed l1 or help.
In that case, you use the beak statement, this exits the loop immediately and
proceeds as i it had completed.
1he conf1nue statement, on the other hand, skips straight back to the start
o the loop, preenting Python rom executing the remaining lines in that cycle.
Organ|s|ng your code: funct|ons, objects and modu|es
\e`e coered Python`s most important nuts and bolts - ariables, decisions
and loops - enough to create simple programs. loweer, to create a useul
application, you need a way to organise your code. Otherwise it would end up as
one long, indecipherable block o Python.
Going back to our book analogy, unctions are the equialent o paragraphs:
a chunk o lines with a specic purpose. lunctions can exist on their own or
within objects or modules. 1hey`re the smallest unit in the Python unierse.
Iunctions
A unction is a block o code with a particular purpose. By organising your code
this way, it can be used as many times as you like rom within your program.
lor example, you might hae a unction that reads the system clock eery
U|t|mate Gu|de to Raspberry P|
61
second to update the elapsed time in a game. Rather than haing seeral lines
o code to do this within the main program, this can be isolated into a unction
to be called as oten as you like. 1his has the added benet o making our main
code much simpler and easier to understand because it isn`t so cluttered. Lach
unction can be named, which, again, makes the program as a whole much easier
to understand.
Let`s get straight into a practical example. 1ype the listing below into Geany
and run it.
1mpof pygame,andom
pygame.1n1f{}
c1ock = pygame.f1me.C1ock{} # C1ock fo 11m1f speed
WlD1h=600 hLlGh1=600 8LACk={0,0,0}
sceen = pygame.d1sp1ay.sefmode{|WlD1h, hLlGh1]}
sceen.f111{8LACk}
def daWc1c1e{co1ou}:
x=andom.and1nf{1,WlD1h}
y=andom.and1nf{1,hLlGh1}
s1ze=andom.and1nf{1,5}
pygame.daW.c1c1e{sceen,co1ou,{x,y},s1ze}
def andomco1ou{m1n1mum, max1mum}:
ed=andom.and1nf{m1n1mum,max1mum}
geen=andom.and1nf{m1n1mum,max1mum}
b1ue=andom.and1nf{m1n1mum,max1mum}
co1ou=|ed,geen,b1ue]
efun co1ou
fo n 1n ange{100}:
c1ock.f1ck{25}
co1ou=andomco1ou{100,255}
daWc1c1e{co1ou}
pygame.d1sp1ay.updafe{}
aW1npuf{"Pess a key"}
1his simple program lls a black window with randomly generated circles.
\ou`ll remember that when we created 1f-fhen-e1se, Wh11e and fo..1n
blocks, we started the block with a colon and then indented the code that is to be
run. lunctions work in exactly the same way.
\e use the def keyword to ine a unction. \ou can see that, in this code,
1
2
3
4
5
6
7

9
10
11
12
13
14
15
16
17
1
19
20
21
22
23
24
25
26
27
U|t|mate Gu|de to Raspberry P|
62
we hae two unctions, which we`e called
daWc1c1e and andomco1ou - we
can use any name that makes sense to us
and ollows the rules or naming ariables.
\hen the program is run, Python
will begin at line 1 and immediately carry
out the instructions through to line 6
note the two ariables WlD1h and hLlGh1
are in capitals - this is the conention
or ariables whose alues stay the same
throughout. \hen it gets to line 8, it
comes across the rst unction: rather
than being immediately run, the code
within the unction is loaded into memory
to be used later. 1he same happens with
the second unction andomco1o,.
1he Python interpreter arries at line
21 and nds a fo..1n loop. In this case,
it`s a loop that will run exactly a hundred
times, since this is how many circles we
want to generate. In other words, Python carries out the code rom line 22 to line
25 one hundred times beore the loop ends. 1he interpreter then jumps down to
line 2, which waits or a key to be pressed beore ending the program.
1o run the code in a unction, we it - you can see the two ways to do
this on lines 23 and 24. 1he purpose o many unctions is to carry out a task and
send back the result. 1ake a wild guess at what line 23 is doing:
co1ou=andomco1ou{100,255}
\es, we`re creating a ariable called co1ou and assigning it the alue sent
back by the unction andomco1ou. Note that eery single element in this
statement was named by us, not Python, so we can choose words that make
sense to us so that our code is easy to understand.
But what about the set o brackets at the end \ell, hae a look at the
unction denition on line 14. Immediately ater we name the unction, we also
indicate what inormation the unction needs in order to run: in other words,
which araveter. must be passed to it. In this case, we need a minimum and
maximum alue or the colour see ocv. ov: Coovr or an explanation o how
colour works in Python,.
Since our background window is black, we don`t want colours that are too
dark. Look back at line 23 and you`ll see we`re passing 100 to the unction as the
rst parameter m1n1mum, and 255 as the second parameter max1mum,.
Our randomly generated circles are attractive
to look at, and were easy to implement
U|t|mate Gu|de to Raspberry P|
63
Lach o the rst three lines o this unction starting at line 14, generates a
random number between m1n1mum and max1mum 100 to 255 in this case,. 1he
ariable names hae been chosen to make clear what they represent. loweer,
ed, geen and b1ue at this point are just number ariables and nothing more,
their names are to help us remember their purpose.
In line 18, we create a new list ariable called co1ou containing each o these
random alues. Again, it`s just a list with a conenient name containing three
numbers o between 100 and 255 each. linally, on line 19, the efun command
sends the list back to the line that called it line 23,.

lold your horses - why does the ariable co1ou appear twice Surely that can`t
be right It is right, because ariables, by deault, only exist inside the unction
that gies birth to them. 1his is what we call their .coe. So, the ariables within
the andomco1ou unction ed, geen, b1ue, co1ou, can be accessed only by
lines o code also inside that unction. 1he co1ou ariable dened at line 23 is
not inside andomco1ou, so this part o the program can`t see` the one at line
18: this is why we must efun it.
laing said that, i a unction contains another unction, then ariables
declared in the arevt are accessible in the cbia. 1his is why sceen, which is
declared in the main code, can be used in daWc1c1e.
On the ace o it, you might think it would make more sense to allow eery
part o a program to see and use ariables rom eery other part, but there are
two reasons why this isn`t a good idea.
lirstly, each ariable takes up memory and, since the ariables within a
unction are there purely to help the unction to perorm its task, it would be
wasteul to keep them alie` once that task is complete. In act, it might cause a
program to run out o memory entirely.
Secondly, by keeping ariables oca to their unction, we can reuse the
ariable name in other unctions without causing a naming clash. 1his isn`t just
a matter o conenience: it also means that we can use reuse unctions across
lots o programs including unctions written by other people, without haing to
worry about accidentally duplicating ariable names.
Occasionally, you do need to hae access to a ariable throughout the
program. \ou can achiee this simply by using the g1oba1 keyword in the line
that originally denes the ariable:
g1oba1 myva = 999
lor the reasons gien aboe you should only use global ariables when
absolutely necessary, and this is ery rarely. 1here is usually a better way to do it
that aoids the problems they create.
U|t|mate Gu|de to Raspberry P|
64
So, back to our program. 1he andomco1ou unction generates a list
with red, green and blue colour alues and sends this list back to line 23. \hat
happens next On line 24, we call our other unction daWc1c1e. 1his time
the parameter is the colour we just receied back rom andomco1ou. On lines
9 and 10 we create random numbers between 1 and the width or height o the
program window.
Most programming languages use a coordinate system, with the point at
the top let-hand corner being 0,0. 1he axis is let to right so, on line 9, we
generate a horizontal position or our circle. 1he axis is top to bottom, so line
10 generates a ertical coordinate. Line 11 generates a random number between 1
and 5, which will be the radius o the circle, and line 12 uses a unction rom the
Pygame module to actually draw the circle on the screen.
\hen the interpreter reaches the end o line 12, it will see that there is
no next line at the same tab leel and go back to line 25 - there is no efun
statement this time because, well, there`s nothing to return!
1o make sure you understand, ollow the order o the lines executed by the
interpreter as it goes once through the loop rom line 21:
21,22,23,14,15,16,1,18,19,24,8,9,10,11,12,25
Lach o these iterations generates and displays one circle. Python repeats this
until 100 hae been generated, then drops down to line 2 to nish.
It`s quite possible that, at this moment, your brain is smouldering - but
don`t worry! It all becomes natural ery quickly, and this little program contains
most o the key concepts you need to understand to become a coder. lrom here
on in, it`s a question o broadening your knowledge and applying it to more
sophisticated and more useul, apps.

Modules sound intimidating, but they`re simply groups o unctions that are
saed in a separate text le and accessed by the interpreter as needed at runtime.
In act all Python les are modules, and the usual approach is to hae one main
module and one or more other modules with specic jobs. So, a word processor
might - in addition to its main module - hae modules called print.py, sae.py
and spellcheck.py.
Python comes with a range o standard modules - andom and mafh are two
that we`e used already - and there`s a huge selection o third-party modules,
including pygame.
\ou might wonder why Python doesn`t simply include all these unctions
into the main language, but it`s a matter o eciency: not all programs need
random or maths unctions, so the code is kept as lean as possible by only
including the modules necessary to the particular task.
Python`s built-in modules are aailable automatically. \ou simply use the
1mpof statement and they become usable. 1hird-party modules including your
U|t|mate Gu|de to Raspberry P|
65
own, either hae to be specially installed as with pygame, or saed as .py les
where the interpreter can nd them. In practice, this usually means including
them in the same older as your code. Let`s look at how we might
improe, our colour circle program using modules. lere`s the main module,
which we`e called snoW.py:
1mpof pygame, d1sp1ay
pygame.1n1f{}
c1ock = pygame.f1me.C1ock{} # C1ock fo 11m1f speed
sceen=d1sp1ay.sefup{}
fo n 1n ange{100}:
c1ock.f1ck{45}
co1ou=d1sp1ay.andomco1ou{100,255}
d1sp1ay.daWc1c1e{co1ou,sceen}
pygame.d1sp1ay.updafe{}
aW1npuf{"Pess a key"}
Co|our
ln Python, colours are made up by mixing red, green and blue, with
each component colour assigned a value representing how strong it is.
The possible values range from 0 to 255; in other words, there are 256
possibilities. This may seem odd - to a human it would make more sense
if the range were set to 0-100, for example - but doing it this way makes
complete sense to a computer.
Remember that, at their heart computers use binary notation. ln
binary, 255 is 11111111; or, put another way, 2
8
. ln other words, it's the
largest number that can be written in eight bits or one byte of data. So, 0
represents none of that colour, and 255 represents 100% of it.
For our pygame circle, the mixed colour is written as a list of the
three channels. Pure black would be [0,0,0| - in other words 0% of red,
green and blue - and pure white is [255,255,255|, with a mid-grey being
[128,128,128|. Pure red would be [255,0,0|, pure green [0,255,0| and a
pure blue would be [0,0,255|.
To get other colours, you simply mix the RGB channels. Magenta is
[255,0,255| and yellow [255,255,0|, whereas [128,64,0| makes a chocolate
brown. Geany has a colour mixer built in, which you can use to work out
the best values.
Focus On
1
2
3
4
5
6
7

9
10
11
12
U|t|mate Gu|de to Raspberry P|
66
And here`s a secondary module that we`e called d1sp1ay.py:
1mpof pygame, andom
WlD1h=600 hLlGh1=600
def sefup{}:
8LACk={0,0,0}
sceen = pygame.d1sp1ay.sefmode{|WlD1h, hLlGh1]}
sceen.f111{8LACk}
efun sceen
def daWc1c1e{co1ou, sceen}:
x=andom.and1nf{1,WlD1h}
y=andom.and1nf{1,hLlGh1}
s1ze=andom.and1nf{1,5}
pygame.daW.c1c1e{sceen,co1ou,{x,y},s1ze}
def andomco1ou{m1n1mum, max1mum}:
ed=andom.and1nf{m1n1mum,max1mum}
geen=andom.and1nf{m1n1mum,max1mum}
b1ue=andom.and1nf{m1n1mum,max1mum}
co1ou=|ed,geen,b1ue]
efun co1ou
In a nutshell, we`e exported all the unctions to do with drawing to the
screen to this new module called d1sp1ay.py. Doing this was simply a case o
creating a new Python le in Geany and pasting the two existing unctions into
it. \e`e also added import statements or pygame and andom to the top o this
module, since they`re needed by these unctions, and we`e moed the WlD1h
and hLlGh1 ariable assignments to this module, too, since this is where they`re
used. 1he only major change we made is moing all the screen setup code into a
unction called setup.
Back in our original Python le our ma1n module,, haing moed the code
across to d1sp1ay.py, we need to make a ew other changes. lirstly, we need
to import our new module on line 1 note, we`e remoed the andom import
because it isn`t needed or the code in this module,. Secondly, we need to call the
sefup unction in d1sp1ay.
1here are a ew things to notice here. lirstly, i we want to call a unction in
another module, we add the name o the module to the beginning so that Python
knows where to nd it. Secondly, i a unction has no parameters, as here, we add
empty brackets. linally, note that the setup unction returns a screen ariable:
this is because this ariable is needed by the daWc1c1e. \hen we created our
1
2
3
4
5
6
7

9
10
11
12
13
14
15
16
17
1
19
20
21
U|t|mate Gu|de to Raspberry P|
67
sefup unction, we put sceen inside it. 1his means it`s no longer accessible by
daWc1c1e, so we must return it rom sefup to the main program, then, in line
9, we add it as a new parameter to our daWc1c1e code.
\hilst this might seem a bit o a palaer or ery little gain, just take a look
at snoW.py in its new orm. Remember, this is the main program. By remoing
much o the display code to another module, it`s now much shorter and ery
clear. Ater all, we can understand what daWc1c1e and andomco1ou do
rom their names, so we don`t need to see the code unless there`s a bug, in
which case we know where to look!,.
1he more sophisticated your program, the more benet you stand to gain
rom organising your code into modules. It`s a good habit to get into thinking in
modules right rom the start.
A qu|ck c|ass |n object-or|ented programm|ng
Many introductory books aoid explaining object-oriented deelopment
because it`s seen as an adanced topic. But it`s an essential part o modern-day
programming, and something you`ll need to understand i you`re to do serious
coding, let alone hae a career in programming.
lortunately, it`s a pretty simple concept to get your head around - and it`s
ery useul, especially or creating games, so we`re going to tackle it head on.
\e`ll leae some o the nitty-gritty to later chapters: or now the point is to
understand what we`re doing when we use object-oriented programming OOP,
techniques and why.

\e introduced objects on page 35. Procedural programming is like writing code
to directly control a puppet. Object-oriented programming is more like placing
the code inside the puppet itsel, so you can simply tell it what to do and it will go
o and do it independently.
1he code or an object is contained in a ca... \ou can think o this as a
blueprint. Lach time a new object sometimes called an iv.tavce, is needed, Python
uses the class as its model or that object. In other words, i you needed lots o
on-screen puppets, you could write just one class, then create a fo..1n loop to
create hundreds at once.
One o the main benets o OOP is evca.vatiov. 1his means that eerything
an object needs to know is contained within its own code. \ou could, in theory,
take an object and use it in another program without haing to change it at all.
In this way, objects are similar to modules, and they`re made up o unctions
just as modules are unctions are oten called vetboa. when they`re inside classes,.
Objects can sit within the main code, within modules, or in a le o their own.
1he more reusable they are, the more likely you`ll want to store them separately.
U|t|mate Gu|de to Raspberry P|
68
Perhaps the most powerul eature o OOP is ivberitavce. \riting a single class
or puppets is all ery well, but marionettes come in many orms and the code
or creating a Pinocchio would be dierent to that used or creating Mr Punch.
Inheritance lets you dene a generic class containing the code that applies to all
puppets, and supplement it with child classes to dene more specic cases.
So, let`s say the generic class includes code or drawing a head, arms and legs.
\hen we come to create the Pinocchio child class, we can simply write new code
to add support or his extending nose. Mr Punch doesn`t hae standard puppet
legs, so his child class might orerriae the daW1egs unction o the generic class
with his own daW1egs unction, whilst keeping all the rest o the code intact.
1his approach means you, as a coder, only hae to write the minimum code.
It also becomes ery easy to create new child classes, since most o the work
is already done. And each change you make to the generic class is immediately
inherited by all child classes, making bug xing much simpler.
A simple class
Let`s hae a look at how we can reise our circle drawing program to use object-
oriented principles. lirst we`ll write the main module, below, then we`ll add a
module containing a class called c1c1e, listed opposite:
1mpof pygame, c1c1e
pygame.1n1f{}
c1ock = pygame.f1me.C1ock{} # C1ock fo 11m1f speed
WlD1h=600 hLlGh1=600
sceen = pygame.d1sp1ay.sefmode{|WlD1h, hLlGh1]}
8LACk={0,0,0}
sceen.f111{8LACk}
c1c1es=|]
fo n 1n ange{100}:
c1ock.f1ck{45}
c1c1es.append{c1c1e.C1c1e{sceen,WlD1h,hLlGh1}}
pygame.d1sp1ay.updafe{}
c1ock.f1ck{1}
fo c 1n c1c1es:
c1ock.f1ck{45}
c.c1eac1c1e{sceen}
pygame.d1sp1ay.updafe{}
aW1npuf{"Pess a key"}
1
2
3
4
5
6
7

9
10
11
12
13
14
15
16
17
1
19
20
21
22
U|t|mate Gu|de to Raspberry P|
69
1mpof pygame, andom
c1ass C1c1e:
m1n1mum=100 max1mum=255
co1ou=None
popef1es=|]
def 1n1f{se1f,sceen,W1dfh,he1ghf}:
se1f.andomco1ou{}
se1f.daWc1c1e{sceen,W1dfh,he1ghf}
def daWc1c1e{se1f, sceen, W1dfh, he1ghf}:
x=andom.and1nf{1,W1dfh}
y=andom.and1nf{1,he1ghf}
s1ze=andom.and1nf{1,5}
se1f.popef1es=|x,y,s1ze]
pygame.daW.c1c1e{sceen,se1f.co1ou,{x,y},s1ze}
def andomco1ou{se1f}:
ed=andom.and1nf{se1f.m1n1mum,se1f.max1mum}
geen=andom.and1nf{se1f.m1n1mum,se1f.max1mum}
b1ue=andom.and1nf{se1f.m1n1mum,se1f.max1mum}
se1f.co1ou=|ed,geen,b1ue]
def c1eac1c1e{se1f,sceen}:
pygame.daW.c1c1e{sceen,{0,0,0}, >
{se1f.popef1es|0], >
se1f.popef1es|1]},se1f.popef1es|2]}
1he c1c1e class completely replaces our display module. 1his in itsel
demonstrates object-oriented thinking: rather than creating a module that draws
circles oer the screen, we instruct each circle to draw itsel. 1hat`s why we name
the class this way.
\ou`ll see immediately that two o the unctions o the display module are
present, largely unchanged, in our c1c1e class. \e begin with the keyword
c1ass, which is used to dene the block containing all the code relating to that
class. \ou can see that eery line within the block is indented, again, this is how
Python knows it belongs to the block.
Creating a class makes a special type o unction aailable, which is always
called 1n1f with two underscores either side o the name,. 1his is short or
initialise` and, as you might imagine, is run when the object is rst
created,. In this case, the 1n1f unction automatically runs the two
1
2
3
4
5
6
7

9
10
11
12
13
14
15
16
17
1
19
20
21
22
23
24
25
26
U|t|mate Gu|de to Raspberry P|
70
unctions we created or the display module, so as soon as it`s created our circle
is drawn. 1his isn`t always the case: the 1n1f unction is oten used to set up
the object or later use.
\ou may hae spotted that the main dierence in the code is the addition o
the se1f keyword. 1his is critical to understanding how objects work. As you`d
expect, se1f reers to the specic circle object being created at that moment.
Remember the loop that runs 100 times in our main module Lach time it runs,
it will create a new object, each o which has its own se1f. It`s just as i you met
100 children: you might struggle to tell them apart, but each would themseles
know who they were. So, each unction has a se1f parameter that`s used to reer
to itsel.
linally, the other main change is that a new unction called c1eac1c1e
has been created. Guess what this does \e`e added a new ariable to the object
called popef1es note: it`s a conention to use the underscore beore the
names o class ariables, but it isn`t compulsory, into which we sae the and
coordinates o this particular circle, along with its size.
Now go back to our main module. lirst, we replace d1sp1ay in the import
statement with c1c1e. \ou`ll see that we`e moed the initial setup code back
Never do |t tw|ce
As a programmer, one of the most important attitudes to develop is a
distaste for writing the same code twice. Whenever you fnd yourself
repeating chunks of code, it should send a shiver down your spine: this
is your warning that you should be fnding a better way of doing it. For
example, could you spin the code out into a function? This is marginally
more hassle the frst time you do it, but it pays dividends once you're able
to use that function the second, third and fourth time.
ln fact, most programming takes this organic form. You spot an
ineffciency in your code and tidy it up by creating a function. Let's say, for
example, that you fnd yourself asking the system to provide the current
time repeatedly. This takes several lines of code because you want it
returned in a specifc way. You decide this would be better in a function so
you create one.
Later, you fnd yourself doing a similar thing for the date or, perhaps,
implementing a countdown timer. You create functions for each and then
realise they could be organised together into a separate module called
f1me11b. This is great, but then you realise that you need to have multiple
countdowns running at once - so you fnally decide to take that particular
function and turn it into a class.
Focus On
U|t|mate Gu|de to Raspberry P|
71
here, because it doesn`t make sense or it to be within the C1c1e object. \e also
create an empty list called c1c1es. Our main loop has become een simpler, and
line 12 is the critical one. Just as with the d1sp1ay module, i we want to reer to
a unction within an imported class we must start with the name o the import -
c1c1e - ollowed by a ull-stop and then by the name o the unction.
In this case, because we`re creating a new object, we simply reer to it. By
conention, class names start with a capital letter, and our class name is C1c1e
so that gets us to c1c1e.C1c1e. 1his will run our 1n1f unction, requiring
three parameters o sceen, WlD1h and hLlGh1. So now we hae c1c1e.
C1c1e{sceen,WlD1h,hLlGh1}. linally, so that we can use our objects later, we
load them into a list using the append method, this simply adds one to the end.
\e`ll end up with a list that`s 100 objects long.
So the eect o line 12 is to create a new object based on the C1c1e class
which results in a circle being drawn on the screen,, and to add that object to a
list. I we were just showing the circles, then the list wouldn`t be needed but, as
you can see in the second fo..1n loop, we also want to erase them.
Line 1, then, says or eery circle in the list`, line 18 sets the speed and
then line 19 calls the c1eac1c1e unction in the class. So, it`ll pull out each
circle object, beginning with the rst and, because each circle knows where it was
painted on the screen and how big it was, we can use this sel-awareness to paint
a black circle on top, eectiely erasing it.
1he old-school way o doing this would hae been to keep track o all o
this within the main program. 1hat`s not as neat or a simple program such as
this, and the more sophisticated a class is, the more useul it is to hae objects
look ater themseles. It also makes it possible to reuse your code and objects
elsewhere since they`re ully sel-contained.
Run the program always run the main module, not the class, and you should
see the random eld o circles appear, pause or a moment, and then just as
sedately disappear in reerse order.
1his program has been an exercise rather than a unctional application. lor
example, there`s no user input at all. loweer, by adding input it could be turned
into something more useul. Imagine i you painted circles across the whole
screen and then paused the program. I you noted the position o the mouse
pointer, you would be able to tell when it moed and respond by remoing the
circles using the code rom line 1. \hat would you hae A simple screensaer
- in ewer than 50 lines.
Again, don`t worry i not all the principles o object-oriented programming
hae ully sunk in. 1he aim o this introduction is simply to start you thinking
in an object-oriented way. \ou`re now equipped with all the main concepts you
need to build a career, or simply personal expertise, in programming. 1he rest o
this book will help rm up what you`e learned and show you how it works in
practice as we create a working game.
U|t|mate Gu|de to Raspberry P|
72
Extend|ng Python
\e`e already seen that Python has a number o built-in unctions - or example,
those that handle strings, lists and dictionaries - as well as a range o modules
that are supplied with the language but must be ivortea beore being used, such
as those containing operations or random numbers and time. loweer, part o
Python`s great ersatility comes rom the huge library o ree third-party modules
out there. 1hese range rom ery popular mainstream libraries, such as Pygame,
to those aimed at niche uses, such as connecting a Raspberry Pi to a robot.
Let`s take a quick look at some o the most important modules - especially
those we`re going to use in our game and project.
Pygame
Don`t be ooled by the name: Pygame
helps you deelop games, but it can also
do much more than that. Remember our
clock widget, the rst thing we coded
to test our setup was working \e used
Pygame to display the window and render
the text in a nice orm. Most o our
examples so ar hae used Pygame, een
though we haen`t yet started coding a
game. Pygame unctions include:
Display Create windows, or allow
games and projects to run ull-screen,
Draw Draw a whole range o rivitire
shapes such as rectangles, polygons,
lines, ellipses, circles and arcs and optionally ll them with colour,,
Surface Draw objects in memory, then paint them to the display in one go -
essential or games with lots o graphics,
Iont Lmbed onts into your project, so you can display them without relying
on the end user haing the same ont installed on their system,
Image, Transform A wide range o image manipulation unctions that
might be used to create specialised picture-processing applications,
Sprite Create sel-aware sprites with built-in collision detection, making
complex games much simpler to create,
Pygame isn't just for creating games -
download it from www.pygame.org
U|t|mate Gu|de to Raspberry P|
73
Mixer, Music, Movie Add sounds and
ideos to your projects,
Lvent Listen` or player action such as
key presses or mouse moements.
Pygame is written mainly in C, so it gies
good perormance in games remember
that one o Python`s strengths is its ability
to use properly prepared C libraries,.
It`s also aailable or a wide range o
platorms: you can create games and apps
or eery mainstream desktop platorm,
and a ew not-so-common ones!
Saving data
It`s important to be able to sae data between sessions, and load it back in as
required - whether you want to allow users to sae their position within a game,
store records to a database or exchange inormation with a web serer. Python
oers a whole range o methods or achieing this, but the main ones - in order
o increasing complexity - are: the I11e object, p1ck1e and sq11fe3.
Iile
1he I11e object lets you create, sae to, read rom and delete text les. Anything
you sae is conerted to text so, essentially, you`re reading and writing strings.
1hat doesn`t mean you can`t use I11e to handle sophisticated data, though. Let`s
take a ery simple example. 1ype this listing into Geany and sae it as f11e1.py:
f1sfname=aW1npuf{`1ype you f1sf name...`}
secondname=aW1npuf{`1ype you suname...`}
savef11e=open{`dafa.daf`,`W`}
savef11e.W1fe{f1sfname+`\n`}
savef11e.W1fe{secondname+`\n`}
savef11e.c1ose{}
p1nf{`5aved`}
f1sfname=None
secondname=None
openf11e=open{`dafa.daf`,``}
name=openf11e.ead{}.sp11f{}
f1sfname=name|0]
secondname=name|1]
p1nf f1sfname+" "+secondname
With the aid of Pygame it's possible to
write professional-quality games in Python
1
2
3
4
5
6
7

9
10
11
12
13
14
U|t|mate Gu|de to Raspberry P|
74
Clearly, the irst two lines ask the user to type in their irst and second names.
1he interesting stu begins on line 3, where we create a new ariable using the
f11e object`s open method remember, unctions` are called methods` when
inside objects,. \e pass in the name o the text ile: this can be any name we
choose as long as it`s alid or our operating system i the ile doesn`t exist, it
will be created by Python at this point,. 1he `W` parameter means that we want
to write to the ile, in other words, we want to sae some data.
In line 4 we write the irst name. By appending `\n` we add a new line. 1his
is the f11e equialent o pressing the Lnter key - essentially we`re using f11e
to organise text by line, so by inserting a \n at this point the surname will appear
separately a line below. \ou could also simply add a to each saed record
- the pipe symbol |`, or example - but you must choose a character that you
would neer use within a record.
laing written the second name to the ile, we then close it. 1his tells the
operating system to sae the ile with its new contents.
\e`re now going to open it up again and read the contents back in. Lines
9 and 10 clear the name ariables, so we can be sure we`e read in the ile and
not simply kept what the user typed. On line 10 we create a new f11e object,
using the same name, but this time with the parameter ``, which reads in the
contents o a ile but leaes it unchanged. Since iles only contain text, openf11e
is a string at the moment: this means we can use the sp11f{} unction to take
this text and create rom it a list with each o the lines as a separate element.
A simple exercise using the h1e object - this time running on an
Ubuntu virtual machine
U|t|mate Gu|de to Raspberry P|
75
lor example, i the user`s name was Jo Bloggs, printing vave would result in:
|`Jo`,`81oggs`]
1o retriee the irst name we use name|0], or the surname we use name|1].
Run the program and you`ll see your name reappear in the terminal. 1here`s an
een better test, howeer: ind the ile dafa.daf i you`e used the same name,
and open it in a text editor. \ou should see the names one per line. 1he f11e
object is the workhorse o Python ile input,output, it`s pretty simple to use.

1he great beneit o p1ck1e is that, unlike f11e, it can take any data orm and
sae it to a ile. It can also unpickle` the data back to exactly its original orm. In
act, p1ck1e is speciically built to augment the built-in f11e object and make it
more useul. Again, this is best understood through a short example, which we`ll
call p1ck1eLxamp1e.py:
1mpof p1ck1e
savedafa={`usename`:`Joe 81oggs`, >
`scoe`:9234,`max1eve1`:5}
savef11e=open{"savedafa.daf",`Wb`}
p1ck1e.dump{savedafa,savef11e}
savef11e.c1ose{}
#zeo va1ab1es, ead f11e back 1n
pogessf11e=open{"savedafa.daf",`b`}
pogessdafa=p1ck1e.1oad{pogessf11e}
p1nf "Dea "+pogessdafa|`usename`]+ >
", you dafa \n"+sf{pogessdafa}
Note that we must begin with an 1mpof statement - p1ck1e is part o the
standard Python install but, because it isn`t quite as basic an object as f11e, it
must be explicitly added to the code. \ou don`t hae to install it, howeer, i
you`re using \indows, Mac or Linux including Raspbian,.
On line 2 we create a aictiovar, containing basic data, including the user`s
name, their current score and the urthest they`e reached in our imaginary game.
Next, we create a f11e object with the parameter `Wb`, which stands or write
bytes`. p1ck1e uses its own storage ormat, so we need to speciy that it`s writing
bytes o data, not text. 1his means the ile it creates will look like gobbledygook
i you open it in a text editor.
Line 4 uses the p1ck1e.dump method to sae the data - passing it the data
itsel it could be any ariable type, we`re using a aictiovar,, and the f11e object.
\e then close the ile.
1
2
3
4
5
6
7

9
U|t|mate Gu|de to Raspberry P|
76
In a real game, you`d probably want to read this data back in later or, indeed,
in a later game session. 1he code rom line achiees this. \e create a new f11e
object, this time with the `b` parameter because we`re reading bytes back in. On
line 8, we create a new ariable and use it to receie the data rom p1ck1e using
the 1oad method. Line 9 prints it out.
p1ck1e is a ery powerul and widely used module. Its main adantage oer
the simpler f11e object is that you don`t need to write code to ar.e read and
conert, the saed data when you want to retriee it: p1ck1e simply gies it back
to you in the same ormat you used to sae it. I you think about the amount
o inormation you`re likely to want to sae in your game a leaderboard, or
example,, you can appreciate how much simpler p1ck1e makes this - not only
saing time, but reducing the chances o bugs creeping in.

I you get into commercial programming then you`ll encounter SQL Structured
Query Language - and no, it is vot pronounced Sequel`, pretty quickly. 1his is a
database system that`s ideal or starting large amounts o structured data - such
as or a customer database, or a ootball league manager game.
1he main adantage o reatiova aataba.e. the sort o databases SQL is most
oten used with, is that they make the retrieing o data lightning-quick. Ater all,
i you hae a large database o Conerence League ootballers and you want to
list all players or sale, this needs to happen in the blink o an eye to aoid your
game appearing slow.
SQLite is a halway house between the ease o use and ersatility o p1ck1e
and the ull-at power and complexity o, or example, MySQL the database
ormat used by a large percentage o websites,. It`s a cross-platorm standard,
Pickle allows us to store data to a fle
exactly as it is, then read it back later
U|t|mate Gu|de to Raspberry P|
77
represents data in a lat orm similar in concept to card indexes. It isn`t good
at cross-indexing data but it`s ery good at simple retrieal - or example, it
would make mincemeat o our players or sale` query.
Python`s SQLite3 module allows you to create, edit, read and write SQLite
iles and, i you intend to ind work as a programmer, it`s a good place to start
learning about SQL whilst also being ery useul. SQL itsel is standard across its
many orms so your experience o SQLite3 with Python would gie you a head
start when aced with learning any other mainstream database.
1o do things with SQL databases, you write and then execute those
queries using your chosen SQL engine. So, our Conerence League player search
might look something like this:
5LLLC1 " IkOM p1ayes WhLkL 1eague = `conf` >
AND sfafus = `fo sa1e`
It really is that straightorward - but since this isn`t a book about SQL,
we`ll moe along. 1he key point to bear in mind is that it`s nothing to be
rightened o. \ou can carry out most database unctions with a small range o
commonly used techniques.
Congratu|at|ons
So ar in this book you`e seen how to set up your Raspberry Pi and your
coding enironment. \ou`e learnt how to think like a programmer. And
you`e had a whistle-stop tour o the basics o Python and object-oriented
programming, so you now know the most useul ariable types, how to create
and use unctions, modules and objects, and how to structure your code
using decisions and loops. \ou`e also learnt about the extra unctionality
Pygame adds, and explored the arious ways to store and retriee data using
Python modules.
1he best way to reinorce this knowledge and make sure it sticks is to put
it into practice, so in the coming chapters we`re going to coer, in great detail,
the deelopment o three ery dierent projects. \ou`e learned a lot so ar, but
don`t worry i you don`t remember eerything we`e coered - een the most
experienced programmer considers Google to be their best riend. Programming
is much more about technique and knowing which tool to use in a gien situation
than about remembering the speciics o how Python, or any other language,
implements that tool.
Once you`e completed the projects, you should hae a ery good idea o
which situations call or a loop, which require a decision, and when it`s best to
spin out your unctions into separate objects. 1his only comes through practise,
so once again it`s time to roll up your sleees and get stuck in.
U|t|mate Gu|de to Raspberry P|
78
In this section we`re going to build on what we`e learnt to design and create a
simple game. By doing this, not only will we create an end product that will be
un to play, but we`ll also explore many o the general programming skills you`ll
be able to transer to uture projects.
1o get the most rom this section, we strongly recommend that you type in
the exercises as we go through. 1his way, you`ll better understand what each line
and statement does within the game. loweer, i you need to sae time or check
your work, the resources can also be downloaded rom WWW.p11ab.nef/code.
Iools rush in
loweer simple the game, you shouldn`t just sit down at your computer and
start coding right away - such an approach will result in nothing but chaos and
rustration. \ou need to begin by thinking careully about exactly how your game
is going to work and, rom that, generate a list o the tasks both you and your
code will need to complete.

Chapter Four
U|t|mate Gu|de to Raspberry P|
79
Genres of games
According to \ikipedia, there are 13 major genres o game, including action,
role-playing, strategy, sports and puzzle. One way to come up with game ideas is
to look through the genres and think about examples rom each. Another option
is to play plenty o games - on a phone, console or computer - and think about
what you enjoy most. Don`t bite o more than you can chew, though. A Space
Inaders clone is certainly achieable by a new programmer, whereas a rst
person shooter inspired by Ca of Dvt, probably isn`t a realistic ambition - not as
a rst project, at least!
The concept
In this case, we`re going to choose a
simple shoot-em-up called Pi Splat. \e`re
using the Raspberry Pi as our inspiration
so, naturally, our targets are going to be
ruit. 1he concept can be summarised as:
!e`re beivg ivraaea! erera t,e. of frvit
fa frov tbe to of tbe .creev - bvt berare,
vo.t are oi.ovov.. |.e a vobie gvv atforv
to ae.tro, oi.ovov. frvit, bvt aor ra.berrie.
tbrovgb to reacb tbe grovva. !bev evovgb
ra.berrie. bare avaea, tbe avetar, aefevce. ri
be actiratea ava tbe ovatiov ri be .area.
Okay, it isn`t exactly the most original
concept but it`s simple and un - two
excellent traits or our rst game. Our
next job is to decide on the rules or our
game, and the ictory conditions.
Pi Splat is a simple, fruit-based shoot-'em-up game
Spec|cat|ons
lf you follow a career in programming, you'll quickly come across the
concept of the "specifcation". This is a document that is created before
programming starts and fully details what the application does, how it
works and what it looks like. Different programming teams use different
specifcations and many now adopt a more rapid development approach
called "agile", which minimises the up-front work and focuses more on
smaller work units that evolve as the project progresses. For a simple
game, our specifcation will be brief.
Focus On
U|t|mate Gu|de to Raspberry P|
80
Rules
In real lie there`s nothing to stop you creating your own card game and making
up the rules as you go along. loweer, the computer needs to know what to do
in eery conceiable situation. In this case, the game rules are simple.
1. lruit appears randomly and drops ertically down the screen, disappearing i
it reaches the bottom.
2. 1he gun turret can be moed let and right along the bottom o the screen.
Pressing the lire button launches a bullet up the screen.
3. I a bullet collides with a ruit, the ruit is destroyed.
4. I the destroyed ruit is not a raspberry, the player receies points.
5. I the destroyed ruit is a raspberry, the player loses points.
6. I a raspberry reaches the bottom o the screen, the player receies points.
. I any other ruit reaches the bottom o the screen, the player loses points.
8. Once a set number o raspberries hae reached the bottom, the leel ends.
9. As leels pass, the speed o the alling ruit increases.
Victory condition
A game needs to hae an aim. In games that hae multiple leels, there is oten
one ictory condition or the leels and a dierent, oerall, aim or the game as a
whole. lor our game, the aim o each leel is to collect the prescribed number o
raspberries. 1he aim o the game as a whole is to clear 5 leels.
Now we hae our rules and our ictory condition, it`s time to design the game,
according to the principles o input, logic and output:
Input
1he user needs to control the gun. 1his means we`ll hae to set up a way or the
player to moe it let and right, as well as ring. Keyboard control works best or
a game o this sort, so we need to write code to speciy which keys the player can
use to control their gun turret and more code to listen` or those key presses.
\e`ll also want the user to be able to sae their progress so they can exit
the game and resume later. So, when the game loads, it needs to check whether
there`s any progress data and, i so, read it as an input.
U|t|mate Gu|de to Raspberry P|
81

\e`ll need to create or nd, graphical images or each o the ruits that`s going
to appear in our game, and we`ll need to write code to moe them down the
screen. 1o add a bit o isual interest, we`ll also want to create an explosion eect
or when the ruits are hit.
In addition, we`ll need a turret graphic and bullets or the player - and this is
also the right time to consider screen decorations or the background, oer which
we might display text or game instructions, score reports and so orth. In all
we`ll need the ollowing graphics:
lruit raspberry, cherry, strawberry, pear and banana,
Player graphics turret and bullets,
Background graphic
Splash screen
Sound is also a orm o output, so we should also at this point consider whether
we might want to include some in-game music and sound eects. Lastly, as
mentioned opposite, we will also be saing the player`s progress data to the hard
disk - another orm o output.
By looking at the game's output, we can generate a list of the graphics needed
U|t|mate Gu|de to Raspberry P|
82
Logic
Lastly, our logic code will check whether bullets hae collided with ruits, and
update the score accordingly. It will also keep track o which leel is being played,
and when the game is oer.
Creat|ng the bas|c game
Now we`e done our large-scale planning, you can nally open up your editor
and start typing. \e haen`t yet worked out the ne details o how we`re going
to implement eerything, but that`s all right. Creating a game is a completely
dierent process to building a real-world object such as a house. In that case
you need a detailed blueprint beore you dig the rst hole. Programming is more
like building a house out o Lego: you select rom a toolset o pre-created blocks
and build one part at a time, experimenting and amending along the way. It`s
an iteratire and orgavic process, in which you ocus on the building blocks o the
program - writing, testing and editing code to create each unction, module and
class - beore bringing them together to make the nal product.
Getting started
\e`ll begin by creating a simple template or our game, then ll in the code to get
the game working. 1o create the template, we need to think about how our code
will be organised in terms o graphics, sounds and Python les - and we do this
using the amiliar structure o input, logic and output rom the preious chapter.
Broadly speaking, you should expect to create a class or each o the game`s
isible objects. \ou could add the code or each o these classes in the main
Python le, but it makes more sense to hae each in its own le: this is clearer
and easier to understand, and remoes clutter rom the main program code.
Where to nd graph|cs and sounds
You can download a huge quantity of graphical and audio resources from
online libraries - but check the terms of use, especially if you intend to
edit them. You can fnd free graphics at the Open Clip Art Library (hffp://
openc11paf.ogj, which you can normally edit and use as you wish.
Fotolia (hffp://en.fofo11a.comj provides top-quality graphics and
photos for a small cost: for the best results, download the format of
the image and edit it in a suitable program.
A good source of free sounds is hffp://feesound.og. You'll fnd
everything here from music loops to special effects.
Focus On
U|t|mate Gu|de to Raspberry P|
83
J. Main.py
Create a older to contain your Python game. Now, in Geany, create and sae a
le called ma1n.py. 1ype in the code in listing 1 oerlea, and sae it.
2. Classes
Create Python les named bu11ef.py, fu1f.py, fuef.py and game.py. 1he
rst three are straight out o our design document and represent isible objects.
1he game class is there to hold inormation about the game as a whole. lor
example, it can keep track o the player`s score and leel number, and can be
coneniently reused across multiple projects
Add the ollowing text to the top o each o the class les:
c1ass 8u11ef{}:
def 1n1f{se1f}:
pass
.replacing 8u11ef with the name o each class. 1he pass command is
simply a placeholder - it doesn`t do anything, but i we didn`t proide it Python
would report an error since it isn`t alid to dene a completely empty unction.
3. Images
linally, in your project older, create a subolder called images` and copy all the
game`s graphic les into it, so they`re in a conenient place or us to access later.
Us|ng externa| resources
You can fnd the code, images and other resources for this game at WWW.
p11ab.nef/code. You'll fnd specifc information about Pygame functions
at WWW.pygame.og/docs and documentation for Python 2.7 is at hffp://
docs.pyfhon.og/2/1ndex.hfm1.
Important: we're not going to go into detail about every single
command used in this code. You've met much of it earlier in this book, and
where a command or function is new we'll explain what it does; but we
expect you to use the documentation for Python and Pygame to learn the
detail. Not only does this help us make progress, it encourages a key skill
every modern day programmer needs: the ability to use documentation.
You'll also notice our code doesn't include many programming
comments (explanatory text following the # symbolj. This is to keep our
listings clean and short. The downloadable code (which you should look
through after completing the chapterj is heavily documented.
Focus On
U|t|mate Gu|de to Raspberry P|
84
Ma|n.py - the "bo||erp|ate" of our program
1mpof mafh,andom,pygame,sys
fom fu1f 1mpof " fom game 1mpof " >
fom fuef 1mpof " fom bu11ef 1mpof "
##1OP LLvLL CON51AN15
IP5 = 30
WlNDOWWlD1h=40 WlNDOWhLlGh1=640
GAML1l1LL="P1 5p1af"
Whl1L=|255,255,255] kLD=|255,0,0] GkLLN=|0,255,0]
8LuL=|0,0,255] 8LACk=|0,0,0]
def ma1n{}:
#sef up 1n1f1a1 d1sp1ay
pygame.1n1f{}
c1ock=pygame.f1me.C1ock{}
suface=pygame.d1sp1ay.sefmode >
{|WlNDOWWlD1h,WlNDOWhLlGh1]}
pygame.d1sp1ay.sefcapf1on{GAML1l1LL}
P|cture and sound formats
The images used in this game are saved in PNG (Portable Network
Graphicsj format. This is because PNGs can have transparent
backgrounds; if you used the popular JPEG format, for example, you'd
see a white edge around each of the fruits. When developing games for
the Raspberry Pi, you need to choose the most effcient format for each
graphic, and for those with transparent backgrounds the 8-bit PNG format
with alpha transparency works well.
As you'll remember, an 8-bit image can include only a maximum of
256 colours (a 32-bit PNG can contain millions of coloursj, so this also
gives the Pi less work to do when it's painting each screen. For most
purposes, this is the format to use.
When it comes to sound, WAv is a good format for short noises.
Although the fle size is larger than MP3, fles in this format aren't
compressed, so your computer doesn't have to do any unnecessary work
to play them. For longer sounds that are loaded once at the start of the
game - background music, for example - MP3 is a better choice so as not
to waste valuable disk space and memory.
Focus On
1
2
3
4
5
6
7

9
10
11
12
13
14
15
16
17
U|t|mate Gu|de to Raspberry P|
85
#MAlN GAML LOOP
gameove=Ia1se
Wh11e gameove==Ia1se:
fo evenf 1n pygame.evenf.gef{}:
1f evenf.fype==pygame.kLYDOWN:
1f evenf.key==pygame.kL5CAPL:
gameove=1ue
p1nf pygame.f1me.geff1cks{}
pygame.d1sp1ay.updafe{}
c1ock.f1ck{IP5}
1f name == `ma1n`:
ma1n{}
1he initial 31 lines o our program comprise the boilerplate`, or standard
structure, which hardly aries rom game to game. Line 2 imports our classes.
\e then set a series o cov.tavt.: ariables whose alues will not change during
the game. Unlike many other languages, Python doesn`t hae a separate type or
constants, so we name them using capital letters so we can identiy them later.
On line 11 we set up a unction called ma1n, which is where our program will
begin. Lines 13-16 use pygame unctions to draw the initial window or the game.
Lines 21 to 28 constitute the vaiv oo: this is the code used to draw the screen
many times per second as the game is being played.
\e set up a ariable called gameove in line 19 and gie it the alue Ia1se.
\e then start a Wh11e loop that will keep repeating until gameove becomes
1ue. 1he fo loop at line 22 asks Pygame i any erevt. hae taken place. In this
case, we`re interested in keyboard eents so, in line 23, we cycle through all the
eents in the queue and, i a key has been pressed, we then ask i that key was
Lsc`. I it was, we set gameove to 1ue, causing the game to exit.
Line 2 updates the display we haen`t yet added anything isual, but will do
soon, and line 28 tells Pygame to make sure the loop doesn`t cycle more quickly
than 30 times per second. linally, lines 30 and 31 are used to make sure that the
ma1n unction will be accessed only i this was the le open in Geany when we
clicked the cog button. In other words, i we accidentally imported this module
into another, vaiv would not be called.
Once you`e entered and checked all this code, click the cog icon or press
l5,. \ou should see a series o numbers running down the terminal window:
these are generated by line 25 and are simply the number o milliseconds since
the program started, proing that you`e typed eerything correctly and are ready
to moe on. I you see any error messages in the terminal window, you need to
correct them beore continuing.
1
19
20
21
22
23
24
25
26
27
2
29
30
31
U|t|mate Gu|de to Raspberry P|
86
Let there be fru|t
Now it`s time to make the ruit appear and drop down the screen. \e`ll start by
setting up the ruit object. Open up fu1f.py in Geany and type in this code:
1mpof pygame, andom
c1ass Iu1f{pygame.sp1fe.5p1fe}:
def 1n1f{se1f,WlNDOWWlD1h}:
pygame.sp1fe.5p1fe.1n1f{se1f}
se1f.spec1es=andom.cho1ce{|"aspbey", >
"sfaWbey", "chey","pea","banana"]}
se1f.1mage=pygame.1mage.1oad{"1mages/"+ >
se1f.spec1es+".png"}
se1f.ecf=se1f.1mage.gefecf{}
se1f.ecf.y=0-se1f.ecf.he1ghf
se1f.ecf.x={andom.and1nf{se1f.ecf. >
W1dfh/2,{WlNDOWWlD1h-se1f.ecf.W1dfh}}}
def updafepos1f1on{se1f,speed,WlNDOWhLlGh1,game}:
1f se1f.ecf.y<{WlNDOWhLlGh1}:
se1f.ecf.y+=speed"5
e1se:
1f se1f.spec1es=="aspbey":
game.updafescoe{50}
game.updafeaspbe1essaved{}
e1se:
game.updafescoe{-10}
se1f.k111{}
def shof{se1f,game}:
1f se1f.spec1es=="aspbey":
game.updafescoe{-50}
e1se:
game.updafescoe{10}
se1f.k111{}
\e begin by importing the pygame library and the andom module. 1ake
a look at line 2 - you can see that we`e added pygame.sp1fe.5p1fe to the
class denition. 1his is an example o class inheritance in action: this line tells
Python to create a new object based on Pygame`s 5p1fe class, so Python will
assume that this object a sprite in all its behaiours and properties - except
1
2
3
4
5
6
7

9
10
11
12
13
14
15
16
17
1
19
20
21
22
23
24
25
26
27
2
U|t|mate Gu|de to Raspberry P|
87
where we explicitly speciy otherwise. A sprite is a specialised object that`s based
on an image and which can be easily moed around the screen. It contains all the
unctions needed to handle the isual side o our ruit.
1he 1n1f unction is run when the main program creates a new iv.tavce
o the lruit class. In other words, when we want a new ruit to appear and all
down the screen. In line 6 we create a roert, o the sprite that we`e named
spec1es. In reality it`s just a ariable like any other, but the conention is to call
ariables that are inside objects properties`.
1he se1f keyword in ront o a ariable name tells the object that this
ariable is part o its unique identity and should be remembered. So eery lruit
instance will remember which species it was set to or as long as it`s alie, this is a
ery useul eature o objects, as we`ll see.
In line , we use Pygame`s 1mage unctions to load a picture into the sprite.
1he next line makes sure that the size o the sprite matches the size o the image
just loaded. Line 9 sets the , ertical, position to zero minus the height o the
image. So i the picture was 50 pixels tall, the top-let corner o the ruit will be
drawn at -50, so it`s just o the top o the screen.
Line 10 looks a little bit more complicated, but it simply species a random
horizontal , position or the ruit. 1he andom.and1nf unction takes two
parameters, to set the range between which you want it to generate a number.
Our rst parameter - the lower bound - is :
se1f.ecf.W1dfh/2
In other words, we want the lowest possible horizontal alue to be hal
the width o the image rom the let. 1his ensures the ruit will neer be drawn
either wholly or partially o the let edge o the screen. 1he second parameter,
speciying the upper bound, is:
WlNDOWWlD1h-se1f.ecf.W1dfh
In this case, the maximum right-hand position will be the width o the
window minus the width o the image. So with a WlNDOWWlD1h o 480 pixels
and a ruit width o, say, 2 pixels, we`d be asking andom.and1nf to proide
a random number between 36 2,2, and 408 480-2,. 1hat number would be
used to position the ruit: each one in a dierent horizontal location.
1he 1n1f unction, then, sets things up, but we need to add more
unctions to make things happen. 1hese unctions will ary depending on the
purpose o the class, and in this case the most obious attribute o our ruit is
that it moes down the screen, so we`ll begin with a unction called updafe
pos1f1on. Unlike 1n1f, this unction will only run when it`s called in this
case, by the main program,.
U|t|mate Gu|de to Raspberry P|
88
1he unction denition in line 12 includes our parameters that must be
passed to it. se1f is part o all class denitions, but the others are our own
ariables. WlNDOWhLlGh1 is sel-explanatory, game is the game object we haen`t
created it yet, and speed is a parameter we`ll set in ma1n.py shortly.
1he unction is pretty simple. On line 13 we check to see i the ertical
position o the ruit is still less than the height o the window i it isn`t, then the
ruit must hae dropped o the bottom,. I it is, then in line 14 we increase its
position by an amount related to the speed.
I the ruit dropped out o the window then Python will execute the
code ater the e1se in line 15. In this case, the code is another 1f statement: it`s
ery important to understand that the code between lines 16 and 21 will be
executed i line 13 is fa1se.
So, on line 16 we check to see i the current ruit is a raspberry. Remember
that the point o the game is to allow raspberries to reach the bottom o the
screen, so, in that case, we are going to increase the score and increment the
number o raspberries saed so ar the game ends when this number gets to ten,.
Note that we haen`t actually added any code to the game object yet, but we now
know which unctions to create.
Line 19 translates as i the ruit is not on-screen because it`s reached the
bottom, and it`s not a raspberry then execute the next line`. In this case, line
20 decreases the score because the player has allowed one o the other ruits to
reach the bottom.
linally, line 21 deletes the object. Look closely at the indentation to make
sure you understand the circumstances under which this line will be executed:
the se1f.k111 unction is inside the 1f structure starting on line 16, so i the
object has allen o the bottom o the screen it will be killed` whicheer ruit
Why use var|ab|es for constants?
You'll have noticed that once we've set the value of WlNDOWWlD1h in
ma1n.py, it stays the same throughout our game - that's why we call it a
constant and why, conventionally, we write it all in capital letters. So why
do we bother with it? Why don't we just specify the value 480 directly
when we need to refer to the width of the window?
We do it this way for two reasons. Firstly, because this allows you to
create a new game - with a different width - by doing nothing more than
changing a value once at the start of the program, rather than having to
fnd and alter every occurrence of 480. The second reason is that it makes
reading your code much simpler. By using WlNDOWWlD1h rather than 480 in
a calculation, you know exactly what that number represents.
Focus On
U|t|mate Gu|de to Raspberry P|
89
type it represents. Although the ruit is no longer isible, it makes sense to clear it
and stop it updating: otherwise it will continue to all, een though we can`t see it,
pointlessly wasting computing power and memory.
linally, since the object o the game is to shoot ruit except raspberries,, we
add a unction called shof. A quick look oer the code should be ample or you
to see what it does.
Sett|ng up the game
c1ass Game{}:
def 1n1f{se1f}:
se1f.scoe=0
se1f.aspbe1essaved=0
def updafescoe{se1f,amounf}:
se1f.scoe+=amounf
def gefscoe{se1f}:
efun se1f.scoe
def updafeaspbe1essaved{se1f}:
se1f.aspbe1essaved+=1
def gefaspbe1essaved{se1f}:
efun se1f.aspbe1essaved
laing written our Iu1f class, we now know what we need initially, at least, to
include in our Game class sae it as game.py,. Remember that this is a dierent
sort o class to Iu1f: it doesn`t relate to a isible object on-screen. It`s simply a
conenient wrapper or code and ariables that relate to the game as a whole.
1he class denition doesn`t contain anything between the brackets because
we`re not basing Game on a pre-existing class. 1he 1n1f unction initialises
two ariables - the score and the number o raspberries we`e saed - so we can
use them later. updafescoe takes the amount sent to it and adds that to the
running score see line 1 o fu1f.py to see this unction called,. gefscoe,
on the other hand, uses the efun keyword to send back the score. So, we could
write a line o code like this to print the current score to the terminal:
p1nf game.gefscoe
1he nal two unctions ull the same purpose or the aspbe1essaved
ariable, so our program can easily check this alue too.
1
2
3
4
5
6
7

9
10
11
12
13
14
15
16
U|t|mate Gu|de to Raspberry P|
90
Updat|ng Ma|n.py
It`s time to ill out the boilerplate` code we created earlier, to accommodate the
additional eatures needed to work with our ruit sprites. Update your ma1n.py
module as ollows:
1mpof mafh,andom,pygame,sys
fom fu1f 1mpof " fom game 1mpof " >
fom fuef 1mpof " fom bu11ef 1mpof "
##1OP LLvLL CON51AN15
IP5 = 30
WlNDOWWlD1h=40 WlNDOWhLlGh1=640
GAML1l1LL="P1 5p1af"
Whl1L=|255,255,255] kLD=|255,0,0] GkLLN=|0,255,0] >
8LuL=|0,0,255] 8LACk=|0,0,0]
5PLLD=0.5
def ma1n{}:
game=Game{}
#sef up 1n1f1a1 d1sp1ay
pygame.1n1f{}
c1ock=pygame.f1me.C1ock{}
suface=pygame.d1sp1ay.sefmode{|WlNDOWWlD1h,WlNDOWhLlGh1]}
pygame.d1sp1ay.sefcapf1on{GAML1l1LL}
#MAlN GAML LOOP
gameove=Ia1se
11vefu1fsp1fes=pygame.sp1fe.Goup{}
f1ckfock=1
Wh11e gameove==Ia1se:
fo evenf 1n pygame.evenf.gef{}:
1f evenf.fype==pygame.kLYDOWN:
1f evenf.key==pygame.kL5CAPL:
gameove=1ue
1f f1ckfock x {IP5/5PLLD}==1:
1f 1en{11vefu1fsp1fes}<10:
11vefu1fsp1fes.add{{Iu1f{WlNDOWWlD1h}}}
suface.f111{8LACk}
1
2
3
4
5
6
7

9
10
11
12
13
14
15
16
17
1
19
20
21
22
23
24
25
26
27
2
29
30
31
32
33
34
U|t|mate Gu|de to Raspberry P|
91
fo sp1fe 1n 11vefu1fsp1fes:
sp1fe.updafepos1f1on{5PLLD,WlNDOWhLlGh1,game}
11vefu1fsp1fes.daW{suface}
pygame.d1sp1ay.updafe{}
f1ckfock+=1
c1ock.f1ck{IP5}
1f name == `ma1n`:
ma1n{}
\ou`ll see we`e made quite a ew changes. \e`e added a new constant called
5PLLD at line 9, and at line 22 we create a sprite group. 1his is essentially a list o
all the ruit sprites so we can easily handle them later.
1he 1f statement beginning at line 31 checks i there are ewer than ten ruits
on the screen, and i so creates a new ruit object and adds it to the sprite group.
\ou`ll notice we created a ariable called f1ckfock on line 23, and we use it on
line 30. 1his is needed because
the main loop beginning at line
24, runs at 30 rames per second
see line 44,. \ithout the code
at line 30, all the ruits would
be added almost instantly rather
than spread out.
At line 42, f1ckfock
increments each loop, so it`ll be
worth 30 ater one second, 60
ater two seconds and so on.
Line 30 says that i you diide
f1ckfock by the number o
rames per second 30 in this
case,, diided by the speed
ariable 0.5 at the moment,, and
get a remainder o 1 that`s what
the or means,, run
line 31 and add a ruit i there
are ewer than ten. It`s a bit o a
brain-melter, but i you think
it through, you`ll see that
35
36
37
3
39
40
41
42
43
44
45
46
47
Run the code and you should now see fruit falling
randomly down the window
U|t|mate Gu|de to Raspberry P|
92
there will be a remainder o 1 when f1ckfock is worth 61, 121, 181 and so orth.
1he eect, then, is to run line 32 eery two seconds or so - which is exactly what
we want. Alternatiely, we could use Python`s time unctions, but doing it this
way keeps things in sync i the computer struggles to keep up or any reason.
Line 34 ills the window with black you`ll be able to see what happens i you
don`t do this in a moment,. Line 35 cycles through eery ruit i there are any,
and, in line 36, runs the lruit class`s updafepos1f1on unction we just created,
moing each one down the screen or deleting it. linally, we run Pygame`s daW
unction, which will paint eery ruit to the screen in one go.
Gie it a try. Make sure ma1n.py is in your Geany window and press l5 or
click the cog. \ou should see ruit appear at the top and moe smoothly down
the window. Close the terminal to stop the program and add a hash symbol 4,
to the start o line 34, this comments out` the line so that Python ignores it.
Press l5 and you should see a ery dierent result.
Shoot|ng fru|t
\e`re only a ew steps away rom haing a working game, so let`s press on and
add the missing sections o code. \e`ll start with the gun turret: enter the code
below and sae it as fuef.py:
1mpof pygame
c1ass 1uef{pygame.sp1fe.5p1fe}:
def 1n1f{se1f,WlNDOWWlD1h,WlNDOWhLlGh1}:
pygame.sp1fe.5p1fe.1n1f{se1f}
se1f.1mage=pygame.1mage.1oad{"1mages/fuef.png"}
se1f.ecf = se1f.1mage.gefecf{}
se1f.ecf.x = {WlNDOWWlD1h-se1f.ecf.W1dfh}/2
se1f.ecf.y =WlNDOWhLlGh1-se1f.ecf.he1ghf
def updafepos1f1on{se1f,d1ecf1on,WlNDOWWlD1h}:
1f d1ecf1on=="1eff" and se1f.ecf.x>10:
se1f.ecf.x-=10
e11f d1ecf1on=="1ghf" and >
se1f.ecf.x<{WlNDOWWlD1h-10}:
se1f.ecf.x+=10
def gefgunpos1f1on{se1f}:
pos1f1on={}
pos1f1on|"x"]=se1f.ecf.x+{se1f.ecf.W1dfh/2}
pos1f1on|"y"]=se1f.ecf.y-{se1f.ecf.he1ghf/2}
efun pos1f1on
1
2
3
4
5
6
7

9
10
11
12
13
14
15
16
17
1
19
20
U|t|mate Gu|de to Raspberry P|
93
1his class is similar to the Iu1f class, with lines and 8 positioning the
turret graphic at the centre o the screen`s bottom edge. At line 10 we set up
the updafepos1f1on method, which takes the direction and the width o the
window as parameters and either deducts rom the turret`s horizontal , position
to send the graphic let, or adds to it to send it right. See i you can work out how
the code preents the turret rom disappearing o the side o the screen.
linally, starting at line 16, we add a unction to send back the position o
the gun in the centre o the turret, so we can make bullets appear like they`re
emerging rom the gun. lere`s the code or the last class, bu11ef.py:
1mpof pygame
c1ass 8u11ef{pygame.sp1fe.5p1fe}:
def 1n1f{se1f,pos1f1on}:
pygame.sp1fe.5p1fe.1n1f{se1f}
se1f.1mage=pygame.1mage.1oad{"1mages/bu11ef.png"}
se1f.ecf = se1f.1mage.gefecf{}
se1f.ecf.x=pos1f1on|"x"]
se1f.ecf.y=pos1f1on|"y"]
def updafepos1f1on{se1f}:
1f se1f.ecf.y>=-se1f.ecf.he1ghf:
se1f.ecf.y-=5
e1se:
se1f.k111{}
In the 1n1f unction, we send the gun position rom 1uef. 1he
unction updafepos1f1on is ery simple, since bullets go the screen, their
alue gets smaller as they moe. Once they go o the top, we destroy the sprite.
Ma|n.py - the rst fu||y work|ng vers|on
Now we`e set up the code to handle our turret and bullets, we simply need
to make a ew last changes to ma1n.py to tie it all together and nish the rst
ersion o the game. \e`e marked the changes in red, below:
1mpof mafh,andom,pygame,sys
fom fu1f 1mpof " fom game 1mpof " >
fom fuef 1mpof " fom bu11ef 1mpof "
##1OP LLvLL CON51AN15
IP5 = 30
1
2
3
4
5
6
7

9
10
11
12
13
14
15
1
2
3
4
5
6
U|t|mate Gu|de to Raspberry P|
94
WlNDOWWlD1h=40 WlNDOWhLlGh1=640
GAML1l1LL="P1 5p1af"
Whl1L=|255,255,255] kLD=|255,0,0] GkLLN=|0,255,0] >
8LuL=|0,0,255] 8LACk=|0,0,0]
5PLLD=0.5
def ma1n{}:
game=Game{}
#sef up 1n1f1a1 d1sp1ay
pygame.1n1f{}
pygame.key.sefepeaf{1, 75}
scoeIonf=pygame.fonf.Ionf{"2568Y1L5.11I",32}
c1ock=pygame.f1me.C1ock{}
suface=pygame.d1sp1ay.sefmode{|WlNDOWWlD1h,WlNDOWhLlGh1]}
pygame.d1sp1ay.sefcapf1on{GAML1l1LL}
#MAlN GAML LOOP
gameove=Ia1se
11vefu1fsp1fes=pygame.sp1fe.Goup{}
bu11efsp1fes=pygame.sp1fe.Goup{}
ofhesp1fes=pygame.sp1fe.Goup{}
fuef=1uef{WlNDOWWlD1h,WlNDOWhLlGh1}
ofhesp1fes.add{fuef}
f1ckfock=1
Wh11e gameove==Ia1se:
fo evenf 1n pygame.evenf.gef{}:
1f evenf.fype==pygame.kLYDOWN:
1f evenf.key==pygame.kL5CAPL:
gameove=1ue
e11f evenf.key==pygame.kLLI1:
fuef.updafepos1f1on{"1eff",WlNDOWWlD1h}
e11f evenf.key==pygame.kklGh1:
fuef.updafepos1f1on{"1ghf",WlNDOWWlD1h}
e11f evenf.key==pygame.k5PACL:
bu11ef=8u11ef{fuef.gefgunpos1f1on{}}
bu11efsp1fes.add{bu11ef}
1f f1ckfock x {IP5/5PLLD}==1:
1f 1en{11vefu1fsp1fes}<10:
11vefu1fsp1fes.add{{Iu1f{WlNDOWWlD1h}}}
7

9
10
11
12
13
14
15
16
17
1
19
20
21
22
23
24
25
26
27
2
29
30
31
32
33
34
35
36
37
3
39
40
41
42
43
44
45
46
47
U|t|mate Gu|de to Raspberry P|
95
fo sp1fe 1n bu11efsp1fes:
sp1fe.updafepos1f1on{}
co111s1ons=pygame.sp1fe.goupco111de{11vefu1f >
sp1fes,bu11efsp1fes,Ia1se,1ue}
1f co111s1ons:
fo fu1f 1n co111s1ons:
fu1f.shof{game}
suface.f111{8LACk}
bu11efsp1fes.daW{suface}
ofhesp1fes.daW{suface}
fo sp1fe 1n 11vefu1fsp1fes:
sp1fe.updafepos1f1on{5PLLD,WlNDOWhLlGh1,game}
11vefu1fsp1fes.daW{suface}
scoe1exf=scoeIonf.ende{`5coe: `+sf{game.gef >
scoe{}},1ue,GkLLN}
suface.b11f{scoe1exf,{10,10}}
pygame.d1sp1ay.updafe{}
f1ckfock+=1
1f game.gefaspbe1essaved{}>=10:
gameove=1ue
c1ock.f1ck{IP5}
#hand1e end of game
suface.f111{8LACk}
scoe1exf=scoeIonf.ende{`Game ove. 5coe: `>
+sf{game.gefscoe{}},1ue,GkLLN}
suface.b11f{scoe1exf,{10,200}}
pygame.d1sp1ay.updafe{}
aW1npuf{"pess any key"}
1f name == `ma1n`:
ma1n{}
4
49
50
51
52
53
54
55
56
57
5
59
60
61
62
63
64
65
66
67
6
69
70
71
72
73
74
75
76
77
7
79
0
1
2
3
4
5
6
U|t|mate Gu|de to Raspberry P|
96
Line 1 calls a Pygame unction that limits the repeat interal on a keypress to 5
milliseconds, so the player can hold down the spacebar and rapidly re a stream
o bullets. Line 18 imports a custom ont WWW.1001feefonfs.com is a good
place to nd them, that we`ll use to display the score. In lines 26 to 29, we create
two new sprite groups: one to hold the bullets, and a second catch-all group or
any other sprites we`re adding.
Lines 3 to 40 respond to the let and right arrow keys, updating the turret`s
position using the code we just added to fuef.py. Lines 41 to 43 create a new
bullet when the spacebar is pressed and add the bullet to the group. Lines 49 and
50 cycle through all the bullets currently isible and trigger the updafepos1f1on
unction or each in turn.
Line 52 is a little bit o Pygame magic. 1his one line checks whether
bullet has collided with ruit. I one has, Pygame generates a o those ruits
that hae collided. All we hae to do is pass in the two sprite groups we want to
check hence our maintaining separate groups or bullets and ruit,, along with
parameters indicating whether Pygame should kill colliding sprites. lor the ruit,
we send a Ia1se parameter because we want to update the score beore killing
them manually. lor the bullets, it`s ne or
Pygame to kill them.
In lines 54 to 56, we iterate through
any collisions and run the shof unction
o the ruit the bullet has hit. Lines 59 and
60 draw the new groups to the screen.
On line 6 we use Pygame`s fonf.
ende to create a picture that displays
the score in green with a transparent
background. Line 68 paints the score onto
the screen using the b11f unction. \ou
must use this unction to draw objects
onto the screen i you`re not using sprites,
otherwise they won`t appear.
Lines 2 and 3 set up a simple
1f statement that breaks out o the
main game loop once we`e saed 10
raspberries. linally, the code rom lines
8 to 83 clears the screen, draws the nal
score and waits or the user to press a key.
Once your code matches our listings,
sae and press l5 to play the game. \hilst
it`s certainly basic, you now hae a ully
working, playable, arcade game in ewer
than 200 lines o code. Not bad!
Our code allows the player to hold down
the spacebar to loose off a hail of bullets
U|t|mate Gu|de to Raspberry P|
97
Comp|et|ng the game
1o add a bit o depth to Pi Splat, we might add leels that become progressiely
harder. \hile we`re at it, we should also implement the additional input and
output unctions we planned at the start: adding a splash,instructions screen
at the start o the game, and giing the player the ability to sae and restore the
player`s progress. \e`ll also smooth out a ew rough edges to gie the game a
more proessional polish.
The n|shed code
Most o the remaining work takes place in ma1n.py. 1his makes sense, as adding
leels doesn`t aect the way indiidual objects such as ruits or bullets behae.
On line 1, we add two new modules: p1ck1e and os. Both are needed so that
we can sae the user`s progress. \e remoe the 5COkL constant and replace it
with NuM8LkOILLvLL5, which we`re setting to e. \ou can change the number
o leels in your ersion o the game by altering this number.
Starting at line 23, we`e added some code to create a splash screen. 1his has
been created as a single graphic. It might hae been more nexible to add the text
at runtime, but a static image is ne or a simple game such as this.
1mpof mafh,andom,pygame,sys,p1ck1e,os
fom fu1f 1mpof " fom game 1mpof " >
fom fuef 1mpof " fom bu11ef 1mpof "
##1OP LLvLL CON51AN15
IP5 = 30
WlNDOWWlD1h=40 WlNDOWhLlGh1=640
GAML1l1LL="P1 5p1af"
Whl1L=|255,255,255] kLD=|255,0,0] GkLLN=|0,255,0] >
8LuL=|0,0,255] 8LACk=|0,0,0]
NuM8LkOILLvLL5=5
def ma1n{}:
game=Game{}
Rather than typing in all the code that follows, we recommend you
download the complete version of the game from WWW.p11ab.nef/code,
load it into Geany and follow the discussion.
1
2
3
4
5
6
7

9
10
11
12
U|t|mate Gu|de to Raspberry P|
98
#lNl1lAL 5L1uP
pygame.1n1f{}
pygame.key.sefepeaf{1, 75}
pygame.mouse.sefv1s1b1e{Ia1se}
d1sp1ayIonf=pygame.fonf.Ionf{"2568Y1L5.11I",2}
c1ock=pygame.f1me.C1ock{}
suface=pygame.d1sp1ay.sefmode{|WlNDOWWlD1h, >
WlNDOWhLlGh1]}
pygame.d1sp1ay.sefcapf1on{GAML1l1LL}
#5PLA5h 5CkLLN
sp1ash=pygame.1mage.1oad{"1mages/sp1ash.png"}
suface.b11f{sp1ash,{0,0}}
pygame.d1sp1ay.updafe{}
gameove=Ia1se
sfafgame=Ia1se
Wh11e sfafgame==Ia1se:
fo evenf 1n pygame.evenf.gef{}:
1f evenf.fype==pygame.kLYDOWN:
1f evenf.key==pygame.kL5CAPL:
gameove=1ue
e11f evenf.key==pygame.kkL1ukN o >
evenf.key==pygame.kkPLN1Lk:
esume=Ia1se
sfafgame=1ue
e11f evenf.key==pygame.kL5hlI1 o >
evenf.key==pygame.kk5hlI1:
esume=1ue
sfafgame=1ue
1f esume==1ue: #1f fhey Wanf fo p1ck up a saved game
1f os.pafh.ex1sfs{"savedafa.daf"}==1ue:
game.1oadgame{}
At line 24, we load the splash screen and b11f it to the surace on line 25,
beore rereshing the screen so it becomes isible. \e`e moed the gameove
ariable to this point so the user can exit een when a game isn`t underway.
Lines 30 to 40 wait or the user to press a key, and respond when he or she
does. 1he instructions tell them to press Lnter to start a new game or Shit to
resume an existing one. Since there are two physical Lnter keys the one under
13
14
15
16
17
1
19
20
21
22
23
24
25
26
27
2
29
30
31
32
33
34
35
36
37
3
39
40
41
42
43
44
U|t|mate Gu|de to Raspberry P|
99
Backspace and the one alongside the numeric keypad,, we hae to handle this
in line 35. Similarly, there are two Shit keys: line 38 captures this and sets the
esume ariable to 1ue.
On line 42, we check to see i they chose to continue an existing game, but
we rst need to check i a sae le already exists there won`t be one i it`s the
rst time they`e played the game,. 1his is achieed through the os operating
system`, module unction. On line 44, we run a yet-to-be-created unction o the
game object. 1he code continues:
#MAlN GAML LOOP
Wh11e game.gef1eve1{}<=NuM8LkOILLvLL5 and >
gameove==Ia1se:
#5hOW LLvLL NuM8Lk
suface.f111{8LACk}
1eve11exf=d1sp1ayIonf.ende{`Leve1: `>
+sf{game.gef1eve1{}},1ue,GkLLN}
suface.b11f{1eve11exf,{150,300}}
pygame.d1sp1ay.updafe{}
pygame.f1me.Wa1f{1500}
#5L1 uP vAklA8LL5 IOk LLvLL
game.savegame{}
11vefu1fsp1fes=pygame.sp1fe.Goup{}
game.aspbe1essaved=0
bu11efsp1fes=pygame.sp1fe.Goup{}
ofhesp1fes=pygame.sp1fe.Goup{}
fuef=1uef{WlNDOWWlD1h,WlNDOWhLlGh1}
ofhesp1fes.add{fuef}
f1ckfock=1
1eve1ove=Ia1se
\e`e added a new loop that runs Wh11e the current leel is less than or
equal to the total number o leels and the user hasn`t pressed Lscape. Beore
each leel begins, we want to display a text message, so on lines 50 to 54 we erase
the splash screen by lling it with black, and set up a ont. \e`e changed the
name o this ariable rom scoeIonf because it now has a more general use.
\e then use Pygame`s f1me.Wa1f{} unction to pause or 1.5 seconds, ater
which we start the code or each leel remember, the code ater line 4 runs
each time a new leel is started,. On line 5 we run another unction o game
- one we haen`t yet written - to sae progress. \hy sae it now Because we
45
46
47
4
49
50
51
52
53
54
55
56
57
5
59
60
61
62
63
64
65
U|t|mate Gu|de to Raspberry P|
100
want the user to come back at the start o the leel they were playing when they
exited, so we sae the state beore it begins. 1he only other changes to this block
o code are that we zero the ariable game.aspbe1essaved beore the leel
starts and we create a new ariable 1eve1ove.
#PLAY lNDlvlDuAL LLvLL
Wh11e 1eve1ove==Ia1se and gameove==Ia1se:
fo evenf 1n pygame.evenf.gef{}:
1f evenf.fype==pygame.kLYDOWN:
1f evenf.key==pygame.kL5CAPL:
gameove=1ue
e11f evenf.key==pygame.kLLI1:
fuef.updafepos1f1on{"1eff", >
WlNDOWWlD1h,game.gef1eve1{}}
e11f evenf.key==pygame.kklGh1:
fuef.updafepos1f1on{"1ghf", >
WlNDOWWlD1h,game.gef1eve1{}}
e11f evenf.key==pygame.k5PACL:
bu11ef=8u11ef{fuef.gefgunpos1f1on{}}
bu11efsp1fes.add{bu11ef}
1f f1ckfock >=120:
f1ckfock=0
1f 1en{11vefu1fsp1fes}<10:
11vefu1fsp1fes.add{{Iu1f{WlNDOWWlD1h}}}
fo sp1fe 1n bu11efsp1fes:
sp1fe.updafepos1f1on{}
co111s1ons=pygame.sp1fe.goupco111de >
{11vefu1fsp1fes,bu11efsp1fes,Ia1se,1ue}
1f co111s1ons: #1f fhee ae any
fo fu1f 1n co111s1ons:
fu1f.shof{game}
backgound=pygame.1mage.1oad >
{"1mages/game8oad.png"}
suface.b11f{backgound,{0,0}}
bu11efsp1fes.daW{suface}
ofhesp1fes.daW{suface}
66
67
6
69
70
71
72
73
74
75
76
77
7
79
0
1
2
3
4
5
6
7

9
90
91
92
93
94
95
97
97
9
99
U|t|mate Gu|de to Raspberry P|
101
fo sp1fe 1n 11vefu1fsp1fes:
sp1fe.updafepos1f1on >
{game.gef1eve1{},WlNDOWhLlGh1,game}
11vefu1fsp1fes.daW{suface}
scoe1exf=d1sp1ayIonf.ende >
{`5coe: `+sf{game.gefscoe{}},1ue,GkLLN}
1eve11exf=d1sp1ayIonf.ende >
{`Leve1: `+sf{game.gef1eve1{}},1ue, Whl1L}
aspbe1es1exf=d1sp1ayIonf.ende >
{`kaspbe1es: `+sf{game.gefaspbe1essaved{}},1ue,kLD}
suface.b11f{scoe1exf,{10,10}}
suface.b11f{1eve11exf,{10,50}}
suface.b11f{aspbe1es1exf,{10,90}}
pygame.d1sp1ay.updafe{}
f1ckfock+=game.gef1eve1{}
1f game.gefaspbe1essaved{}>=10:
game.updafe1eve1{1}
1eve1ove=1ue
c1ock.f1ck{IP5}
\ou`ll notice that all o this code has been indented by an additional tab do
this in Geany by highlighting the lines you want to indent and pressing 1ab once,.
I you think this through you`ll see that we`e done this because, at the end o
each leel, we want to loop back to line 4 to see i we`e reached the nal leel.
\ou`ll also see that on line 68 we`re testing two conditions: the leel will
play i 1eve1ove isn`t 1ue and i the user hasn`t pressed Lscape. 1he eent-
handling code is unchanged, but we`e simplied the code or adding new ruits
to the screen: we`re now doing this eery time f1ckfock reaches 120, which, or
leel 1, will be 4 seconds 30 rames per second into 120,.
On lines 95 and 96 we load a more interesting background, as an 8-bit PNG.
1he code then remains unchanged until line 101 when we add a new parameter
to the updafepos1f1on unction o the Iu1f class. \e`ll come to this when we
look at the changes to that class.
Lines 104 to 110 hae been enhanced to add extra player inormation. And
on line 114 we call a new unction o the game object to increment the leel i
ten raspberries hae reached the bottom o the screen. \e set 1eve1ove to
1ue so that the leel exits and Python loops back to line 4.
1he only change to the last ew lines which we haen`t reproduced here, is
to add a summary to the nal screen showing the player`s oerall score.
100
101
102
103
104
105
106
107
10
109
110
111
112
113
114
115
116
U|t|mate Gu|de to Raspberry P|
102
Game.py
1mpof p1ck1e
c1ass Game{}:
def 1n1f{se1f}:
se1f.scoe=0
se1f.aspbe1essaved=0
se1f.1eve1=1
def updafescoe{se1f,amounf}:
se1f.scoe+=amounf"se1f.1eve1
def gefscoe{se1f}:
efun se1f.scoe
def updafeaspbe1essaved{se1f}:
se1f.aspbe1essaved+=1
def gefaspbe1essaved{se1f}:
efun se1f.aspbe1essaved
def updafe1eve1{se1f,amounf}:
se1f.1eve1+=amounf
def gef1eve1{se1f}:
efun se1f.1eve1
def savegame{se1f}:
savedafa={`scoe`:se1f.scoe,`1eve1`:se1f.1eve1}
savef11e=open{"savedafa.daf","Wb"}
p1ck1e.dump{savedafa,savef11e}
def 1oadgame{se1f}:
pogessf11e=open{"savedafa.daf","b"}
pogessdafa=p1ck1e.1oad{pogessf11e}
se1f.scoe=pogessdafa|`scoe`]
se1f.1eve1=pogessdafa|`1eve1`]
1he main change to game.py is to add the code or saing and loading the
player`s progress. So, on line 1 we import the p1ck1e module. \e`e also
added unctions to update the score - on line 9 we multiply the amount the
score changes by the leel number, so the urther through the game you get the
1
2
3
4
5
6
7

9
10
11
12
13
14
15
16
17
1
19
20
21
22
23
24
25
26
27
2
29
30
31
32
33
34
35
U|t|mate Gu|de to Raspberry P|
103
bigger the rewards or hitting the right ruit and the deductions or shooting a
raspberry!,. \e also add unctions to update and get the leel numbers.
1he interesting stu starts at line 26. 1he code here is ery similar to the
examples in the section on Python libraries. On line 2 we create a aictiovar,
containing the data we want to sae just score and leel numbers or this game,
but we could include the player`s name or example,. \e open a le to sae the
data i it doesn`t exist, Python creates the le, and then dump it to sae.
1he 1oadgame unction is almost exactly the reerse. I the user had reached
leel 3 with a score o 1,234 when they pressed Lscape, on restarting the game,
p1ck1e would load that data and game.1eve1 would now be 3. game.scoe
would be 1,234, exactly as i they had neer exited.
Fru|t.py
1mpof pygame, andom
c1ass Iu1f{pygame.sp1fe.5p1fe}:
def 1n1f{se1f,WlNDOWWlD1h}:
pygame.sp1fe.5p1fe.1n1f{se1f}
se1f.spec1es=andom.cho1ce{|"aspbey", >
"sfaWbey","chey","pea","banana"]}
se1f.1mage=pygame.1mage.1oad{"1mages/"+ >
se1f.spec1es+".png"}
se1f.1mage=pygame.fansfom.ofafe{se1f.1mage, >
andom.and1nf{-35,35}}
se1f.ecf=se1f.1mage.gefecf{}
se1f.ecf.y=0-se1f.ecf.he1ghf
se1f.ecf.x={andom.and1nf{se1f.ecf.W1dfh/2, >
{WlNDOWWlD1h-se1f.ecf.W1dfh}}}
def updafepos1f1on{se1f,1eve1,WlNDOWhLlGh1,game}:
1f se1f.ecf.y<{WlNDOWhLlGh1}:
se1f.ecf.y+=2+1eve1
e1se:
1f se1f.spec1es=="aspbey":
game.updafescoe{50}
game.updafeaspbe1essaved{}
e1se:
game.updafescoe{-10}
se1f.k111{}
1
2
3
4
5
6
7

9
10
11
12
13
14
15
16
17
1
19
20
21
22
23
24
U|t|mate Gu|de to Raspberry P|
104
def shof{se1f,game}:
1f se1f.spec1es=="aspbey":
game.updafescoe{-50}
e1se:
game.updafescoe{10}
se1f.k111{}
\e`e made only a couple o minor changes to fu1f.py. Line 8 rotates new
ruit images by a random alue between -35 and 35 degrees, making their
appearance a little more interesting. \ou could add code into updafepos1f1on
to hae them gently swing as they ell i you wanted the ull eect!
Otherwise, the only change is on line 13, where we replace the speed
parameter with 1eve1 and then, on line 15, use that to increase the speed as the
player progresses through the game.
Turret.py
1mpof pygame
c1ass 1uef{pygame.sp1fe.5p1fe}:
def 1n1f{se1f,WlNDOWWlD1h,WlNDOWhLlGh1}:
pygame.sp1fe.5p1fe.1n1f{se1f}
se1f.1mage=pygame.1mage.1oad{"1mages/fuef.png"}
se1f.ecf = se1f.1mage.gefecf{}
se1f.ecf.x = {WlNDOWWlD1h-se1f.ecf.W1dfh}/2
se1f.ecf.y =WlNDOWhLlGh1-se1f.ecf.he1ghf
def updafepos1f1on{se1f,d1ecf1on,WlNDOWWlD1h,1eve1}:
1f d1ecf1on=="1eff" and se1f.ecf.x>10:
se1f.ecf.x-=10+1eve1
e11f d1ecf1on=="1ghf" and >
se1f.ecf.x<{WlNDOWWlD1h-10}:
se1f.ecf.x+=10+1eve1
def gefgunpos1f1on{se1f}:
pos1f1on={}
pos1f1on|"x"]=se1f.ecf.x+{se1f.ecf.W1dfh/2}
pos1f1on|"y"]=se1f.ecf.y-{se1f.ecf.he1ghf/2}
efun pos1f1on
1he nal change we`e made is to add the leel number to the amount the turret
moes each cycle. 1his has the eect o speeding up as the leels get higher,
25
26
27
2
29
30
31
1
2
3
4
5
6
7

9
10
11
12
13
14
15
16
17
1
19
20
U|t|mate Gu|de to Raspberry P|
105
otherwise, as the gameplay accelerates,
the player would struggle to get across
the screen in time to shoot the ruit.
Run the game and you should nd
you can play multiple leels and get a nal
score. It may not be o commercial quality
but it`s a complete, working game, and
strangely addictie!
Targeting the Raspberry Pi
I you`e been using a PC to create your
game or the Pi, the last step is to test it
on real Raspberry Pi hardware to ensure it
perorms acceptably.
Pi Splat could certainly be enhanced
- with animations and explosions, or
example - but since it isn`t currently
possible to access the Pi`s ull graphics
capabilities rom Python reliably, you
may hae to keep your ambitions modest.
Once support is added, you`ll be able to
include spectacular graphical eects with
ery little impact on perormance.
Shar|ng your game
Once you`e polished your masterpiece, you`ll want to share it. Lxactly how you
go about that depends on your target audience.
Sharing with Raspberry Pi and Linux users
Lery major Linux distribution, including Raspbian, comes with Python installed,
and Raspbian also has Pygame as part o its deault installation. I you share your
game with users o other distributions, they may need to install Pygame.
Zip it up
1o share a Python program with other Linux users, you can simply compress
the les into an on \indows, these are called ZIP les, and send it. 1o
do this on the Raspberry Pi, right-click on the main older containing your game
and select Compress. 1hen choose a le name and type or the package. I you`re
sharing with other Linux users then you can leae the type as . I you
want to share your le with \indows users, you`ll want to change it to - in
this case, there are other some steps you`ll need to take too, which we`ll discuss
Our game is complete, including its own splash screen
U|t|mate Gu|de to Raspberry P|
106
below., \hen the recipient receies this archie, they`ll be able to extract your
les, load ma1n.py into Geany or their preerred Python enironment, and
launch the game.
Clearly it would be nicer i the player could simply double-click a le to run
the game. \e can achiee this by creating a script le that tells the computer
how to launch and run it. lere`s how to do this in Linux: start by naigating to
the older containing your ma1n.py le, then right-click and select Create New
Document|Lmpty Document`. Gie it the name sfaf.sh. Now, right-click and
select Open with Geany`. 1hen, in Geany type the single line:
pyfhon ma1n.py
.and sae the le. 1his is the same line you would type in at the terminal to
run a Python le. \e now need to tell Linux that it should execute this command
when the text le is double-clicked. 1o do this, open a terminal window and type
the ollowing:
cd Deskfop/P15p1af
cd is the Linux command or change directory` and it simply tells the
terminal that we want to work in the older containing the game. Replace
Deskfop/P15p1af with the location o your game i you`e saed it somewhere
dierent. Now, in the terminal type:
chmod +x sfaf.sh
1he chmod command changes the mode` o the le, in this case, the +x
makes it executable. So, or example, instead o launching a text editor, the
operating system will run the command. 1o see this in action, double-click the
start.sh` icon and select Run.
Sharing with Windows users
\indows doesn`t come with Python installed as standard, so you can`t simply
send a \indows user an archie o your game and expect them to be able to
play it. An easy solution to this problem is a tool called Py2Lxe, which can
compile your game into a single executable le that a \indows user can run
with a double-click. 1he process eels conoluted the rst time, but needs
doing only once - and the person you`re sharing with doesn`t need to do
anything at all.
1o begin, head oer to WWW.p11ab.nef/11nks and download Py2Lxe.
Next, we need to dele into the bowels o \indows to make sure Py2Lxe can
nd Python. 1o do this in \indows or 8, press the \indows key and type
U|t|mate Gu|de to Raspberry P|
107
Ldit Lnironment Variables` as a search term. Open the Settings dialogue
that comes up, click the Lnironment Variables button, and then, in the System
Variables list, nd the entry Path` and click the Ldit...` button. Now, assuming
you`e installed Python 2. to the deault location, simply add the ollowing entry
to the text in this box making sure the entry beore it ends in a semi-colon,:
c:/Pyfhon27
Sae these settings and then reboot the PC.
\hen \indows comes back up, go to WWW.pygame.og/W1k1/Pygame2exe
and copy and paste the text in the white box on that page into a Geany window.
1his is a template specically written or
using Pygame with Py2Lxe, so, to get it to
work or our project, we need to change
the ollowing lines:
. change lename to ma1n.py
. Change project name to P15p1af
. change project ersion to 0.1
. change licence to GNu Genea1
Pub11c L1cense ,
. change description to A s1mp1e
shoof-em-up
. change the se1f.exfadafas list to
include 1mages so that the game images,
in a subolder o that name, will be
bundled into the resulting le.
\hen you`e done all this, sae the
le as comp11e.py, then open a \indows command prompt and naigate to the
older containing your game using the command. So, or example, i you`e
been saing the program les into a older on your desktop, you might type:
cd Deskfop\p1sp1af
Now, to compile your LXL le type:
pyfhon comp11e.py
At the end o the process, you`ll nd a new subolder called d1sf that
contains all the les you need to distribute or your game to run. Double-click
the le with the LXL extension and your game should now run. 1o share the
game, all you need to do is ZIP up and distribute the contents o the d1sf older.
Download Py2Exe from the Pygame website Download Py2Exe fr the Py ebsite
U|t|mate Gu|de to Raspberry P|
108
Back in the mid-1990s, Russian programmer Lugene Alemzhin released a game
called barii in which the player scored points by matching three or more circles
o the same colour. 1hese circles then disappeared and their places were lled by
the circles rom the rows aboe, with additional circles randomly dropping rom
the top o the board to ll the gaps. Sound amiliar
Shariki was the basis o many popular games including the hugely successul
Bejeweled series by PopCap Games and current aourite Candy Crush Saga by
King.com. 1ogether, this genre has become known as vatcbtbree gave..
In this chapter, we`ll look at a Raspberry Pi ersion o this game called lruit
Pi. Although in principle, match-three games are relatiely simple, creating a
commercial-quality game is a more inoled task than Pi Splat, our simple shoot-
em-up. So, we`re going to take a look behind the scenes at the game halway
through its deelopment. 1hat way, we can discuss the game`s design phase, the
programming techniques used so ar and what remains to be done beore it can
be released. 1he code can be downloaded rom p11ab.nef/code.
Oreat|ng a
po||shed game
Chapter F|ve
U|t|mate Gu|de to Raspberry P|
109
How the game works
As with Pi Splat, the rst step is to look
at the game rom the user`s point o iew:
what do they expect rom a match-three
game lere are the basic rules, which are
shared by most games o this type:
1he player sees objects arranged in a
grid, usually 8x8.
1hese objects are randomly drawn
rom a limited selection. In the case
o an 8x8 grid, there are usually six. 1oo small a selection would lead to too
many matches, while too large a selection would result in too ew matches.
1he aim is to swap adjacent objects so that, in their new conguration,
they orm a pattern o three or more identical objects either ertically or
horizontally. I no swap is possible, the objects return to their original place.
1he initial board or each leel should contain no matches this is why it is
random rather than truly random,.
\hen a pattern is ormed, the objects are then remoed rom the board and
points are awarded.
1he objects directly aboe then drop into that space. Random ruits are
added at the top o the grid to keep the whole board populated.
I this change in conguration causes matches, the game processes them and
awards points.
1he leel is complete when a pre-determined score threshold is reached.
Dierent ersions o the game add extra eatures such as power-ups` or
rewards or matching the same object type more than once in succession.
1his is a comparatiely brie list o rules - it`s not like learning chess.
loweer, translating these simple requirements into a computer program is
a dierent matter. Once again, we`ll start by breaking the rules down into the
amiliar categories o input, logic and output to arrie at an initial set o tasks.
was the frst "match-three game"
U|t|mate Gu|de to Raspberry P|
110
Input
1he user needs a way to indicate which objects they wish to swap. In a computer-
based game, this will usually mean by using a mouse. 1he nal game will also
need a way o reading in any saed progress data or stored game preerences.
Logic
1he code must generate a pseudo-random set o objects ritb vo vatcbe. or the
initial board. \hen the player starts swapping objects, it must check or matches.
\hen a match is made, the logic must identiy which objects to delete as a result,
moe existing objects down the grid, and add new objects at the top to replace
them. linally, our game logic must keep track o game data, such as the player`s
current score and which leel has been reached.
Output
lrom the player`s perspectie, the graphics, animations and sounds are what
generate the experience o playing the game. So the game design, and the code
we create to implement it, must include:
Drawing attractie graphics
Loading them into appropriate classes
Animating them onto the screen
Indicating which ruit has been selected during swapping
Displaying the score and other game inormation
Saing game progress and preerence inormation to a le
Playing in-game music and sounds
It`s quite a list - and each o these tasks breaks down into many smaller
programming jobs. Ultimately, we could be looking at hundreds or een
thousands o lines o code. But don`t be intimidated: as we mentioned earlier,
many successul games hae been deeloped by ery small teams or indiiduals.
Iruit Pi
As with Pi Splat, we`ll aim to get a single leel running beore going on to
add multiple leels and the arious other eatures that make or a complete,
proessional game. Aside rom sourcing the ruit images or our game, we need
to make seeral decisions, namely:
U|t|mate Gu|de to Raspberry P|
111
1. The size of the playing area. \e`e decided on a width o 1,024 pixels
and a height o 68. 1his stretches the Pi`s capabilities whilst still being large
enough to make or a good isual experience.
2. How we will indicate which fruit is selected. 1he player needs a isual
indicator. 1his might be that the ruit increases in size when clicked, or
example. \e`e opted or a simple rectangle oer the selected ruit.
3. How we will animate fruit. Many games make use o . \e present
the ruit as i they`e been poured into the top o the computer screen rom
let to right, so we need to renect this in the animation.
4. How we will present user information. Our 1,024 x 68 window leaes
room or us to display inormation alongside the play area. \e`e opted to
put the board on the right and the inormation on the let.
1he game background is an 8-bit PNG le, and we`e created a graphic or
the board that`s placed on top. \e can reresh just this area when ruits moe,
saing processing power. \e`ll use sounds rom feesound.og as beore,
but beore implementing them we`ll ocus on getting the game mechanics and
graphics working well on the Pi.
Programming approach
As with Pi Splat, each ruit will be based on a lruit class, which will remember
what type o ruit it is and where it`s located on the screen. It will be capable o
updating its own position and ollowing rules about when to stop moing. \e`ll
also once more organise our code into modules. 1he ma1n module contains the
game loop, most o the logic is contained in a 1og1c module and most o the
output code will go in a module called d1sp1ay.
Our fruit-themed match-three game, ingeniously named Fruit Pi
U|t|mate Gu|de to Raspberry P|
112
Under the m|croscope
lruit Pi ollows a structure that`s typical o games, and in particular those games
created in Python. 1he central module, ma1n.py, contains the core o the game
- the main loop - with most o the work o generating and displaying the isual
objects and handling user interaction undertaken by an array o modules and
classes summarised in this diagram:
1his structure proides good examples o the dierences between modules
and classes. \ou can see that each o the classes denes an object that has a clear,
indiidual, identity. 1he Iu1f and Cuso classes are graphical objects and the
Game class is used to hold inormation about the game currently being played
including the score and leel,.
1he modules, on the other hand, are simply blocks o code organised
according to their purpose. 1he le 1og1c.py, or example, doesn`t dene a sort
o object: it`s a set o unctions that handles the program`s decision making.
Similarly, the unctions in d1sp1ay.py deal with the isual aspects o the
game - including creating and handling the ruit objects. 1o use a juggling
analogy, the class denes the balls and the module describes how the juggler
throws them. \e`ll see this working in practice as we look at the code itsel.
Modules, then, are mainly used to organise code into logical units, and they
also make it easier to share code across projects. \ou could dump the entire
contents o each module into the ma1n.py le and it would still work, but it
would be ungainly, impossible to reuse and hard to manage.
\ou`ll hae noticed that the module names are innuenced by our input,
logic and output approach d1sp1ay.py representing the last o these,. 1he
only reason there isn`t a discrete 1npuf module is because, or this game, the
user input amounts to little more than clicking a pair o ruits, so it can be easily
handled within the other modules.
1he way you organise your code must make sense to you and your team
i you aren`t working alone,. And, aboe all else, whateer approach you use, it
must be practical. I you eer eel you`re being restricted by the structure you`e
created, then you`e created the wrong structure!
game.py
cursor.py
c|asses
ma|n.py
fru|t.py
|og|c.py
modu|es
d|sp|ay.py
g|obvars.py
U|t|mate Gu|de to Raspberry P|
113
So, rom our thoughts on design and by using our input, logic, output
approach we can ery quickly generate a code structure or our game: we know
rom the start which objects we`re likely to need and which modules to create.
\e may add or remoe classes or modules as we deelop, but by thinking in
those terms we hae a good starting point.
\ou`ll notice one module that doesn`t t this rule: g1obvas.py. As its
name suggests, this module contains all the g1oba1 ariables or the game. Now,
mention the phrase g1oba1 va1ab1e to programmers o a certain type and
they`ll throw up their hands in horror because, used inappropriately, they can
cause problems.
loweer, it makes sense to use globals or ariables that need to be accessed
by all modules, especially where they are constants. \e do this by dening them
in a separate Python le and then importing it into all modules and classes.
lere`s the releant code:
In the case o this game we`re dening ariables including the height and
width o the game window, the position o the game board within that window,
and the height and width o the cells within the board. \e also dene some
common colours and a typeace.
The main loop
Let`s look at the structure o a typical main loop or a game. Broadly speaking,
this will be all that ma1n.py contains, with all the other work being done by the
modules and classes. \e might characterise the structure o operations as:
#lmpof modu1es and c1asses
#Def1ne va1ab1es
#DaW fhe backgound
#Game Loop
#Leve1 Loop
U|t|mate Gu|de to Raspberry P|
114
So, when the player rst launches the game and the background has been
drawn, they enter the game loop. Unless they`e continued a saed game, they`ll
be at leel 1, so the player enters the 1eve1 loop that handles eerything that
happens within the leel - ruit dropping into iew, swapping, deleting and so on.
Once the leel is completed, the player is sent back to the game loop as the
1eve1 loop is inside it,. 1his checks to see whether the player was playing the
nal leel and, i not, starts a new iteration o the 1eve1 loop. 1his continues
until the leels run out or the player exits the game. Let`s take a look at how this
works in practice.

\e start by importing the arious Python libraries we want to use on line 1:


pygame is the only one o these libraries that isn`t included in a standard Python
install although it is included on the Raspberry Pi,. Lines 3 to 8 import our
custom classes and modules. \ith these we use a slightly dierent syntax:
fom |modu1e/c1ass name] 1mpof "
1he fom keyword is mainly used to allow us to import part o a module. lor
example, the ollowing line would import only the and1nf unction rom the
kandom library:
fom andom 1mpof and1nf
1his is a more resource-ecient way o doing things, because Python doesn`t
hae to import any unnecessary code - but it means that i you subsequently
want to use another unction rom the library, you`d hae to go back and add it
to the fom line. By speciying an asterisk we import eerything, exactly as i we`d
used the 1mpof keyword. 1his may seem to deeat the object o using fom, but
by doing it in this way we can reer to the unctions within the module by just
using their unction name, rather than haing to also add the module name. So, i
we use the fom keyword with an asterisk as aboe, we can turn this line:
mynumbe=andom.and1nf{0,5}
U|t|mate Gu|de to Raspberry P|
115
. into the simpler:
mynumbe=and1nf{0,5}
In other words, once you`e imported a unction using the fom syntax, you
can use it as i it were built into the language rather than imported. 1his saes
typing and, in many cases, is just as clear as explicitly naming the module.
1here`s one caeat to this approach, though. I multiple unctions in separate
modules hae identical names then this will cause an error, so it needs careul
handling. One way to do this is to use only the fom method o importing with
your own classes. 1his means that game=game.Game{} becomes game=Game{}.
1he rst one must indicate which le the class is contained in, the second doesn`t
hae to because we`e used fom.
1his is another reason why you must organise your modules logically. I
your code is to be easy to understand, either by yoursel or another programmer,
you can either prex all module unctions with their name by using 1mpof or,
i you use the shorter orm, hae a logical structure to the modules that makes
it obious which one a unction belongs to. lor example, you could reasonably
expect to nd a unction called an1mafeIu1fs in the d1sp1ay module, you
wouldn`t expect to see it in 1og1c.py.
Let`s look now at the heart o the game - the leel loop. 1his loop runs many
times per second and carries out the ollowing instructions during each cycle:
1. I ruits are alling both at the beginning and when ruit is remoed, draw
the animation beore moing on.
2. I not:
a. Check whether any keys hae been pressed or whether the mouse button
has been clicked.
b. I a ruit has been clicked on then:
i. I it`s the rst o a pair, draw the cursor.
ii. I it`s the second o a pair, check whether the two ruits are
neighbours i not, they can`t possibly match,.
iii. I so, run the matching algorithm and:
1. I they do match, swap the ruits, update the score, delete the
ruits, regenerate the board in its new conguration and animate
into place.
2. I they don`t match, moe the ruits back.
i. I the two ruits were not neighbours, set the second ruit to be the
new position or the cursor and await a second click.
3. I no animation is taking place, reresh the screen.
U|t|mate Gu|de to Raspberry P|
116
1his leel loop continues to run until a pre-determined score is reached or
the leel, at which point it exits back to the main game loop. Most o the lines
within the leel loop call unctions rom modules or classes that carry out the
actual work. lor example, consider this line:
an1mafeIu1fs{boad,Dl5PLAY5ukIACL,fu1fsp1fegoup, >
8OAkDAkLA,boadgaph1c}
1his single statement calls a 34-line unction in d1sp1ay.py. Using unctions
in this way makes it easy to reuse the unction elsewhere in this program, and
it helps keep the code clear and easy to understand. \ithout knowing any o
the detail o how an1mafeIu1fs works, another programmer could look oer
the main module and instantly understand what the line does. So, ma1n.py is,
in a sense, a road map showing the primary route the program takes, with each
module sering as a street atlas proiding the detail.
Loading fruits
Beore each leel begins, the game must create a alid board. 1o do this we must
rst decide how the board will be represented, that is, what sort o ariable can
we use to store it lundamentally, the board is simply a table with eight rows and
eight columns, and once you`re used to Python you`ll immediately realise that the
humble list is the ideal ariable type to store this. \e might create a list or the
bottom row o the playing area that looks like this:
{`sfaWbey`,`sfaWbey`,`pea`,`banana`,`pea`,`chey`, >
`aspbey`,`aspbey`}
1o deal with the act that we hae eight dierent rows to handle, we`ll make
use o the act that a list can contain other lists. In other words, we`ll store the
play area as a list o eight lists, each o which represents a row. \e can then
access the alue o, say, the second ruit on the bottom row ia the statement
below. Remember that all lists are zero-indexed!
Iu1f=boad|7]|1]
In practice, we rarely need to do this: it`s easier simply to pull the whole row
out and then access it in the normal way.
Now we`e decided how our board will be represented, we can write a
unction that will create a new alid grid o ruits. 1he game loop runs this
command beore each leel:
1oadIu1fs{boad,fu1fsp1fegoup}
U|t|mate Gu|de to Raspberry P|
117
As you`d expect, this unction is ound in d1sp1ay.py: here`s how the
releant code looks:
1he use o two fo..1n loops such as this is ery common when you want
to represent two-dimensional structures such as a table in code. Line 23 runs
eight times, once or each row - during which line 2 runs eight times, once or
each cell in the row.
Line 25 sets the ertical position o the row, using the global ariables to
do so. By doing it this way we could replace the existing board with one o a
dierent size by simply changing the alues o those global ariables.
Remember that one o the rules or the initial board is that it mustn`t contain
any immediate matches, so the 1f statements at lines 30 and 34 check whether a
pair o the same ruit already exists to the let o the current cell or immediately
aboe it. I so, then we can`t use that ruit or this cell. So, we make a list called
exc1udefu1fs, speciying those ruits we mustn`t choose this time. \e then
call the geffu1f unction in the logic module, which will send back the name
o a randomly generated alid ruit. lere`s the releant section o 1og1c.py:
1ake a look at the parameters or geffu1f. \ou`ll see that we speciy
exc1ude11sf as you`d expect, so that d1sp1ay.py can send a list o ruit names
U|t|mate Gu|de to Raspberry P|
118
we mustn`t choose. loweer, most o the time this list will be empty. By setting
exc1ude11sf=|] we`re telling Python that i we aren`t sent a list, we can assume
that there are no ruits, and to thereore use an empty list in this unction. 1his is
a deault setting - it can be ery useul i you aren`t sure which parameters will be
passed to a unction.
\e then create a list with the complete set o ruit names and, in line 123,
cycle through the list o excluded ruits, remoing them rom the list o ruit
names in line 124. 1he 1f statement in line 124 is needed because i, say, there
are two raspberries to the let two aboe, then exc1ude11sf would contain
raspberry` twice - and Python would throw an error i we tried to remoe it
when it had already been deleted.
Lines 126 and 12 pull a random ruit out o the remaining candidates and
send them back.
Once we hae that name, we can create a new Iu1f object or this cell.
\e then add this ruit to the row and, once we hae a whole row, we add it to
the board.
fh1sfu1f=Iu1f{fu1fname,x,y,oW,co1umn,speed, >
8OAkDWlD1h,8OAkDhLlGh1}
1his calls the initialisation routine in the Iu1f class and sends it the
inormation it needs in order to create a ruit object. In this case, this means it
will load the correct graphic and set its nal position on the board. It also sets a
ariable called mov1ng, which the code will use later to work out i the ruit is
still animating or whether it`s arried in place.
1he other unctions contained in the Iu1f class illustrate how sel-aware
it is. ca1cu1afeneWpos1f1on works out where the ruit should be the next
time it`s drawn to the screen. It takes account o whether it`s traelling down
the screen as it would be initially,, across or up in the case o a swap,, and also
works out when to change the mov1ng ariable to Ia1se so that the game can
then ignore it during animation. In traditional procedural programming, you`d
need to write a complicated nested list to track each ruit rom within the leel
loop, here we leae it to the object itsel to do this.
ca1cu1afene1ghbous method records the ruits aboe, alongside
and below this ruit where applicable,. 1his is used later by the leel loop when
determining whether ruits can be swapped.
change1mage is used when we swap ruits - this is because we`re actually
changing their image rather than directly swapping objects. 1his is a much
simpler approach because it means that each object can retain its and
positions in the grid or the entire leel, and simply needs to update its ruit
graphic to renect the state o play. 1his unction handles all the changes
necessary when a ruit changes.
U|t|mate Gu|de to Raspberry P|
119
An|mat|ng fru|ts
One particularly distinctie aspect o
games such as Bejeweled and Candy
Crush Saga is the way the objects - gems,
sweets or, in our case, ruit - all onto
the screen. \hen designing a routine or
this, the rst step is to write a set o rules
or displaying the objects. Our rules are
simple enough: rst, the ruit appears
rom the top and lls the board rom the
bottom upwards. 1hen, ruit lls rom the
right-hand side o the row.
In other words, when building an
empty board, the bottom right-hand cell
is the rst to be lled with ruit, and the
top-let-hand cell the last. 1he implication
o this is that we hae to build a routine
that not only adds ruit rom bottom to
top but also rom right to let.
Remember, at this point we hae a list
called boad containing eight sub-lists representing the rows and each containing
eight ruit objects, one per cell. Our job now is to animate them onto the screen
rather than simply plonking them there in one go een though that would be
much simpler to program!,. 1o make matters more dicult, the row should ll
rom right to let rather than the whole row appearing at once.
1he an1mafeIu1fs unction is contained in d1sp1ay.py, as you`d expect,
and is called rom the leel loop wheneer the epa1nf ariable is set to 1ue.
1his will be the case at the start o each leel as the board lls up and each time
ruit is remoed by swapping.
lere`s the line that calls it:
an1mafeIu1fs{boad,Dl5PLAY5ukIACL,fu1fsp1fegoup, >
8OAkDAkLA,boadgaph1c}
\hat do we send to an1mafeIu1fs 1he board the list o ruits organised
by row,, the Pygame surace onto which we`re going to draw, the sprite group
into which all the ruits will be placed, a global containing a ecf o the board
area that is, its x, y, height and width,, and a reerence to the graphic itsel.
1he structure o an1mafeIu1fs is similar to that o 1oadIu1fs in that
we`re iterating oer rows and columns. 1his time, howeer, we`re altering the
position o the ruit each cycle.
an1mafefu1fs produces the effect of fruit being
poured onto the screen from bottom to top, right to left
U|t|mate Gu|de to Raspberry P|
120
1he aboe code shows the releant part o d1sp1ay.py. \e begin by making
a copy o the board 11sf - we`ll see why later. In line 63 we begin the row by
row loop, the evesed keyword species to start at the end o the list the
bottom row, and work upwards. On line 65, we add the entire row to the sprite
group, then we work through each ruit again using evesed, this time to work
rom right to let, progressiely raising the ertical position as we go. 1his gies a
staggered line with the let-hand ruit urther o-screen than the right.
\e then run each ruit in the row`s moveme unction, which launches the
ca1cu1afeneWpos1f1on unction we coered earlier. \e check whether the
ruit`s mov1ng property is Ia1se - indicating that it`s arried at its nal position
- and i so, we remoe the reerence to that row rom fu1foW. 1hus, we use
ewer resources as each ruit stops moing, and we can use the 1en unction
in line 2 to check when the row has completed. I we`d been using the actual
boad ariable, it would end up containing no ruits. 1his is why we copied it.
Line 9 calculates the minimum area the ruit will pass oer as it alls. As the
rows build up rom the bottom, we don`t need to redraw the settled rows eery
cycle, so this area becomes smaller and smaller. \e eed this calculation into
line 81`s b11f operation, which draws the board. \e draw the ruit sprite group
in one go but only update the shrinking board area. \e could redraw the whole
board each cycle, but this more ecient approach helps the Pi to keep up.
Once the board has been drawn, the program waits or the user to click
on a ruit. Just as with key presses, Pygame can or mouse eents, such as
MOu5L8u11ONDOWN. \orking out which ruit the mouse pointer was oer when
the button was clicked is handled in the 1og1c.py unction Wh1chfu1f:
U|t|mate Gu|de to Raspberry P|
121
1his code takes adantage o a Pygame unction called co111depo1nf, which
receies as a parameter the evenf.pos returned by MOu5L8u11ONDOWN this is
actually two numbers, namely the and positions,. Our loop simply iterates
through each ruit in turn, checking whether co111depo1nf is 1ue or that ruit.
\hen it is, we know we`re dealing with the ruit that`s located under the mouse
pointer, so we efun this object.
Back in ma1n.py, we now check whether this was the rst ruit to be clicked
in a pair by establishing whether pa1offu1fs|`souce`] already contains a
ruit. I it doesn`t, we assume this is the rst click, moe the cursor oer this ruit
and wait or the player to click again.
Otherwise, the e1se at line 61 is triggered and we check whether the second
ruit is a neighbour o the rst. I it isn`t, we consider this a new` rst click,
since we assume that the player has ound a match elsewhere. I the second ruit
a neighbour o the rst then we must check whether there is a match and, i
so, increment the score and update the screen. I not, we swap the ruits back to
their original positions and go back to square one.
U|t|mate Gu|de to Raspberry P|
122
F|n|sh|ng the game
So ar, we`e seen how the code builds a playing board, animates the pieces into
place and handles the player`s attempt at matching ruit. 1he next thing we need
is some code to check that two selected ruits really are a alid match. 1he rst
step here is to check whether the selected ruits are neighbours. lere`s the code
rom 1og1c.py that handles this:
1his code is pretty simple: remember that when we created each ruit object,
we ran a unction that established its immediate neighbours. 1ake a look at line
32 and consider how this would translate into plain Lnglish: f botb frvit. are ov tbe
.ave ror tbe .ecova frvit`. covvv vvvber i. tbe .ave a. tbe fr.t frvit`. veigbbovr ov tbe
eft, tbev tbe, vv.t be veigbbovr..`
\e then check the same on the right, then, in lines 36 and 38, we work out
whether they are neighbours aboe or below. I any o these tests returns a 1ue
result, we immediately return this, along with the direction. I none o them
returns 1ue, we return Ia1se because we`e established that the selected ruits
can`t be neighbours.
Assuming they are neighbours, our next task is to work out whether, by
swapping the ruits into the place the player intends, a ertical or horizontal line
o at least three ruits would be ormed:
U|t|mate Gu|de to Raspberry P|
123
1he actual business o nding matches is pretty straightorward. \e begin by
making a copy o the board, so we can work on it without changing the original.
\e then use our amiliar double fo..1n structure to go through each row and
column in turn. Note that at line 13 we only need to check the rst six ruits in a
row: this is because any pattern that begins in the seenth would be too short to
be alid the same applies to columns,. lor each ruit, we check to see whether
the two ruits to its right are the same as it. I so, we set the de1efe property to
1ue or all three ruits. 1his has no immediate eect - it simply marks the ruit
or deletion later.
\e repeat this or the columns rom line 18, and send back both the any
mafches ariable 1ue or Ia1se, and, i 1ue, the updated copy o the board.
1his contains copies o all the ruit objects, with those that are part o a matching
pattern haing their de1efe property set to 1ue.
1he aboe code implements the de1efemafches unction - arguably the
most important unction in the entire program. 1his section o code remoes
ruits that hae been ound to be part o a matching set, and generates a new
board with all the necessary changes made. It begins by creating two lists, both o
eight elements one or each column o the board,.
U|t|mate Gu|de to Raspberry P|
124
Lach element o the rst list, exfafu1fsneeded, represents the number
o new ruits that need to be generated or that column. 1he second list contains
the number o the last row that is aected by the changes, again by column. 1his
enables us to simply ignore the rows that remain the same.
At this point, we need to think about how we`re going to handle ruits
disappearing and being added. lrom the player`s perspectie, when a gap appears,
the ruit aboe drops to ll the gap. As we`e mentioned, it`s easiest to handle
this by updating the objects in the releant positions. So, i three raspberries
disappear and the ruit aboe the gap is a cherry, we can simply change the
bottom raspberry to a cherry. 1his starts at line 9, aboe. 1o proide the
correct isual eect, howeer, we don`t want the cherry to instantly jump down
into place, but to all rom its old position to the new one. \e achiee this by
temporarily changing the position o each aected ruit to the same as the ruit
whose ariety it`s stolen. 1hen we animate it moing back to its original position.
Lines 90 to 94 deal with adding new ruits to the board - or, to be precise,
assigning new ruit names as needed to ll the gaps where ruits hae allen
down. \e generate random names or the releant slots, load in the graphics and
set the new ruits aboe the board so they can be animated into place.
1here`s one nal eentuality we must deal with: what i, ater the player has
matched a line o ruits, and the board has been updated, the resulting updated
board itsel contains new matches 1his is easy to handle: once the ruits hae
animated back into position, we run the checkfomafches process again.
1he unction doesn`t care whether the board it`s working on was created by
a user swapping ruits, or is the result o being regenerated. Lither way, it will
check through and report any matches.
Because we`e used modular code, we`re
able to reuse the an1mafefu1fs and
checkfomafches procedures to handle
both the initial board and all subsequently
generated boards with no additional work.
Next steps
\e now hae a ully working single
leel. 1he next step is to implement
multiple leels, along with a splash screen,
instructions and a unction to sae
progress. 1he graphics and animations
will need a little extra polish and sound
eects are more or less mandatory.
loweer, adding additional pizzazz will
impact perormance. So it`s important
Fruits drop into place to fll the gap left by a match
U|t|mate Gu|de to Raspberry P|
125
to thoroughly test the game on the Raspberry Pi, and optimise the basic ersion
or this slow platorm beore adding anything else. I your game is intended only
or more powerul computers you can omit this stage, but you`re narrowing
your audience. 1he best approach is to optimise as ar as you can and add only
a minimum o extra graphical oerhead to the nal game - that way, it should
work well on all platorms.
T|ps for programm|ng games
1. Get each part fully working before moving on. lor this game, the rst
step is to create the initial game board - so this was implemented beore
animation was considered. 1hat was completed beore the interactie
eatures were added. 1his approach can mean updating code when you moe
to the next stage, but you`re always building on a ully working oundation.
2. Code, test, code, test... Remember that coding is done in small steps: you
write a line or a short block, and you test it. It almost neer works rst time,
so amend and test again. Only moe on once it`s working.
3. Write it down! Don`t be araid to pull out a pen and paper when you get
stuck. It can be hard to isualise the eect o what you`re doing sometimes,
but by drawing a rough representation o what the player will see, you can
work out the consequences o your code.
4. Use the terminal. I you`re unsure o how a piece o code works, type it
into the Python interpreter ia the terminal and see what happens.
5. Use the documentation. Python has excellent ocial documentation
at pyfhon.og, and on third-party sites such as WWW.sfackoveoW.com.
1here`s no need to struggle - the Python community is ery helpul.
6. Write the documentation. Use the 4 symbol to document your code as you
go. 1he code examples in this book don`t include extensie documentation
or reasons o space, but the online samples are heaily commented.
. Take a break. I you nd yoursel struggling with a particular problem, take
a break. It`s amazing how oten a solution to a seemingly intractable problem
can pop into your head when you`e rested.
8. Lnjoy yourself. Gie yoursel a big pat on the back when you get each part
o the game working. 1here is nothing quite like working hard on a piece o
code, getting deeply into it, running it and seeing it work on-screen.
UItimate Guide to Raspberry Pi
126
1he Raspberry Pi has a number o eatures that make it ideally suited to real-
world projects. It`s cheap, small and rugged, and needs only a modest power
supply. In this section, we`re going to discoer how to turn a Pi into a climate-
monitoring station that can take measurements o the temperature, air pressure
and light leels outside - and sae them in a orm you can then analyse using a
spreadsheet program such as Microsot Lxcel.
\e`re also going to coer how to connect to Dropbox, so that our project
can share its results across multiple deices. linally, we`re going to look at how
to use a Raspberry Pi without a keyboard, monitor or mouse, so that you can use
your Pi in a wide range o small-scale projects.
The project objectives
Lery home, school or workplace has its own micro-climate, so by taking
measurements, you are generating unique local data. \ou can record seasonal
nuctuations, or example, or obsere how climate readings relate to weather.
P| |n the sky
Chapter S|x
UItimate Guide to Raspberry Pi

lere are e questions you might want to design experiments or:


1. Does higher air pressure correlate with higher temperatures and clear sky
2. Can a trend in air pressure predict temperature and,or light leels I so, how
ar ahead
3. \hat is the range o temperatures experienced at your location this year
\hat is the aerage low does that compare with the aerage at your local
Met Oce weather station and across the region,country low does it
compare with historical aerages
4. Is there a correlation between light leel and temperature on any gien day
5. low does the length o the day ary during the year Is the speed o
lengthening,shortening consistent or does it change with the seasons
1he list o theories to test is almost endless, but we`re going to design our
experiment with these e in mind. \e can always add extra sensors and code to
enhance it later.
Lquipment list
1o answer the questions aboe, we need sensors to read temperature, air pressure
and light leels, as well as somewhere to house them. \ou can hook sensors
directly to the Raspberry Pi`s GPIO pins or ia a breakout board,, but we`e
opted or a system based on USB. 1his makes the hardware setup dead simple
no soldering required, and it also means you could use a laptop as the host
computer i you don`t hae a Pi.
Specically, we`ll use the 1inkerlorge system WWW.f1nkefoge.com,,
which is made up o controllers bricks`, that plug into the Pi`s USB socket and
sensors bricklets`, that connect to the bricks. 1his tutorial has been written
specically or these components, nd direct links at p11ab.nef/11nks.
Raspberry Pi and case - any ersion we used a Model A,.
Raspberry Pi power supply
4-port unpowered USB hub
Compatible USB wireless dongle - see hffp://e11nux.og/kP1
ve1f1edPe1phea1s#u58W1-I1Adapfes or a list o possible options.
\e used the 1P-Link 1L-\N23N in this project.
UItimate Guide to Raspberry Pi

4GB SD card - or larger with Raspbian and Geany.


Keyboard, mouse and monitor - needed only or deelopment, once we
deploy the project, these can be disconnected.
A Master Brick, Temperature Bricklet, Ambient Light Bricklet,
Barometer Bricklet and optional Humidity Bricklet, all aailable rom
1inkerlorge. \e also recommend a 3m USB cable and mounting kit or the
Master Brick, plus cables and mounting kits or each bricklet. 1he length
o the bricklet connector cables will depend on your specic project, i in
doubt, get the largest size. 1he mounting kits consist o our small pillars.
Lach sensor is xed to the pillars with the included bolts, which can then be
screwed into a mount o your choice.
Bird nesting box - yes, really! \e`re going to use this to house our sensors
and, optionally, depending on how you want to set it up, the Master Brick.
Drill holes in the ront and sides to allow air now i the holes are big enough
or birds to t through, use gauze
or chicken-wire to preent this, and
paint it white to renect heat. \ou also
need to drill a hole in the back to eed
cables through.
Choosing a location
1he Raspberry Pi must be within range
o a \i-li router unless you`re able to
connect directly to a wired network,. 1he
bird box containing your sensors must be
outside in a position where it isn`t exposed
to direct sunlight at any time, as this
would aect the temperature readings. It
should be sited around 4t o the ground
and positioned so that there`s reasonable
air now around it.
1he Pi itsel will need to be protected
rom the rain. One option is to attach the
bird box to the outside o a house, school
building or garden shed with the Pi inside.
\ou can try housing the Raspberry Pi in a
weatherproo box don`t put it in the bird
box,, but you`ll need to think about how
you`re going to proide it with power.
This bird box hides a set of sensors linked to a Raspberry
Pi inside the shed that has been monitoring the climate
continuously since July 2012
UItimate Guide to Raspberry Pi

Step J: Getting started


Our deelopment process will inole using the Raspberry Pi in the
normal way, connected to monitor, keyboard and mouse. Once we hae
eerything working, we`ll moe it to its nal position and log into it
remotely. Prepare your sensors by connecting the USB cable to the Master
Brick and then connecting the sensors to the brick - do not plug these into
the Pi yet you can get urther instructions rom 1inkerlorge,. Boot into
the desktop.
Step 2: Install Brick software
\e`ll now set up the drier that allows the Raspberry Pi to communicate with the
Brick - the Brick Daemon - and a utility called the Brick Viewer, which allows us
to see the status and readings rom the brick and sensors.
J. Brick Daemon
Begin by starting LX1erminal and typing the ollowing:
sudo apf-gef 1nsfa11 pyfhon-fW1sfed pyfhon-gudev 11busb-1.0-0
1his will install the releant libraries. 1hen ollow with these two lines to
get` the latest ersion o the Brick Daemon rom the 1inkerlorge website and
extract and install the drier:
Wgef hffp://doWn1oad.f1nkefoge.com/foo1s/b1ckd/11nux/>
b1ckd11nux1afesfamhf.deb
sudo dpkg -1 b1ckd11nux1afesfamhf.deb
2. Brick Viewer
Once the Daemon is installed, return to LX1erminal and type the ollowing:
cd /home/p1
sudo apf-gef 1nsfa11 pyfhon pyfhon-qf4 pyfhon-qf4-g1 >
pyfhon-qWf5-qf4 pyfhon-openg1
Wgef hffp://doWn1oad.f1nkefoge.com/foo1s/b1ckv/11nux/>
b1ckv11nux1afesf.deb
sudo dpkg -1 b1ckv11nux1afesf.deb
Shut down the Pi, plug the Master Brick into the computer`s USB port and
start it up again. \ou can then launch Brick Viewer it`s in the Other` older,
and click the Connect button. Ater a couple o seconds, the Master Brick and
Bricklets will appear. Click the tab or the temperature sensor and you`ll see the
reading it`s reporting.
UItimate Guide to Raspberry Pi
130
3. Installer Software
Beore we go any urther, we can make lie easier or ourseles by installing
Python`s Setup 1ools library. 1his will in turn make installing the additional
Python tools we need to communicate with our arious bricklets ery
simple. 1o install the library, go to hffps://pyp1.pyfhon.og/pyp1/
sefupfoo1s#f11es download the appropriate ersion or your system. Once
this has downloaded, type:
sudo sh sefupfoo1s-0.6c11-py2.7.egg
...into LX1erminal, replacing the sefupfoo1s ersion with the name o the
le you`e actually downloaded the aboe line is or a Pi running Python 2.,.
An egg le is the Python equialent o a standard Linux package. It contains
all the necessary les as well as setup inormation that ensures the package is
properly installed into the operating system.
Once this process has completed, we`ll hae access to a new command,
easy1nsfa11, which we can then use to set up additional Python tools with
a single line.
Cod|ng the bas|c app
\e`e now set up a working connection between our sensors and the Raspberry
Pi. 1he next step is to make them programmable through Python. 1o do this, we
need to install the language - a code library that orms a bridge between
the bricklets and our application.
Begin by going to hffp://WWW.f1nkefoge.com/doc/DoWn1oads.
hfm1#b1nd1ngs-and-examp1es and downloading the Python bindings.
Right-click the le once it`s downloaded and extract the contents to
home/p1/f1nkefoge.
\e now need to set up the library so that Python knows where to nd it.
Open a terminal and type the ollowing:
cd f1nkefoge
sudo easy1nsfa11 f1nkefoge.egg
1he rst line moes the terminal into the 1inkerorge older and the
second one uses easy1nsfa11 to set up the libraries. \e can now use 1mpof
f1nkefoge in any Python code we write.
You can download the code for this project from WWW.p11ab.nef/code
UItimate Guide to Raspberry Pi
131

\e want our code to take periodic readings and then sae them in a orm we can
use. I we intended our code to also process our measurements into charts and
tables then we`d probably choose SQLite as the method or saing data, because
it lets us retriee the results using sophisticated database queries.
loweer, it`s much simpler to use a spreadsheet application such as
Microsot Lxcel or Google Docs to analyse and graph data. So, at this stage at
least, we`re going to output our data in CSV comma separated alues, ormat,
which can be read by all spreadsheet programs. It`s a ery simple ormat -
eectiely it`s a text le, which, in our case will contain each set o measurements
on its own row.
Since we want to make repeated measurements, our main structure will be
a loop, exactly as in a game, except that the code will loop much more slowly -
eery 15 minutes in our case. \ou can, o course, pick a dierent interal.
Gett|ng connected
Lach 1inkerorge sensor has its own unique ID UID,, which allows you to hae
more than one o the same sensor type connected at once. lor example, you
might want to measure the temperature both inside a building and outside. 1he
easiest way to nd out the UID is to start up the Brick Viewer and click the tab
representing each one, you`ll see the identier listed.
Once you hae the IDs, create a new le in Geany called and enter
the import statements we need:
Once again, we import Pygame to handle keyboard eents, plus the CSV
module to sae our spreadsheet le. \e then set up a number o ariables
including the UIDs or each o the sensors. linally, we import our 1inkerorge
libraries: the rst is the code or connecting to the Master Brick and the
remaining lines import libraries or each o the sensors we`re using in this project.
UItimate Guide to Raspberry Pi
132
Reading the sensors
lor testing purposes, we`ll write a loop that senses eery two seconds as waiting
15 minutes to see i our code is working is clearly dat,. lere`s the code:
It begins by creating ariables based on the lPConnecf1on object, and then one
ariable or each sensor. In line 21, we make the connection to the Master Brick.
\e then set up a loop that`s ery similar to those we used or our games: it keeps
cycling until we press the Lscape key.
Lines 33, 34 and 35 read the measurements rom the sensors and conert
them to the standard orm: millibars or air pressure, degrees Celsius or
temperature, and lux or light.
linally, we print the alues. Gie it a go! \ou should see the current readings
appear in the terminal eery couple o seconds.
Sav|ng to spreadsheet
lor our project, we`ll need to keep track o calendar dates and times o day - and
these are complicated things or computers to handle. 1hanks to the ancient
Babylonians, our time measurement system is based largely on the number 60
with 60 seconds in the minute and 60 minutes in the hour,, which isn`t entirely
UItimate Guide to Raspberry Pi

computer riendly. In addition, the Larth takes approximately 365.25 days to


orbit the sun so we also need to account or leap years. A nal complication is
added by the act that the same point in time will represent dierent times o day
in dierent locations - and those times ary throughout the year. In the UK, we
use Greenwich Mean 1ime GM1, in the winter and British Summer 1ime BS1
or GM1-1, in the summer.
\hat our project requires is a standard and accurate way o recording when
measurements were made. lor example, we might want to compare the time o
sunrise throughout the year: i we stick to local time, that will seem to spring
orward` by an hour in March and all back` in October. 1he best plan is to use
GM1 or its international equialent U1C, throughout the year and add an extra
column to our data that records how many hours to add or deduct rom that to
get the local time.
lortunately, Python proides libraries to help with managing time. \e need
to add the ollowing lines to the top o the code:
fom dafef1me 1mpof dafef1me
1mpof pyfz
1he second o these modules, pyfz, adds time zone inormation to make
the job o working out how many hours to add a doddle. Building on these,
we can create a module called geffomaffedf1me, which returns the current
time ormatted the way we want it. \e begin by dening a time zone using
pyfz`s built-in denitions and calling it GM1. \e then retriee the current U1C
time using the noW{} method o dafef1me beore using 1oca11ze to return the
GM1 equialent:
Once this is done, in line 28 we create a date in the ormat dd,mm,
yy` using the string ormat conentions common across most programming
languages. \e do the same or the time in line 29 and then, in line 30, we store
the current zone oset. In the summer, this will be a 1 because the UK time at
that point will be one hour ahead o U1C. linally, we return these alues to the
ca111ng unction in the orm o a dictionary with dafe, f1me and zone entries.
UItimate Guide to Raspberry Pi

Back in the ma1n loop, we`e remoed the temporary p1nf statements
that wrote temperature, pressure and illuminance alues to the screen. \e`e
replaced them with the code at line 56, which calls our new geffomaffedf1me
unction. 1hen, on line 58, we assemble a new list object that contains the
inormation returned rom this unction. lor example:
"27/02/2013,14:14:17,0,6.75,1027,594.3"
Now, all we to do is sae this inormation to a CSV le. In line 11, we`e
created a new constant Ou1Pu1IlLL that holds the name we`re giing to this le.
Lines 18 to 21 are all we need to add the current measurement to that le. In line
19, we open the le it will be created i it doesn`t already exist,. 1he parameter
a+ tells Python that we want to append this measurement to the end o the le.
UItimate Guide to Raspberry Pi
135
\e then create a new object based on the csv object and, on line 21, we use the
csv library`s W1feoW unction to sae the measurements to the CSV le as a
single line. \e then close the le.
I you run the completed code or this ersion o the program, you should
notice the CSV le being created and lines being added eery two seconds. Lnd
the program and open the CSV le in your spreadsheet program: you`ll see that
seeral rows hae appeared.
Add|ng a summary
Our CSV le grows at quite a rate, and een once we`e set the sampling period
to its nal alue o 15 minutes which we`ll do by increasing the interal in
pygame.f1me.Wa1f to 900,000 milliseconds, - we`ll still be generating a lot o
data oer time. lor most purposes this is good. I we want to see i there`s a
correlation between light leels and temperature, or example, haing plenty o
data to choose rom across any particular day is helpul.
loweer, i you wanted to examine the link between air pressure and aerage
temperature oer a month or more, it would be more conenient to hae the
data summarised and organised by date. lortunately, the work inoled in saing
a second set o data is pretty minimal: all we need to do is total up the day`s
readings and then sae them once per day.
\e`ll do this by creating a class called 1oday, which we can call rom our
ma1n module at the appropriate time. 1his class has three ariables also called
, to keep running totals o the temperature, air pressure and light leels.
Lery time measurements are made, we now add a unction called updafe that
tells 1oday to update its totals and check whether the day has nished:
UItimate Guide to Raspberry Pi

\orking out whether the day has ended is pretty simple: all we do is pass the
current day number to the unction and check whether it equals the one stored
by 1oday. I, or example, we took a reading at 11.50pm on 21 July, then foday.
day would hae a alue o 21 and the alue o day passed by the main loop
would also be 21. liteen minutes later, howeer, the day alue in the main loop
would hae increased to 22, as it would now be 22 July. \hen day was compared
with foday.day, the two would now be unequal and we`d set neWday to 1ue.
\ou can see on line 3 that this triggers the summa1se unction and sends it the
nal set o measurements.
I it`s not a new day, we add the current measurements to the lists and then
sae them using p1ck1e otherwise, i the program were stopped at any point
during the day, all the preious measurements would be lost,. 1hen, on line 4,
foday`s ariables are cleared ready or the new day to start rom scratch and
then the latest set o measurements is added to the new lists:
Once we`e read the p1ck1e data into the lists, we want our summary
to include minimum and maximum temperatures or the day, along with the
aerage temperature. \e do the same with aerage pressure and also report the
maximum light leel - we don`t report the minimum because that will always be
zero at night,. \e don`t record an aerage or the same reason.
\ou can see that, because we`e stored each set o measurements in a list, we
can use Python`s built-in unctions to make nding the maximum and minimum
ery simple. Once the alues hae been calculated, we create a new list called
summay and send it back. Now we simply need to insert three lines into our
main loop to trigger the update:
Note that neWday will either be Ia1se i we`e simply updated the current
day`s running totals, or it will be a list i midnight has just passed. In this latter
case, we then trigger a new unction in the ma1n module to sae the summary:
UItimate Guide to Raspberry Pi
137
Since there are more alues to deal with, and it isn`t necessarily obious what
each one represents, we`re going to add a header row to the spreadsheet. So, on
line 33, we use the os module`s pafh.ex1sfs unction to establish whether the
CSV le has preiously been created in other words, whether this is the rst
time the program has been run,.
I the le doesn`t exist, we write a header row, ollowed by the summary data
line. Note that in this case we use the `W` parameter or opening the le: this is
because we are rritivg a new le rather than aevaivg to an existing one.
I the le does exist, the code in lines 39-41 saes the additional row in
exactly the same way as with the 15-minute measurements.
Us|ng th|rd-party serv|ces
Python is powerul and easy to use - but what i the unctionality you`re ater
already exists in another serice lor example, you might want to allow users
o your latest game to be able to post their scores to lacebook thus attracting
potential new players,. 1he social network doesn`t gie you direct access to its
code, naturally, but it has created an Application Programming Interace API,
that allows your programs to talk to theirs. 1he API eectiely species the rules
or the conersation` between your
program and the serice, and species
which topics` are allowed.
I you wanted to proide your users
with a list o books on a specic topic, or
example, you could do that by using the
Google Books API - or direct them to
their nearest bookshop with the Google
Places API. \ou can embed Netnix`s
unctionality into your app using its
API, or sae les into the cloud using
Google Drie, Amazon S3 or the popular
Dropbox serice. Let`s do that now.
UItimate Guide to Raspberry Pi

Dropbox is a cloud storage serice. Lssentially it works by proiding a special


older on the Dropbox serer that`s accessible only to the user. \hen you install
the client` sotware on your computer or mobile deices, the contents o that
older are copied onto it. Dropbox keeps all deices synchronised as les are
added, edited and deleted - so, or example, i you create a new document on
your PC and sae it to your Dropbox older, you could then access the same
document on your iPad without taking any other action.
As well as client sotware and a web application or managing your content,
Dropbox also oers an extensie API to allow you to access your les ia a
program. Gien that there is no ocial Dropbox client or the Raspberry Pi,
we hae no choice but to make use o the API - but this is a conenient way
to proceed anyway, since it gies us sophisticated access to Dropbox, enabling
us to build complex and useul eatures into our code, without any need or
user interention.
Dropbox and Python work well together, not least because the Dropbox
client is itsel written in Python. As with most APIs, Dropbox includes its own
library that makes connecting with its serices possible, in much the same way as
1inkerorge`s library makes connecting with its sensors possible.
Beore you can do anything useul with Dropbox, you need to create an
account a ree account is ne,. \ou can then go to hffps://WWW.dopbox.com/
deve1opes/app1y?conf=/deve1opes/apps and, once you`e agreed to the
terms and conditions, click the Create an app` button. 1his might seem a bit
odd, but eery program that wants to connect to Dropbox needs its own unique
ID to identiy it to the serice.
Gie your app a name and leae the Access setting` alue set to lolder. 1his
means that any Dropbox user connecting to your climate-measuring app will see
a new older created in their Dropbox account called apps i one doesn`t already
exist, and, within that, a subolder with the same name as your app. In our case,
we`e chosen to call the app kP1Lab.
On the General inormation` page
or your new app you`ll see alues or
App key` and App secret` - you`ll need
both o these alues or your Python code.
Make sure to keep these priate since they
gie the code ull access. \ou`re now set
up on the Dropbox serer.
1he nal step beore we can start
integrating your app with Dropbox is to
download the Sotware Deelopment
Kit SDK,, which is analogous to the
1inkerorge bindings. 1o do this, head
Make a note of the App key and App
secret - you'll need those for your code
UItimate Guide to Raspberry Pi
139
oer to hffps://WWW.dopbox.com/deve1opes/coe/sdk on your Pi and click
the heading under Download SDK.
Once the SDK has been saely downloaded, right-click the le and select
Xarchier rom the context menu. Lxtract the les to home/p1/dopbox and type
the ollowing into the terminal:
cd /dopbox/dopbox-pyfhon-sdk-1.5.1
Bear in mind that the older name could be slightly dierent i the SDK`s
ersion number has been updated since publication, i the aboe command
doesn`t work, adjust your syntax accordingly. linally, type this into the terminal:
sudo pyfhon sefup.py 1nsfa11 -f
1his uses the easy1nsfa11 library we added earlier to install the necessary
Dropbox les. \e`ll now be able to access all the API unctionality through a
simple import statement.
F|n|sh|ng the c||mate mon|tor
\ou won`t be surprised to learn that we need authorisation rom a Dropbox
user beore connecting to their account to upload the data. 1o handle Dropbox
operations, we`re going to create a new module called up1oad.py with two
unctions: aufhdopbox and savefodopbox.
UItimate Guide to Raspberry Pi

Authorising Dropbox
Assuming you`e installed the Dropbox SDK, you can now import the releant
parts using the fom keyword as shown on line 3. \e`re also going to use the
p1ck1e and os standard libraries.
Dropbox works using , which, or our purposes, you can think o as
being one-o attempts to use the serice. lor each session you need to supply
the application key, its Secret key and the access type appfo1de in almost
eery case,. Dropbox uses these to establish that your application is registered
with them and you, as the coder, are connecting legitimately only you should
know the Secret key,.
Dropbox also needs to know which user`s account you want to connect
to and that you`re authorised to do so. lor this it requires an access token and
secret token: these are dierent or each user and each session, and can only
be generated when you`re actually running the code. Since this isn`t a publicly
distributed app, some security restrictions apply: the Dropbox user must be
either the person who registered the app with Dropbox you, or one o the e
additional accounts you can add on the app details` page.
I you don`t want the user to hae to go through the rigmarole o authorising
your app eery time they run the program, you need to store these tokens to use
again later. Not surprisingly, we`ll be using p1ck1e to do this.
1he rst step is to sae the access inormation into properly named ariables
and create an object sess, that`s an o the Dropbox sess1on class. \e`ll
be using this to connect.
On line 11, we use os.pafh.ex1sfs to check whether conf1g.daf exists -
this being the name we`e gien the le in which we`ll sae the tokens. I it does
exist then the program must hae been run at least once beore, and tokens must
hae been generated already and saed here. I so, we don`t need to do anything
urther at this point.
I the le doesn`t exist then we need to get the user`s authorisation. Gien
that this is a program we`ll be running ourseles, we can use a airly basic
approach to this, i you were creating a commercial app that connects to
Dropbox accounts, you`d need to polish it up a bit.
1he rst step in obtaining authorisation is to create a request token that
identies us to the Dropbox serer. Using this, we create a URL or the user to
isit and authorise our access to their account. \e add a aW1npuf{} statement
to halt execution until they`e done this. Once they hae, then the access token
will be a property o the sess object and we can set a ariable to its alue.
1his ariable is actually a dictionary containing two tokens - the access token
key and the access token secret - and we can then use p1ck1e to sae them to the
conf1g.daf le. laing done this, we can reuse these tokens in uture sessions.
1o connect with a dierent Dropbox account, simply delete conf1g.daf: the
authorisation process will trigger again next time you run the program.
UItimate Guide to Raspberry Pi

Saving to Dropbox
Now that we hae our access credentials and are linked to a user`s account, we`re
ready to sae our data to their Dropbox older on a regular basis. lere`s the code
that handles the actual writing o the le:
It`s important to bear in mind that Dropbox relies on a working network
connection to upload the latest data. I a network error should occur to preent
Dropbox rom connecting to the internet, Python`s deault response will be
to exit the program with an error code, causing monitoring to stop. 1his is
a potential stumbling block or such projects, because once the program is
deployed we`ll want the Raspberry Pi to run remotely, without a keyboard,
monitor or mouse. 1his means that eery time we want to reboot it, we`ll hae to
connect to it oer the network i it`s accessible, and restart the program. I we
weren`t able to do this until hours later, we`d lose a lot o measurements.
lortunately, Python has a built-in mechanism or handling errors using the
fy statement - and its best riend excepf. \hen Python encounters the fy
statement, it knows that i any o the ollowing code produces errors, it shouldn`t
abort the program, but should skip to the excepf statement later on to handle it.
In our case, we`re instructing Python to attempt to upload the data lines 38-
4,. I there`s a problem with the network connect, an lOLo will be generated
and the rst excepf block will run. In this case, it simply prints a message. Any
other error prints some inormation to help us diagnose the problem. Crucially,
in neither case does the program stop, so your data needn`t be lost. As a rule o
thumb, you should always use this technique when conditions you can`t control
directly such as an internet connection`s aailability at any specic moment,
would otherwise cause the program to crash.
UItimate Guide to Raspberry Pi

Let`s walk through the code in our fy block. lirst, we create a new
Dropbox session. \e then open the conf1g.daf le and use p1ck1e to load
in the access token and secret token we saed earlier. \e then assign these
to the sess1on object, giing it all the inormation it needs to connect to the
correct account.
\e`re now able to create an object based on Dropbox`s core class
- DopboxC11enf - which takes our sess1on ariable as its argument, and
we hae the Dropbox API at our command. In this scenario, all we want to
do is upload a specic le to a particular older, but you could build the complete
unctionality into your application i you wanted or example, le browsing,.
On line 45 we open the le and then pass it to the puff11e unction o
the c11enf object:
esponse=c11enf.puff11e{`/`+fhef11e,f,1ue}
1he rst parameter tells Dropbox to upload the le, `f` is a reerence to
the le itsel and the 1ue switch ensures that Dropbox oerwrites the le in the
user`s account. I we didn`t use this it`s Ia1se by deault, then Dropbox would
create a new le each time.
1he esponse ariable contains arious data about the le once it`s been
successully uploaded. On line 4 we simply print it out so we can see, by looking
at the interpreter output, that it`s working.
1he code is now almost complete: all we hae to do now is add a ew lines to
ma1n.py to trigger the Dropbox uploads:
laing imported the up1oad module into ma1n, we add a call to the
authorisation unction in the main loop at line 2.
\e`e decided to upload the data eery 30 minutes in other words, ater
eery second measurement, and this is achieed by line 1. 1his creates a new
eent that will be triggered eery hal an hour in line 8, at which point we run
the savefodopbox unction we just created.
UItimate Guide to Raspberry Pi

linally, we add a line to the savesummay unction o ma1n that causes the
daily summary to be uploaded in one go ater midnight. 1he end result is that
eery 15 minutes measurements are taken and saed to the SD card, eery 30
minutes the latest ersion o this CSV le is uploaded to Dropbox, and then, at
midnight, we calculate the daily aerages, minimums and maximums, add them to
the summary CSV le, sae this locally and upload it.
Dialling into your Raspberry Pi
Our weather station is almost ready to deploy in its nal position. 1he last thing
to do is set up a remote connection to it so we can access the desktop rom
another computer - this means we don`t hae to hae a monitor, keyboard or
mouse connected to the Pi. Beore we disconnect, howeer, we need to know its
network IP address. \hilst this might change when you reconnect it, more oten
than not it will be assigned the same address, so this is a good place to start.
1o nd the current IP address type this in LX1erminal:
1p a
1his will cause a lot o inormation to appear: we`re only interested in the
nal line, beginning 1nef. Specically, you need to write down the numbers that
ollow it. In most cases, the rst three sets o numbers will be 192.168.1, so look
or these and add the nal one-, two- or three-digit number.
linally, we need to install the sotware the Raspberry Pi will run to accept
and manage connections. In LX1erminal, enter the ollowing lines:
sudo apf-gef updafe
sudo apf-gef 1nsfa11 f1ghfvncseve
vncseve :1
\ou`ll be prompted to create a password, which will be truncated to eight
characters: this is the password you`ll use when your computer connects to the
Pi. \ou`ll be asked whether you would like to add a iew only` password: in
most cases, you won`t need one.
\e now need to set this serer to run automatically when the Raspberry Pi
is rebooted in its new location. 1o do this, launch the lile Manager rom the
Raspbian desktop. Click View and then tick the 5hoW h1dden option. \ou should
now see a older called .conf1g in the P1 older. Inside this older, you should
see an aufosfaf directory i it`s not there click lile|Create New|lolder,.
Right-click and select Create New|Blank lile and name it f1ghfvnc.deskfop.
Now, right-click f1ghfvnc.deskfop and open it in Geany. \ou need to add
the ollowing text to the le be careul to include the space beore the colon on
the ourth line,:
UItimate Guide to Raspberry Pi
144
|Deskfop Lnfy]
1ype=App11caf1on
Name=11ghfvNC
Lxec=vncseve :1
5fafupNof1fy=fa1se
\ou should now be able to log in remotely. 1o test this in \indows, go to
WWW.f1ghfvnc.com/doWn1oad.php and select the Installer or \indows` entry
appropriate or your setup. Download the installer, choose the custom` option
and deselect 1ightVNC Serer you only need the 1ightVNC Viewer,. Mac and
Linux users can use a built-in remote client or the Jaa ersion o 1ightVNC
aailable rom the downloads page.
Now launch the 1ightVNC Viewer and type the IP address o the Pi into
the Remote lost` box, ollowing it with :1. 1hen click Connect. \ou`ll be
prompted or the password you chose and, once that`s been entered, you should
see a large window appear with a iew o the Raspbian desktop. Congratulations,
you`e connected your computers together!
\ou can now shut down your Raspberry Pi, remoe the keyboard, mouse
and monitor, and install it in its nal location, henceorth using 1ightVNC
Viewer to control it remotely.
I 1ightVNC Viewer reports that it can`t make the connection, this is
possibly because the Pi`s IP address has changed. In that case you can either
guess by starting at 192.168.1.2 or 192.168.0.2 i your network is set up that
way, and moing upwards until you connect, or you can log into your router and
examine the list o connected deices to nd the IP address.
\hen you`re ready to begin monitoring the climate, load your ma1n.py le
into Geany and run it. 1he rst set o readings should appear quickly, conrming
that the program is working.
What next?
\ou should now start receiing updates
to your Dropbox older eery 30
minutes assuming you`re using the same
update interal as in our example,. 1he
update will appear as a CSV le in your
application older. Make a copy and open
it in your spreadsheet - you should see
your initial readings listed. Remember
to check the ollowing morning or the
summary CSV le. I that`s there too, you
know eerything is working as intended. TightvNC lets you access your Raspberry Pi remotely
UItimate Guide to Raspberry Pi

Calibrate your unit


It`s a good idea to check your readings against those o your local weather
station. 1he Met Oce`s obserations page at WWW.mefoff1ce.gov.uk/
Weafhe/uk/obsevaf1ons will help you nd the station nearest to you. I your
alue or current temperature diers rom the ocial` alue by more than a
degree then you should inestigate whether your box is being oerheated by
direct sunlight or cooled by the wind,. \ou can check or this by waiting or a
sunny day, then plot your temperature data as a graph. \ou should see a airly
smooth, bell-shaped cure as the temperature rises and alls. I you see big jumps
in temperature then it might indicate that the box is warming up too much.
I you hae this problem, try moing the box, shading it or coering it in
aluminium oil to renect the heat away. Otherwise, your readings won`t be alid.
Next steps
\our weather station can be used or long-term studies, but it will start
generating useul data ery quickly, so it makes sense to decide on some short-
term objecties too, to start drawing conclusions sooner rather than later.
Let`s say that you`re interested in the relationship between air pressure
and temperature. Once you hae a week`s worth o data, you can plot graphs
to see how they interrelate. lere`s how to generate your chart in LibreOce,
OpenOce Calc:
1. Make a copy o the CSV le and open it in LibreOce.
2. Select the date column rst, then hold down Ctrl and select the Ag1emp
and AgPressure columns - you should now hae three selected columns.
3. Click Insert,Chart choosing the Points and Lines chart type. Click in the
Smooth Lines checkbox and click linish.
4. \ou`ll notice an immediate problem in the chart: the temperature alues ary
oer a much smaller range than the air pressure alues. 1o x this, right-click
oer the chart and choose Insert,Delete Axes. Now, under Secondary Axes
click next to - this adds another ertical axis on the right-hand side.
5. Right-click oer the temperature line in blue, at the bottom, and select
lormat Data Series. Under Align data series to`, select Secondary \ axis.
1he temperature readings will now be plotted against a much smaller scale.
1o draw any rm conclusions you might want to wait until you hae a larger data
set, so you can compare results in dierent seasons, or example. Ultimately, it`s
up to you what you do with your data - that`s what spreadsheets are or, ater all.
146
1he Raspberry Pi is the perect robot brain`, not least because its diminutie
size makes it easy to slot into all manner o robot bodies` and its lack o
moing parts makes it durable - essential i you`re going to send it where no
droid has gone beore. Unlike your laptop, the Pi is also ery easy to directly
connect to hardware, so it can drie motors or read the alues o sensors. linally,
the Pi can be powered by standard household batteries, making it truly mobile,
the cheaper Model A ariant uses only one-third the power o the Model B,
making it ideal or use in a robotics project.
The Carpet Crawler
In this chapter, we`re going to create a roing robot that you can use to learn
about robotics or carry out real tasks, all or a raction o the cost o buying
a traditional kit. 1he rst step is to decide what we want our robot to do, and
there`s no better inspiration than NASA`s Mars Curiosity roer.
Since it takes up to 48 minutes or a radio signal to complete the round trip
Bu||d a rov|ng robot
Chapter Seven
UItimate Guide to Raspberry Pi

between Larth and Mars, NASA uploads a complete sequence o commands in


one go. 1he robot executes those commands 24 minutes later, one ater the other
and without human inolement. loweer, the robot also senses its enironment
so that i it`s in danger o colliding with a rock, or example, it will alter its course
to aoid it, oerriding the instructions rom ground control.
\e`re setting more modest, and strictly terrestrial, goals or our Carpet
Crawler robot. In our case, mission control will be in the kitchen, while our robot
trundles around the liing room. Just like Curiosity, howeer, Carpet Crawler will
load and execute a series o commands, and our modest mechanoid will be able
to take photographs o its immediate enironment so that its controller you,
can see exactly where it is. Like its illustrious counterpart, it will also use a pan-
and-tilt mechanism to capture a wide iew while stationary. linally, the Carpet
Crawler will include an inrared sensor so that it can react i anyone, or anything,
walks into its eld o iew.
A platorm such as this can be used or all sorts o research and educational
purposes, not to mention that most important pastime o cat photography. It
can be expanded to incorporate more sensors both to record the enironment
around the robot and to help it cope with bumping into objects. lollow this
tutorial through and you`ll hae an excellent general-purpose educational roer -
and, you neer know, perhaps the start o a career or hobby in robotics.
BuiId your robot
Robotics is a practical subject so we`re going to die right in and get building. I`ll
deal with the concepts you need to know as we come to them, so let`s get started.
Note: you can nd a complete parts list, including links to suppliers, at WWW.
p11ab.nef/obof. \ou can choose your own parts, improise or recycle old
bits and pieces - that`s part o the un - but my instructions assume you`re using
the ocial` parts list. \ou`ll also nd all the code used in this chapter at the
URL aboe, along with extra photos, hi-resolution wiring charts and ideo o the
robot in action.
Warning: this project inoles directly connecting your Raspberry Pi to real
hardware. \e`e taken great care to proide detailed instructions on how to do
this saely, but accept no responsibility i you damage your Pi in the process.
Step J: Raspberry Pi
1o prepare the Raspberry Pi, load up an SD card with the latest ersion o
Raspbian, add a \i-li dongle and install Geany ollowing the instructions in
Chapter 1,. Once that`s done, set up the Pi to be used headerless` without
monitor, mouse and keyboard, by ollowing the instructions in the preious
chapter. Beore you begin to build the robot, check that you can access the Pi
using 1ightVNC.
UItimate Guide to Raspberry Pi

\e`re using the Raspberry Pi camera module so, when setting up your Pi, be
sure to select Lnable Camera` option 5, on the kasp1-Conhg screen. \ou can
always relaunch the conguration tool by opening up LX1erminal, typing sudo
asp1-conhg and pressing Lnter.
\ou`ll need a case or your Pi. Choose one made rom a non-brittle
material that includes slots or the GPIO and camera module ribbons see my
recommended choice at WWW.p11ab.nef/obof,.
Step 2: Chassis
I chose the popular and cheap Magician
chassis, which includes two powered
wheels and a caster built into a ramework
that has plenty o mounting points or
bits and pieces. It should be possible
to use most two-wheeled chassis with
this project or, indeed, to repurpose an
old remote-control toy i you`re eeling
particularly adenturous.
lollow the instructions or
download rom hffp://sc1b.me/
mag1c1anchass1s, supplied with the
chassis to start construction, halting ater
step 5 don`t bother with the speed board
holders`,. Skip step 6 and, in step , add
all the spacers except those at the let and right o the cured edge - we`ll need
to be able to access this area later.
Beore you complete construction o the chassis, you need to add some
components to the top layer, this is easier to do beore screwing it into place.
Step 3: GPIO and servos
Use a nut and bolt to secure the bottom part o the Raspberry Pi case to the top
layer o the chassis. \e`re going to use the top o the case to mount the camera
and a GPIO breakout board. 1he Raspberry Pi has 26 GPIO General Purpose
Input Output, pins, many o which you can use to send or receie digital pulses
in the orm o a 5V signal.
Misuse o the GPIO pins is the most likely cause o damage to your Pi, so,
to make misconnections much less likely, we`re going to use a breakout board
that sits on top o the case and connects to the GPIO pins ia a ribbon cable.
My aourite board uses paddle` connectors, into which you push wires and
then push down the paddles to engage: this orms a secure connection that can
be easily released i you want.
1his board comes with our mounting holes, but I suggest using only three
The blue variant of the Magician chassis, as supplied by
Dawn Robotics (www.dawnrobotics.co.ukj
UItimate Guide to Raspberry Pi

and leaing out the one immediately aboe the slot or the camera module. 1his
gies room or the module`s ribbon cable. Place the board on top o the Pi case
and mark the position o the three mounting holes, then drill through the marks
using a 3mm or similar, metal drill bit. Now you can mount the board on brass
or plastic spacers.
\e`re going to mount the camera on the Dagu Pan & 1ilt kit, so we can
moe it independently o the robot chassis. 1his kit contains two identical seros
a specialised orm o motor,, one o which will be mounted on your Pi case.
1o do this, you can either use your imagination or, as I did, careully remoe the
bottom o one o the seros and drill two 3mm holes, a centimetre or so apart.
Pass the nuts that were intended or the battery holder as they hae nat heads,
through the holes and into two o the small brass spacers included as spare
parts` with the robot chassis.
Position the sero alongside the GPIO breakout board and mark where the
spacers rest on the case. Drill 3mm holes in those positions, but don`t mount the
sero at this point. Plug in the ribbon cable to the GPIO pins with the central
Here we see the chassis with case, modules and breadboard in place
UItimate Guide to Raspberry Pi

ridge acing the outer edge, and draw it through the slot on the edge o the case
beore connecting to the breakout board.
Step 4: Motor Driver
1he GPIO pins can only supply a small amount o current - not nearly enough
to drie the robot`s two motors, so we must nd a way that allows the GPIOs to
switch power on and o, but which actually supplies this power rom a separate
source. \hile it`s perectly possible to build a circuit to handle this, it`s more
conenient, and saer, to use a pre-built module. 1he chip at the heart o this
package is the L298N and the modules built around it come in arious orms.
\e`re using the most commonly seen one as detailed in the parts list.
1he motor drier works by allowing the GPIO to indicate when each motor
is enabled and whether it should be turned orward or reerse. lor now, simply
mount the module on the top layer o the robot chassis in ront o the Pi case.
\ou can now attach the top layer to the rest o the robot chassis, pulling
through the wires rom the motors so they come out next to the blue screw
terminals on each side. linally, take the breadboard, peel o the sticky backing
and mount it next to the motor drier module. \our setup should look like the
photo at this stage
Step S: Power
1he Magician chassis comes with a battery pack that takes our AA batteries and
supplies power ia a barrel jack. In our conguration, we`re going to situate this
at the ront, cured end o the chassis. Use good-quality batteries, ideally top-
grade alkaline rechargeables proiding around 2,500mAh, as motors consume a
lot o current. Plus, we`re using those batteries to power both the wheels and the
pan-and-tilt seros, which also use the 6V our battery pack will supply 4 x 1.5V,.
I used a breadboard barrel jack connector that allows me to send the oltage to
the power rail and -e to the ground rail, this makes or a solid connection, but
you could simply strip the wire rom the battery pack and connect it directly to
the rails.
I you`re using the barrel jack connector, place it on the breadboard acing
the ront o the robot. 1he connector has three legs but the one to the side is
purely there to gie extra stability: the back leg is connected to the battery oltage
and the one nearer the ront is ground, so you need to use a small patch wire to
connect the breadboard row o each to the correct rail.
\ou then need to run a cable rom the power rail to the let o the three
screw terminals on the motor drier as seen rom the ront, and a separate cable
rom the ground rail to the middle terminal.
\e now need to connect the motors to the motor drier module. \ou`ll
see two sets o blue double terminals, one on each side. Connect the black
lead o the right-hand motor as seen rom behind, to the top terminal on
UItimate Guide to Raspberry Pi

Breadboards
Breadboards allow you to connect components together without needing
to use a soldering iron. They come in many sizes (we're using a "half-size
version), but they're all essentially a matrix of holes containing spring
mechanisms, enabling them to grip cables and component legs that are
pushed into them, thus connecting them together electrically.
Take a look at the diagram: it shows a close-up of one corner of a
standard breadboard. At the top, you can see two rows in red and blue (the
actual breadboard shows just the blue and red lines). Plugging a battery's
+ve terminal anywhere along a row supplies voltage to the entire row; it's
usually called a "power rail when this is done. Plugging the -ve terminal
into the other row creates a "ground rail along the entire length.
To understand how the rest of the breadboard works, look at the
circuit. You can see that voltage runs from the red horizontal rail through
the orange cable and into the frst hole in row 27, moving in the direction
indicated by the arrows. n contrast to the rails at the top, in this case
voltage fows down the row so it passes into and through the LED, out
the other leg, along row 26 and into the resistor, then across the resistor
and up row 24 into the ground rail. So, whereas the rails are connected
horizontally (when seen from this angle), the rows are only connected
vertically - in other words, there's no connection between rows 27 and 26
unless you create one (by using an LED in this case).
Most breadboards are split into at least two independent regions.
n the case of the half-size breadboard in this project, there's a valley
running up the centre that creates, essentially, two separate breadboards
with their own rails and rows. We're using one side for the motors and
the other for the Pi.
Focus On
UItimate Guide to Raspberry Pi

the let-hand block the one nearest the heatsink,, the red lead to the bottom one.
Now connect the black lead o the let-hand motor to the bottom o the
right-hand terminal block, and the red lead into the nal one nearest the heatsink
on the other side,. Check the diagram to see how it should all look, you can see
that power goes rom the battery into the motor module and out again through
the two terminals to the wheels. I you`e got it right, an LLD should switch on
when you make the nal connection.
\ou also need to separately power the Raspberry Pi, which requires 5V. \ou
can do this in seeral ways, but the simplest is to use a mobile phone battery pack
such as the PowerGen 8400mAh, which will keep your Pi going all day. \ou can
also use standard batteries, but since there`s no combination o 1.5V cells that
equals exactly 5V, you`ll need to add a conerter.
In that case, the best compromise between weight, power and price is
a high-capacity 9 PP3 battery connected to the Pi ia a USB conertor see
the parts list,, which steps down the oltage to a sae leel. Bear in mind,
howeer, that you`ll get only a ew hours` continuous use out o een the
best 9V battery.
The above diagram shows how the breadboard should be wired for power
UItimate Guide to Raspberry Pi

1he power supply or the Pi can sit beneath it on the bottom layer - the
PowerGen 8400mAh ts perectly - and can be connected to the computer ia a
short micro-USB cable.
Step 6: Getting ready to move
\e need one GPIO pin to control each o the our directions let-orward, let-
reerse, right-orward, right-reerse, so begin by pushing a patch wire into the
holes marked P22, P23, P24, P25 on the paddle board - make sure they`re secure.
1he other end o the wire should go into consecutie rows on the
breadboard, starting right next to where it meets the Pi`s case. 1his might be rows
1, 2, 3 and 4 or 30, 29, 28 and 2, depending on which way round you hae your
board. Look at the motor module and you`ll see a row o pins. Put a lead into
each o them and then connect them to the breadboard so that IN1 is in the
same row as P24 - this connects them electrically. IN2 should be connected to
P25, IN3 to P22 and IN4 to P23.
1here`s also a pin on each end i they`re coered by a black jumper,
remoe it,. 1hese pins are labelled LNA and LNB, and they turn each motor
on and o. Use a emale-to-male lead to connect both LNA and LNB to the
same row on the breadboard we want both motors to run at the same speed,.
Now, push one end o a cable into the paddle-board hole labelled MOSI
To get your rover moving, connect your GPlO paddle board to the motor driver
UItimate Guide to Raspberry Pi

this is GPIO10, and the other into the breadboard row containing the LNA and
LNB leads. Connect a wire rom any o the paddle-board ports labelled 5V0` to
the top red power rail.
Important: do NO1 connect this wire to the same power rail as the battery!
Now, run a wire rom any o the GND` holes on the paddle board to the
blue ground rail at the top and, nally, run one more cable to connect the ground
rail o the Pi to the ground rail o the battery. \our wiring should look like the
diagram on p133. Note that I`e let out most o the wiring rom the preious
step to aoid it becoming conusing.
Step 7: Get moving
\ou can nd the code or each step at WWW.p11ab.nef/code. Download the
code or the rst step to a older on your Pi`s desktop called Robot. \ou can
now use 1ightVNC to access the Pi. Run the program rom the command line in
LX1erminal since controlling the GPIO pins requires administratie priileges,
so type the ollowing assuming you`e just started your session,:
cd Deskfop/kobof
sudo pyfhon ma1n.py
\our robot should now moe orwards, backwards, let and right, and
you should see messages appearing in the terminal window as it runs through
each manoeure.
Controlling the GPIO is simple using the RPi.GPIO library. Lssentially, each
o the pins we plan to use is set up to be used either or input to read rom a
sensor, or example, or, as in this case, as output to control motors. Once this
is done, we send a high` alue to the pin to send oltage or a low` alue to
turn it o. lor example, to moe orward, the pins connected to IN1 and IN3
are both set to high. 1o go backwards, IN2 and IN4 are set high. 1o go let, IN1
is set high and IN4 to high so that the let and right wheels rotate in opposite
directions - this causes the robot to spin on the spot.
1o control speed, we use a technique called Pulse \idth Modulation.
Lssentially, this inoles turning the motors on and o many times a second.
In the example code, at lines 51 and 52, we set up the P\M and, once
done, the Pi will pulse the LNA and LNB ports as we`e specied. \ou`ll
see that I`e written a unction that wraps all this up so we can send simple
commands such as go{"foWad",2,6} to tell the robot to go orward or two
seconds at ull speed.
Step 8: Snap happy
1o add photo-taking capabilities, we must rst install the camera module and
then mount it on the pan-and-tilt unit. lollow the instructions to insert the
UItimate Guide to Raspberry Pi

camera`s ribbon cable into the appropriate connector on the Pi and pass it
through the slot beneath the GPIO breakout board.
\ou can capture photos rom within LX1erminal using the raspistill utility,
but Sean Ashton`s PiCam library makes it much simpler to do this rom within
Python. Start by booting up your Raspberry Pi with camera attached, and typing
the ollowing in an LX1erminal window:
sudo apf-gef 1nsfa11 pyfhon-1mag1ng
1his downloads the libraries that PiCam uses to unction. 1o install PiCam
itsel, start up a browser on the Pi, go to hffps://g1fhub.com/ashfons/p1cam
and click the Download ZIP` button.
Open up the le explorer in Raspbian and naigate to the /home/p1/ older
where you should see the ZIP le. Right-click it and select Xarchier`, then
extract the ZIP le to the /home/p1 older. Back at LX1erminal, fype cd /p1/
p1cam-masfe and press Lnter, then install the library by typing:
sudo pyfhon sefup.py 1nsfa11
It`s now time to build the pan-and-tilt mechanism, making sure that the sero
on which you`e mounted the two spacers ends up at the bottom. Once done,
you can screw the pan-and-tilt assembly to the Pi`s case using the two holes you
drilled earlier, and then mount the camera module on it using plastic screws.
Lach sero has three leads that terminate in a emale header, so you`ll need
to put six header pins into the breadboard each on a separate row, on the side
nearest the motor drier modules. Into these you can plug the sero leads - you
Connecting the servos for the pan-and-tilt mechanism is easy: the red cables are power
and the brown cables ground. The orange cables connect to the GPlO paddle board for us
to control the servo positions.
UItimate Guide to Raspberry Pi

could also use stripped cable or, i you preer, remoe the sero connectors
and plug in the bare wires. Now use small cable jumpers to connect the rows
containing the red cables to the battery power rail, and also to connect the rows
containing the dark brown cables to the battery ground rail.
1he third lead is orange - this is the signal` cable that tells the sero
which position to moe to. 1ake another cable and connect - ia the breadboard
- the orange lead o the bottom sero the one responsible or panning the
camera, to the hole labelled P1 on the paddle board. 1he orange lead o the
top sero tilt, should be linked to the hole labelled GPCLK0. 1hat`s it, your
seros are now connected.
\e`re going to use the SeroBlaster library created by Richard lirst
to control the pan and tilt. 1o install it, type the ollowing commands into
LX1erminal, pressing Lnter between each:
sudo apf-gef updafe
sudo apf-gef 1nsfa11 g1f
g1f c1one hffps://g1fhub.com/1chadgh1sf/P181fs.g1f
cd P181fs/5evo81asfe/use
make sevod
sudo chmod 777 sevod
SeroBlaster allows us to use any number between 50 and 250 to
control how ar each sero will turn, with most haing a total range o
around 180 degrees. 1o simpliy matters when it comes to controlling our
robot, we want to use commands such as right`, let`, up` and down`
rather than numbers, so rst work out which alues correspond to which
positions. 1o do this, I`e written a program called sevofesf.py, which you
can download rom WWW.p11ab.nef/code.Download it to the same older as
your ma1n.py and use this command assuming your LX1erminal is still in this
older, to run it:
sudo pyfhon sevofesf.py
\ou`ll be inited to enter alues in pairs separated by a space, with the
tilt rst. So, typing 180 120 would set the tilt sero to 180 and the pan to
120. Lach setup is dierent since it depends on the position o the seros
when you assembled the pan-and-tilt mechanism. I suggest beginning with
the aboe alues as they`ll probably result in the pan,tilt acing ront and
roughly nat - this is your deault position. Lower alues will make the tilt
moe upwards and the pan moe let - by experimenting, you can establish
the alues to use or let, ront and right or the pan direction, and up, nat
and down or tilt.
UItimate Guide to Raspberry Pi

Important: nd the central position ront, nat, rst using sae alues such
as 180 120 then add or subtract in tens rom there to read the extremes. Don`t
start low or high, since it could strain the seros. I you hear the seros whine,
change the alues. 1o end the program, type stop`.
\ou can now download the updated ma1n.py or step 8 rom WWW.p11ab.
nef/code to replace the code rom the preious steps. \ou should also download
sevo.py, which is a class containing most o the code or using the pan and tilt.
Open it in Geany and change the alues in lines 5 and 6 to those or your setup.
Sae and close the le. In the new ma1n.py le, on line 88 you`ll see the sel-
explanatory command sevo.movesevo{"pan","1eff"}.
I`e also added a unction or taking a photo. 1o trigger this, call the
unction: fakephofo{} as on line 90. 1ake a look at all the code rom lines 86 to
103 and you`ll see it`s a complete sequence or moing, positioning the camera,
and taking photos. 1he only thing you need to do beore running the code is
to create a subolder in the Robot directory called Photos`. \ou can now use
sudo pyfhon ma1n.py to watch the robot go through its paces. I you`re using
1ightVNC, you`ll see the photos appear in that older as they`re taken.
Step 9: Sensing movement
Our robot can now be programmed to moe, position its camera and take
a photo. It can`t, as yet, respond to its surroundings. So, we`re going to add
a passie inrared sensor such as those ound in burglar alarms, that will
be triggered when something warm moes in ront o it. 1he sensor listed on
WWW.p11ab.nef/obof is cheap and easy to use: you can mount it on the ront
o your robot with a little Blutack.
1here are three pins on the top. 1he VCC pin connects directly to the
power rail rom the Pi it uses 5V, so don`t plug it into the motor`s power rail,
and the GND pin should be connected to the Pi`s ground rail. \heneer the
A passive infrared sensor will enable the robot to detect and respond to movement
UItimate Guide to Raspberry Pi

sensor detects moement, it outputs oltage on the middle pin, so connect that
to a spare row on your breadboard. Run a cable rom the same row to the hole
marked MISO on the GPIO paddle board.
\ou can now download ma1n.py or Step 9 to oerwrite your existing
le sevo.py is unchanged,. On line 9, you`ll see that we set the PIR_pin as
GPIO 9 this is the MISO pin, and on line 19, we set up the pin or input. 1he
unction at line 85 cycles through a Wh11e loop in case the PIR module had
already been triggered, it continues cycling until the PIR stops sending oltage.
It`s now ready to wait or moement and, as soon as it`s triggered, the unction
exits. 1he result is that the robot will halt execution o the script until something
moes in ront o it. All you need to do is add the unction call as shown at line
108: PIR,.
Run the script as beore and your robot will moe orward then pan and tilt.
It will then wait or moement and, as soon as it`s detected, take a photo and
then go through another sequence o moes.
Step 9: Next steps
Our robot can now lay in wait or passing pets, or human intruders, and take a
picture o the oenders. \ou can edit the ma1n.py le to create any sequence o
commands: it`s easy enough to work out what the parameters are by looking at
the unctions themseles. lor the nal ersion o my robot, I added a buzzer that
sounds when photos are taken or moement is detected, along with an LLD or
giing isual eedback.
I`m using a piezo buzzer because I can then make it sound simply by passing
oltage through it, the sound it makes is similar to the startup beeps o a desktop
PC. Buzzers are cheap and hae only two connections, namely a positie and
ground. 1o make things more exciting, I`m also adding an LLD. \ou can buy one
or pennies - or liberate` one rom an unloed toy or electronic deice.
To receive feedback when the robot is taking actions, we add a buzzer and light
UItimate Guide to Raspberry Pi

1o make it work, connect the positie terminal o the buzzer to a GPIO port
I`m using the one marked CL0, which is GPIO 8, on the breadboard. Naturally,
the other terminal needs to connect to the ground rail, but rather than doing so
with a bit o wire, i you drop the longer leg o the LLD into the same row on
the breadboard as the negatie terminal o the buzzer, and the shorter leg into
the ground rail, you complete the circuit through the LLD. So, when we turn
on the GPIO port using Python, electricity nows through the buzzer making a
noise,, then through the LLD making it light, beore reaching ground. In other
words, by using one Python command, we can control the buzzer and the light.
Once you`e set up the hardware, you can download the code or step 9.
Adding this auditory and isual eedback is simple. On lines 16 and 31, we set
up the GPIO ports we`re going to use. \e then create a new unction rom line
61 to make the buzzer beep: it does this by turning on the power or 0.1 seconds
then o or 0.2. 1he unction accepts a parameter called epeaf, so that we can
make it beep a specic number o times or each purpose. It might beep three
times when it rst boots up, or example, and once when taking a photo.
I also wrote code to read in an external text le containing the robot`s
commands, so they could be edited and uploaded in a text editor rather than
haing to directly alter the Python code as we`e been doing up to this point. 1o
do this, I created a text le called COMMANDS.1X1 and inented my own simple
language or instructing the robot. Direction is controlled by the orward,
backward, let, right commands, each o which has a fo parameter which is the
number o seconds the robot must moe or, and a speed parameter, you may
remember that these are the parameters used in the go unction in our code, so
we won`t need to change that at all.
\e also hae a pan command or controlling the horizontal direction o the
camera using the parameters 1ghf, 1eff, and fonf. Plus, there`s a tilt command
or the ertical direction, which uses up, doWn and af. 1he camera is controlled
with snap and the Wa1f PIR command causes the robot to pause until the
inrared sensor is tripped.
So, in the text le, you can type a sequence o commands such as this:
foWad fo:2.5 speed:6
1eff fo:1 speed:6
Wa1f Plk
pan fonf
f11f af
snap
1hese would make the robot moe orward, then let beore waiting or the
PIR to be triggered. It would then moe the camera to ront and centre beore
taking a photo. 1he beauty o this approach is that you can now easily get the
UItimate Guide to Raspberry Pi

computer to carry out a complete sequence without haing to go into your


Python code at all.
All we hae to do now is read in the text le, extract the commands and, or
each, run the correct unction. 1he code or this begins at line 128 and uses the
and structures to loop through the contents o the le until it`s nished.
1he series o statements then works out what command is on the current line,
extracts any parameters, and runs the appropriate unction. 1he code has been
heaily documented, so you can work out what each line does.
As well as making it possible or a non-coder to control the robot by typing
simple commands into a text le, this approach also makes it easy to add new
unctionality to the robot by writing the Python code and adding a simple text
command to control it. In act, as your robot becomes more sophisticated, you
might want to make your code more object-oriented as we did with the games
earlier in the book.
\hateer you do, hae un. Robotics is one o the most interesting areas o
computing and there`s a particular thrill in watching your creation naigate its way
around your home or oce. Robots may appear to be science-ction, but they`re
becoming progressiely more mainstream and will be used in many aspects o
eeryday and commercial lie. 1he Raspberry Pi makes it possible to experiment
in robotics and create real-world projects or minimal cost. \ho knows, today`s
Pi owner may create tomorrow`s planetary roer.
By editing this text fle, we can make the robot carry out a sequence of commands without
needing to dive into the Python code
UItimate Guide to Raspberry Pi

Robots come in many forms


n this chapter, we've built and
programmed a roving explorer, but
many of the robots in day-to-day use
don't move anywhere.
Robot arms are commonly used
in assembly lines and laboratories
across the world and, whilst the real
thing is expensive, it's possible to
build your own robot arm and control
it with your Raspberry Pi at a very low
cost. Maplin (hffp://b1f.1y/1g9kzZo)
stocks a small, self-assembly robot
arm that's intended to be used with a
Windows PC, but by connecting it to a
Pi we can directly program it to carry out tasks. You can usually buy one of
these robot arms on eBay (search for "Maplin robot arm) for half the retail
price of around 40; just make sure the one you buy is sealed in its box.
Begin by following the instructions to build the arm. Test that it works
using a Windows PC and the software that comes with it. Connect it to your
Raspberry Pi via a powered USB hub and boot into the desktop. We need
to install a few bits of software, so execute these commands in sequence in
LXTerminal:
sudo apf-gef 1nsfa11 pyfhon-p1p
sudo p1p 1nsfa11 pyusb
This installs the USB library that allows us to control the robot arm
using the Python programming language.
You can download some sample code we've created from WWW.p1-
nef/code/obofam to give you a head start. You can then open them
in Geany. Feel free to edit amfesf.py, but don't change kobofAm.
py unless you know what you're doing. To run the script, double-click
LXTerminal and, assuming you've copied the Python fles to a folder
called "robotarm on the desktop, type: sudo pyfhon Deskfop/obofam/
amfesf.py.
The amfesf.py fle contains a sample routine that moves every joint in
the robot. t should be easy enough to see how it moves the arm, so try to
work out how to get it to go through a set of movements and then return to
its original position. Maybe you could program it to stir your tea!
Focus On
U|t|mate Gu|de to Raspberry P|
162
Congratulations! laing made it this ar, you`e acquired the majority o the
skills you`ll need or a career in programming. lrom now on it`s a matter o
broadening your knowledge in the areas that interest you, and then adding the
secret ingredient: practise.
Python can be used or powering websites, creating mobile apps and
programming embedded deices - in act, there are ery ew aspects o
programming that aren`t open to Python deelopers. 1he Raspberry Pi is a
perect companion to the language, and perhaps you`e already thought o how
you can combine the two in all sorts o weird and wonderul ways.
My adice is to start by ocusing on an achieable project that interests you,
and then nd out whether anyone in the marellous Raspberry Pi community
has created something similar. Build something personal to you that makes a real
dierence to your day-to-day lie - perhaps a Pi-powered door-entry system, an
intelligent alarm clock, or a time-lapse photography setup. Or how about building
on the games and projects we'e proided
Always remember, being a good programmer isn`t about memorising the
names o commands and unctions. It isn`t necessarily about late nights slumped
oer a laptop tracking down a particularly naughty bug. It isn`t the presere
o geniuses who dream code, and it certainly isn`t a purely male presere.
Programming is or eeryone. It`s about doing something you loe, it`s the
ultimate creatie pursuit.
Go out there, make something abulous - and don`t orget to tell me all
about it by emailing kev1n.pafne0n11ghfn.nef.

LIABILI1\
\hile eery care was taken during the production o
this MagBook, the publishers cannot be held responsible
or the accuracy o the inormation or any consequences
arising rom it. Dennis Publishing takes no responsibility
or the companies adertising in this MagBook.
1he paper used in this magazine is produced
rom sustainable bre, manuactured with a alid
chain o custody.
ISBN
1-8106-312-5
MAGBOOK
1he MagBook` brand is a trademark o Dennis Publishing Ltd,
30 Cleeland Street, London \11 4JD.
Company registered in Lngland. All material Dennis Publishing
Ltd, licensed by lelden 2014, and may not be reproduced
in whole or part without the consent o the publishers.
Raspberry Pi or Beginners is an independent publication. All
trademarks are the properties o their respectie owners.
Use o logo: approed by the Raspberry Pi loundation
Printed by Polestar Stones,
Banbury, Oxordshire
\RI11LN B\ Kein Partner keinpartnernlightn.net
DLSIGNLD B\ Andrew Bunce andrew_buncetalk21.com
MANAGING LDI1OR Priti Patel
ADVLR1ISING
MAGGBOOK ADVLRISING MANAGLR
Simone Daws 020 90 661
MANAGLMLN1
GROUP MANAGING DIRLC1OR Ian \estwood
MANAGING DIRLC1OR, 1LClNOLOG\ John Garewal
LDI1ORIAL DIRLC1OR, 1LClNOLOG\ 1im Danton
MD Ol ADVLR1ISING Julian Lloyd-Lans
MAGBOOK PUBLISlLR Dharmesh Mistry
NL\S1RADL DIRLC1OR Daid Barker
ClILl OPLRA1ING OllICLR Brett Reynolds
GROUP lINANCL DIRLC1OR Ian Leggett
ClILl LXLCU1IVL James 1ye
ClAIRMAN lelix Dennis
LICLNSING AND RLPRIN1S
Material in this MagBook may not be reproduced in any orm
without written permission. It is aailable or licensing oerseas.
1o license: contact Carlotta Serantoni,
-44 0, 20 90 6550, carlotta_serantonidennis.co.uk
1o syndicate: contact Anj Dosaj-lalai,
-44 2,20 90 6132, anj_dosaj-halaidennis.co.uk
www.magbooks.com

7
.
9
9
kasberry P| o| |e|nne|:
BoughI a Paspberry Pi? TempIed by programming buI
puI off by all Ihe dull Iomes IhaI liIIer Ihe shelves? Cr
perhaps you wanI Io buy a guide IhaI will inspire your
children or grandchildren? Then Ihis guide is for you.
By Ihe end, you'll know:
How Io geI Ihe mosI ouI of a Paspberry Pi
The basic concepIs of programming
How Io wriIe a game, sIep by sIep
How Io build your own roving roboI
using Ihe Pi
Abcut the authcr
Kevn Fartner s a progranner, wrter and
unashaned geek. He's deveoped connerca
appcatons and ganes n around a dozen
anguages, wth Fython as hs current favourte.
Kevn owns nore Faspberry Fs than he'd care to
adnt and sees the F as the nost revoutonary
new conputng devce for nany years.
A reguar contrbutor to FC Fro nagazne, Kevn currenty
wrtes technca artces and a nonthy counn coverng onne
connerce. He's aso the author of "How to set up an onne
busness", avaabe fron www.nagbooks.con.
P
r
a
c
t
ic
a
I
g
u
id
e
tc
t
h
e
r
e
v
c
Iu
t
ic
n
a
r
y

3
0
P
C

You might also like