The MagPi Essentials - Learn To Code With Scratch - Make Simple Games and Applications On Your Raspberry Pi PDF
The MagPi Essentials - Learn To Code With Scratch - Make Simple Games and Applications On Your Raspberry Pi PDF
The MagPi Essentials - Learn To Code With Scratch - Make Simple Games and Applications On Your Raspberry Pi PDF
LEARN TO
CODE WITH
SCRATCH
MAKE SIMPLE GAMES AND APPLICATIONS
ON
YOUR Raspberry Pi
Written by The MagPi Team
THE OFFICIAL
RASPBERRY PI
MAGAZINE SAV
UP T E
25%
O
2
FREE PI ZERO!
Subscribe in print for six or 12 months to receive this stunning free gift
Pricing
Get six issues:
£30 (UK)
£45 (EU)
$69 (USA)
£50 (Rest of World)
Subscribe for a year:
£55 (UK) Other benefits:
£80 (EU) Save up to 25% on the price
$129 (USA) Free delivery to your door
£90 (Rest of World) Exclusive Pi offers & discounts
Direct Debit: £12.99 (UK) (quarterly) Get every issue first (before stores)
How to subscribe:
magpi.cc/Subs1 (UK / ROW) imsnews.com/magpi (USA)
3
WELCOME TO
LEARN TO CODE
WITH SCRATCH
oding doesn’t just have to be about typing
C in line after line of gobbledygook. Created
by the boffins at MIT, Scratch enables
anyone – children and adults alike – to start
programming within minutes, without any prior
knowledge. You simply drag and drop various code
blocks and link them together like jigsaw pieces
to form logical scripts, unobstructed by confusing
jargon and tricky syntax. Even better, Scratch is
included as standard in the Raspbian operating
system for the tiny Raspberry Pi computer. It can
even be used with the Pi’s GPIO pins to interact
with electronic components and sensors.
In this book, we’ll help you start coding with
Scratch, guiding you step by step through the
process of creating all sorts of projects: games,
animations, quizzes, electronics circuits, and more.
It’ll be educational and also a lot of fun.
Phil King
Contributing Editor, The MagPi magazine
EDITORIAL DESIGN
Managing Editor: Russell Barnes Critical Media: criticalmedia.co.uk
[email protected] Head of Design: Dougal Matthews
Contributing Editor: Phil King Designers: Lee Allen, Mike Kay
Sub Editors: Lorna Lynch and Laura Clay
Contributors: Sean McManus, William Bell & Code Club
THE MAGPI SUBSCRIPTIONS
DISTRIBUTION Select Publisher Services Ltd
Seymour Distribution Ltd PO Box 6337, Bournemouth
2 East Poultry Ave, London BH1 9EH | +44 (0)1202 586 848
EC1A 9PT | +44 (0)207 429 4000 magpi.cc/Subs1
In print, this product is made using paper This book is published by Raspberry Pi (Trading) Ltd., Mount Pleasant House, Cambridge, CB3
sourced from sustainable forests and 0RN. The publisher, editor and contributors accept no responsibility in respect of any omissions
the printer operates an environmental or errors relating to goods, products or services referred to or advertised in this product. Except
4 [ management
Chapter One ] which has been
system where otherwise noted, content in this magazine is licensed under a Creative Commons Attribution-
assessed as conforming to ISO 14001. NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0).
[ LEARN TO CODE WITH SCRATCH ]
ESSENTIALS
CONTENTS
45 [ CHAPTER NINE ]
21 [ CHAPTER FOUR ]
MULTIPLE-CHOICE QUIZ
CHATBOT
Create a fun quiz game
An interactive character
49 [ CHAPTER TEN ]
25 [ CHAPTER FIVE ]
ADD A TITLE SCREEN
BOAT RACE
Make professional-looking games
Code an arcade game
54 [ CHAPTER ELEVEN ]
ADD A HIGH SCORE TABLE
Keep players coming back
59 [ CHAPTER TWELVE ]
BUILD A SPACE SHOOTER
Create an impressive 3D game
70 [ CHAPTER THIRTEEN ]
QUICK REFERENCE
A handy guide to blocks and more
[ Don’t
[ Contents
Panic ] 5
ESSENTIALS
ESSENTIALS
[ CHAPTER ONE ]
GET STARTED
WITH SCRATCH
Fancy yourself as Disney or Miyamoto? Whether your
inspiration is Mickey Mouse or Mario, Scratch helps
you to bring your creations to life…
6 [ Chapter One ]
[ LEARN TO CODE WITH SCRATCH ]
Scripts Area: Assemble The Sprite List: Select your sprites The Stage: Watch
your programs here by here, so you can change their scripts or your sprites move
dragging blocks in from costumes. Click the Stage in the Sprite and interact here
the Blocks Palette and List to add scripts to it or change its
joining them together background
Right: Scratch
comes with a
library of sprites
to choose from,
including these
fantasy sprites
8 [ Chapter One ]
[ LEARN
[ LEARNTOTOCODE
CODEWITH
WITHSCRATCH
SCRATCH] ]
Control: Used to describe what happens when, and for making bits
of your program repeat.
Operators: Used for maths, random numbers, and doing things to text.
There are also blocks here for combining the blocks used
in decision making.
>STEP-01
Move 10 steps
When you open Scratch (it’s listed under
Programming in your Start menu), it shows the
Motion blocks in the Blocks Palette. Click the move
10 steps block here and you’ll see the cat move
on the Stage. Each time you click, it only moves
once. That’s because ‘10 steps’ is how far it moves,
and not how many times. You can click on the 10
and type a different number in here to make it go
further or less far with each click. Drag and drop
the move 10 steps block in the Scripts Area.
>STEP-02
Combining blocks
Drag the point in direction 90 block into the
Scripts Area. If you drop it just above the move 10
.01 steps block, they’ll lock together. Look for the white
line that shows they’re about to join before releasing your mouse button. If
[ GET ARTY! ] you click either of the blocks, Scratch will carry out the instructions in order,
Can you add first pointing in direction 90 (facing right) and then moving 10 steps. Click
controls for the Control button above the Blocks Palette. Drag in the when space key
pen up and pen pressed block and join it to the top of your two blocks. Your sprite will move
down so you can
use this program to the right (direction 90) when you press the space bar.
to draw on
the Stage? >STEP-03
Making keyboard controls
Right-click your script and choose Duplicate. Click on an empty space
in the Scripts Area to drop your copied script. Repeat until you have four
identical scripts. Let’s turn them into cursor key controls. Click ‘space’
in the first block to open the menu and choose ‘up arrow’. In the point
in direction block below, click ‘90’ and choose ‘0’ (up). Now when you
press the up arrow, the cat moves up the screen. Edit the other scripts to
add controls for left, right, and down. Listing 1 shows the finished code.
10 [ Chapter One ]
[ LEARN TO CODE WITH SCRATCH ]
ESSENTIALS
[ CHAPTER TWO ]
BOUNCY
HEDGEHOG
Spike the hedgehog loves playing on the trampoline,
but he’s a bit clumsy. Can you move the trampoline
to stop him landing with a bump?
Move the
trampoline left
and right to catch
the hedgehog and
bounce it back up
in the air
>STEP-01
Prepare your artwork
For this Scratch project, you don’t need the cat, so right-click it in the
Sprite List and then choose Delete. To add a new sprite, click the icon
above the Sprite List that shows a folder and a star. Add the trampoline
sprite from the Things folder, then the fantasy11 sprite in the Fantasy
folder. Let’s change the background: click the Stage in the Sprite List
and the Costumes tab changes to a Backgrounds tab. Click the tab and
use the Import button to bring in your choice of background. We’re
using the image atom-playground in the Outdoors folder.
12 [ Chapter Two
One ]
[ LEARN
[ LEARNTOTOCODE
CODEWITH
WITHSCRATCH
SCRATCH] ]
>STEP-02 .01
Adding player controls
Click the trampoline (which should
be Sprite1) in the Sprite List to
select it, and then click the Scripts
tab above the Blocks Palette.
Listing 1 shows the scripts you
need to add to this sprite. Work
your way down them, dragging
the blocks into the Scripts Area
one at a time and joining them up.
Click the white holes in the blocks
and type the right numbers in.
Remember that the colours are a
clue: to find the yellow blocks, click
the yellow Control button above
the Blocks Palette first.
.02
>STEP-03
Set up the hedgehog
Click Sprite2 in the Sprite List
(the hedgehog). Add the script
shown in Listing 2 to it. This puts Below: Right-
click the sprite in
the sprite in the top left when the
the Sprite List to
game begins, and gives the player delete it. Note the
buttons to add a
a chance to spot it before it moves.
sprite above the
cat here too
>STEP-04
Add a repeat loop
We’re going to extend that script
now by adding some more blocks
at the bottom. Listing 3 (overleaf)
shows the entire script, including
the bits you’ve already done.
Click the Control button above
the Blocks Palette. Drag a repeat
until block into the Scripts Area
and join it to your script so far.
[ Bouncy Hedgehog ] 13
ESSENTIALS
Above:
The Operators >STEP-05
blocks include the Make the hedgehog move
block for picking
random numbers, To make the sprite move, add the two Motion blocks shown in Listing 4
and the blocks into the repeat until block in your script. Click the green flag above
for comparing
numbers the Stage to test it so far. You should see the hedgehog go to the top
left, plummet down, and stop when it reaches the bottom.
.03 .04
14 [ Chapter Two
One ]
[ LEARN
[ LEARNTOTOCODE
CODEWITH
WITHSCRATCH
SCRATCH] ]
.05
>STEP-06
Make the trampoline bouncy
We need to make the hedgehog bounce back up again if it touches the
trampoline. Click the Control block and drag an if block into your
script. Be careful with where you put it: it belongs inside your repeat
until bracket, as shown in Listing 5. Click the Sensing button and drag
in a touching block for the diamond hole in your if block. Click the
menu in the touching block to choose Sprite1 (the trampoline). Inside
the bracket of your if block, put a point in direction 90 Motion
block. Instead of putting a number in its hole, this time we’ll use pick
random with values of -45 and 45. You’ll find it in the Operators section
of the Blocks Palette. Now the sprite will point in a random upward
direction (between 45 degrees left and 45 degrees right) if it touches
the trampoline. Finally, add a say block at the end of your script,
outside all the brackets. This is shown when game ends.
[ Bouncy Hedgehog ] 15
ESSENTIALS
ESSENTIALS
THREE ]
[ CHAPTER
LOST IN SPACE Program your own animation of a spaceship heading
for Earth, using a scaling effect to make the ship
smaller as it moves into the distance
16 [ Chapter Three
One ] ]
[ LEARN TO CODE WITH SCRATCH ]
>STEP-01
Prepare your artwork
After deleting the cat (right-click and Delete), it’s time to import a
new stage background and sprites. Let’s begin by creating our space
scene, changing the stage to a field of stars: click Stage in the Sprite
List (bottom right), select the Backgrounds tab (top middle), then
click Import and navigate to ‘stars’ in the Nature folder. Since none
of the sprites used in this project is in the Scratch 1.4 library, you can
download them (magpi.cc/scratch_art). First, let’s import the Earth
and Spaceship sprites: for each, click the star/folder above the Sprite
List, then navigate to the folder where you’ve stored your sprites.
[ Lost in Space ] 17
ESSENTIALS
.01 >STEP-02
Move the spaceship
Click the Spaceship sprite
in the Sprite List to select it, then
click the Scripts tab. Listing 1
shows the script you need to
add to this sprite to make it
move. First, we point it upwards
(point in direction 0)
and tell it to go to x: -150
y: -150, near the bottom-
left corner. After waiting one
second, we use the handy
point towards Motion block to
point it at our Earth sprite. We
then use a repeat loop to keep
moving it towards Earth, two
steps at a time.
Right:
The spaceship
points towards
Earth and
is gradually
moved and
shrunk within a
repeat loop
18 [ Chapter Three
One ] ]
[ LEARN
[ LEARNTOTOCODE
CODEWITH
WITHSCRATCH
SCRATCH] ]
>STEP-03 .02
Scale the ship
To simulate the spaceship moving
further away from us, we need
to gradually reduce its size as it
moves towards Earth. This is easily
achieved by adding a single extra
block to its existing script. Click
the Looks button in the top-left
pane and then drag a change
size by block and drop it just
below your move 2 steps block,
within the repeat loop. Change
the 10 of the change size block
to -0.5. The code should look like
Listing 2. Now, try clicking the
green flag to see your space rocket
hurtle towards Earth, getting
smaller all the time.
>STEP-04 .03
Add a space monkey
Now let’s add a few extra features Below:
In the Paint
to our space scene. For a bit of fun,
Editor, draw an
we’ll add a floating monkey who’s ellipse around
the monkey’s
lost in space. Click on the star/
head to give him
folder icon again and navigate to a space helmet
your Lost in Space sprites folder,
then select Monkey. As with any
sprite, you can adjust its size using
the Grow/Shrink sprite icons
above the stage. Now let’s give our
monkey a space helmet! Select it
in the Sprite List, then click the
Costumes tab and the Edit button.
In the Paint Editor, select the
Ellipse tool, the outline option (on
the right) below the tools, then
[ Lost in Space ] 19
ESSENTIALS
.04 .05
a yellow colour from the palette. Now draw a yellow ellipse around the
monkey’s head for a helmet. To make things more interesting, we’ll make
our monkey spin around by adding the simple looping script in Listing 3.
>STEP-05
Bounce and shine
Finally, we’ll add a shining star and bouncing rock. Import them both
from your Lost In Space sprites folder, then position and scale them on
the stage to your liking. For the star, add the code from Listing 4 (two
repeat loops inside a forever one) to repeatedly scale it up and down
in size. Add the Listing 5 code to the rock to get it moving, including a
special block (as used in chapter 2) to make it bounce off whenever it
reaches the edge of the stage.
>STEP-06
Taking it further
Your animation should look pretty cool by now. Try playing around
with various parameters to see how they affect the speed, movement,
and scaling of the objects. You could also add your own touches, such
as using a change color effect block to give the spaceship a fancy
disco-light effect as it moves!
20 [ Chapter Three
One ] ]
[ LEARN TO CODE WITH SCRATCH ]
ESSENTIALS
[ CHAPTER FOUR ]
[[ High
[ ChatBot
High fliers ]
Fliers 21
ESSENTIALS
The Nano
sprite has four
costumes, which
are alternated to
animate him
>STEP-01
Prepare your artwork
After deleting that cat by right-clicking on it and selecting Delete, it’s
time to import a new stage background and our character sprite. Since
neither of these is in the Scratch 1.4 library, you can download them
(magpi.cc/scratch_art). Let’s choose a new backdrop: click Stage in the
Sprite List (bottom right), select the Backgrounds tab (top middle), then
click Import and navigate to the place in the folder where you’ve stored the
downloaded graphics for this project. Next, click the star/folder icon above
the Sprite List, then navigate to the same folder and import the Nano
sprite. If you click the Costumes tab, you’ll notice that Nano has four of
them; we’ll switch between them to animate our little robot friend.
22 [ Chapter Four
One ]]
[ LEARN
[ LEARNTOTOCODE
CODEWITH
WITHSCRATCH
SCRATCH] ]
>STEP-02
Ask for a name
First, we’ll get our robot to ask
for the user’s name and then use
it in a response. With the Nano
sprite selected, click the Scripts
tab (top middle) and add the code
from Listing 1 (overleaf). Note
that instead of using when green
flag clicked, we’re starting the
program when the Nano sprite is
clicked. He then asks for the user’s
name, which is stored in a variable
called name. First, we need to create
the latter: select Variables from
the top left, then click ‘Make a variable’, ‘For this sprite only’, and enter Above: We create
a variable to
‘name’ in the text field. Untick the name block to stop it showing on the store the user’s
stage. We can now set name to answer (the user’s text input) and then add name and then
repeat it within
it into Nano’s response by using the join Operator block. Make sure you Nano’s speech
put a space after ‘Hi’ to avoid it being joined together with the name.
>STEP-03
Add a question
Next, we’ll add some more blocks
from Listing 2 to the bottom of this
script. After saying ‘hi’ to them,
Nano asks the user it they’re OK.
Again, we use the ask Sensing block
for this, and the name variable to
refer to them by name. We then
use an if…else Control block to
determine Nano’s response based on
the user’s input. If it’s ‘yes’ – which
we test for using the = Operator – we
switch Nano’s costume to happy
nano-c, using the drop-down box on
Above: By switching between four
this Looks block. We also get him to
costumes, we can alter our character’s
say ‘That’s great to hear!’ facial expression
[ ChatBot ] 23
ESSENTIALS
.01 >STEP-04
Else this…
In the else part of the if…else
block, we determine what happens
if the user’s input isn’t ‘yes’. In this
case, we’ll switch Nano’s costume
to the frowning nano-d and get him
to say ‘Oh no!’ Test out this code
with different input to check that
it’s working as expected. Note that
while the user’s text input isn’t
case sensitive, it has to be just ‘yes’,
.02 with nothing added, in order to be
recognised as such.
>STEP-05
Jump up and down
Above:
The Operators Finally, we’ll add another question
blocks include the with ask, using a standard if block
block for picking
random numbers, to make Nano jump up and down
and the blocks or not; add the blocks from Listing 3
for comparing
numbers to the script. We use a repeat loop
to make Nano move repeatedly up
and down for a jumping animation.
To make sure he’s not frowning
from the previous response while
doing so, we switch it to nano-c
before the repeat loop.
>STEP-06
Taking it further
You can alter the example questions
or add any extra ones you want, even
getting Nano to tell a joke. You could
also add extra costumes by copying
and editing them in the Paint Editor,
or even a design a brand new sprite
.03 with various costumes.
24 [ Chapter Four
One ]]
[ LEARN TO CODE WITH SCRATCH ]
ESSENTIALS
[ CHAPTER FIVE ]
BOAT RACE Create your own boat race game,
complete with mouse control, collision
detection, and on-screen timer
[[ High
Boat Race ]
High Fliers
fliers 25
ESSENTIALS
>STEP-01
Prepare your artwork
First, delete the cat! You should then import the two sprites, for the boat
and gate. Since they’re not in the Scratch 1.4 library, you can download
them (magpi.cc/scratch_art). Just click the star/folder icon above the
Sprite List (bottom right), then navigate to the folder where you’ve stored
the downloaded graphics for this project. Import the Boat and Gate sprites.
If you aren’t designing your own course, you can also download and import
our Course backdrop: click Stage in the Sprite List, select the Backgrounds
tab (top middle), then click Import and navigate to the folder.
26 [ Chapter Five
One ]
[ LEARN
[ LEARNTOTOCODE
CODEWITH
WITHSCRATCH
SCRATCH] ]
>STEP-02 .01
Design a course
You could just edit our course.
Alternatively, to create a brand
new one, click on the Stage in the
Sprite List, then the Backgrounds
tab, and Paint. Use the paint .02
bucket tool to fill the canvas with
a blue colour for the water. Then
use a brown colour – which should
be the same as in the Gate sprite
– to draw the walls of the course.
Use a yellow colour to draw some
sand for the finish. Finally, add
some white arrows which will act
as speed boosters. Once this is
done, let’s make our Gate sprite
rotate by adding the simple code
in Listing 1 to its Scripts area.
Left: We used
touching color
Sensing blocks
to detect when
the boat has hit a
hazard, booster,
or the finish
[ Boat Race ] 27
ESSENTIALS
.03
>STEP-03
Controlling the boat
In this game we’ll be controlling the boat with a mouse – using the
code in Listing 2 in the Scripts tab of the Boat sprite. To do this, we
simply point it towards ‘mouse pointer’ and move it 1 step at a time,
within a forever loop. To stop it from moving when near the pointer,
we put the control code in an if block that only tells it to move if the
distance to the pointer is greater than 5. Try out the code and guide the
boat: at the moment, it sails straight through barriers.
>STEP-04
Make it crash!
What we need is some collision detection to check whether the boat has
hit a hazard. Within your forever block, add the code from Listing 3
under your boat control code. Here, we use the touching colour
Sensing block to see if the boat has hit anything brown: click the colour
square to get a dropper tool, then click on a brown part of the course.
When it crashes, we switch the boat’s costume, say ‘Noooooo!’, then
place it back at the start point (in its normal costume).
Let’s add two more if touching color blocks, shown in Listing 4, to
our forever loop. The first checks whether the boat has reached the yellow
beach, which acts as the finish line, and stops the program. The second
detects the white of our booster arrows and moves the boat three steps.
28 [ Chapter Five
One ]
[ LEARN
[ LEARNTOTOCODE
CODEWITH
WITHSCRATCH
SCRATCH] ]
Left: You
can edit the
course in the
Paint Editor or
create a brand
new one
.04
>STEP-05
Boosters and time
To make our game a bit more
exciting, we need a timer. Click
the Stage and add the Listing 5
code to its Scripts area. This sets
the time to zero at the start of the
game, then gradually increases the
time variable in line with real time
– you’ll need to create the latter in
Variables and make sure it’s ticked
so that it’s shown on the stage.
.05
>STEP-06
Taking it further
You could easily add a sound effect
for when the boat crashes, using
a Sound block. You could even add
background music, composing it
using Sound blocks with various
drums, instruments, and notes.
The best time(s) could also be
stored in a variable or list.
[ Boat Race ] 29
ESSENTIALS
ESSENTIALS
[ CHAPTER SIX ]
ADA POETRY
GENERATOR Ada Lovelace unveils the Analytical Engine!
This early computer looks a bit primitive,
but can generate random poems
30 [ Chapter Six
One] ]
[ LEARN TO CODE WITH SCRATCH ]
The poem is
generated by
selecting random
words from lists
>STEP-01
Prepare your artwork
After deleting the cat sprite, as usual, you need to import the sprites
and backdrop. Since they’re not in the Scratch 1.4 library, you can
download them (magpi.cc/scratch_art). As the Poetry backdrop is so
simple – just a grey stripe at the bottom of a white canvas – you could
paint it yourself, or just use ours by importing it from the folder where
you’ve stored the downloaded graphics for this project. The same
goes for the Banner sprite. Otherwise, import each sprite as usual,
by clicking the star/folder icon above the Sprite List.
>STEP-02
Ada says hello
Similar to our ChatBot in chapter 4, we’ll get our Ada sprite –
when clicked – to interact with the user via speech bubbles and
text input, using the say and ask commands. Open the Ada sprite’s
Scripts tab and type in the code from Listing 1 (overleaf). As before,
you’ll need to create a name variable: select the Variables block category
from the top left, then click ‘Make a variable’, ‘For this sprite only’,
and enter ‘name’ in the text field. You should untick the name block
to stop it showing on the stage. We can now set name to answer (the
user’s text input) and then add it into Ada’s response by using the join
Operator block. Make sure you put a space after ‘Hi’ to avoid it being
joined together with the name. After this, we add a block to get Ada to
tell the user to click the computer.
>STEP-03
Computer beeps
Click the Computer sprite and select its Scripts tab. This is where
we’ll add the workings of our poetry generator. To start with, type
in the code from Listing 2 (on page 32). After a block to say ‘Here is
your poem’ and the user’s name, we’ll use a Sound block to make our
computer beep. Our Computer sprite already has the sound for this,
or you can record/import a new one in its Sounds tab. We also add a
repeat loop with two turn blocks to make the computer shake.
32 [ Chapter Six
One] ]
[ LEARN
[ LEARNTOTOCODE
CODEWITH
WITHSCRATCH
SCRATCH] ]
>STEP-04
Create word lists
You can’t make a poem without words. We’ll store ours in four lists:
verbs, adverbs, nouns, and adjectives. Create each of these in
Variables, by clicking the ‘Make a list’ button, then ‘For this sprite
only’, and typing its name. It will then appear on the stage: to add
words to it, click the ‘+’ icon and type them in, one by one. When done,
untick this list block to make it vanish from the stage. We used the
following words for our lists:
>STEP-05
Poetry in motion
Now we have our word lists, we can use them to generate a random
poem each time the computer is clicked by the user. Join the code from
>STEP-06
.02 Taking it further
While we’ve only created short
lists for this example, you could
add lots more words to them
for greater variation in the
random poems created by the
computer. More, and differently
constructed, say blocks can also
be added to make poems longer.
If you’re not keen on blank
verse, why not create lists of
rhyming words?
.03
34 [ Chapter Six
One] ]
[ LEARN TO CODE WITH SCRATCH ]
ESSENTIALS
[ CHAPTER SEVEN ]
LIGHT
AN LED
Scratch can be used with the Pi’s GPIO pins
for physical computing projects. Here,
we’ll hook up a button-activated LED
[ Light
[[ High LED ]
HighanFliers
fliers 35
ESSENTIALS
Need
components or add-on boards. In this first GPIO tutorial, we’ll
be creating a simple circuit with a button that, when pressed, causes
an LED to light up. Take a look at the ‘You’ll Need’ box to see which
>S
olderless
breadboard
electronic components are required; you can buy them separately, but
they’re all in the CamJam EduKit #1 (magpi.cc/1OcXtim).
>L
ED
>3
33Ω resistor >STEP-01
> Push button Connect the LED
> 3× male-to- It’s best to turn the Pi off when building your circuit. The breadboard
female jumper features numbered columns, each comprising five connected holes.
wires Place your LED’s legs in adjacent numbered columns, as shown in the
>M
ale-to-male diagram. Note that the shorter leg of the LED is the negative end; in its
jumper wire
breadboard column, insert one end of the resistor, then place the other
end in the outer row marked ‘–’ (the ground rail). Use a male-to-female
jumper wire to connect another hole in that ground rail to a GND pin on
the Pi. Finally, use a jumper wire to connect a hole in the column of the
LED’s longer (positive) leg to GPIO pin 17.
36 [ Chapter Seven
One ] ]
[ LEARN
[ LEARNTOTOCODE
CODEWITH
WITHSCRATCH
SCRATCH] ]
Above: This
project is simple
to wire up using
a solderless
breadboard
and some
jumper wires
>STEP-02
Configure Scratch GPIO
Before we can use the GPIO pins from Scratch, we need to turn its GPIO
server on. While this can be done from the Edit menu, instead we’ll get
our code to activate it. Under a when green flag clicked block, add
a broadcast Control block, click its arrow, select new/edit, and enter
gpioserveron. We also need to configure GPIO pin 17 as an output
pin (to trigger the LED), so add another broadcast block and change
it to config17out.
>STEP-03 .01
Light the LED
We’ll now test our circuit by using
a loop to make the LED blink. Add
a forever block to the bottom
of your code. Within it, add the
following blocks: broadcast
gpio17on, wait 1 secs,
broadcast gpio17off, and wait
1 secs. Now try running the code
(Listing 1) and your LED should
blink on and off continually.
[ Light an LED ] 37
ESSENTIALS
>STEP-04
Connect the button
We can control our LED by adding a push button. Again, we’d advise
you to turn the Pi off while connecting new components. Add the push
button to the breadboard, with its pins straddling the central groove (as
shown in the diagram). Connect a male-to-female jumper wire from one
pin’s column to GPIO pin 21 on the Pi. Connect a male-to-male jumper
from the other pin (on the same side of the groove) to the ground rail
you’re using for the LED circuit (to share its connection to the GND pin).
>STEP-05
Configure button
Before Scratch can react to your new button, it needs to be told which
pin is its input. Delete the forever loop from your blinking LED code,
by dragging it out of the area. Add another broadcast block with
config21in to configure GPIO pin 21 as an input – see Listing 2. Run and
stop the code. Now, click the
.02 Sensing category in the top-left
pane. Find the sensor value
block and change it to gpio21.
Click its tickbox to show its
value on the stage: whenever
the button is pressed, it should
change from 1 to 0.
.03
38 [ Chapter Seven
One ] ]
[ LEARN
[ LEARNTOTOCODE
CODEWITH
WITHSCRATCH
SCRATCH] ]
>STEP-06
Link to LED
With the button working, it’s time to make it trigger the LED. Add the
code from Listing 3 to the end of yours. Again, we’re using a forever
block for a continual loop. Inside it we add an if…else block. In the if
field, we place an = Operator
block; in its left field, we add .04
gpio21 sensor value, with 1 in
the right field. Underneath, we
insert broadcast gpio17off.
This way, when the button
isn’t pressed, the LED will
be off. Under else, we insert
broadcast gpio17on, to light
the LED when the button is
pressed. Run the code (as in
Listing 4), press that button,
and watch your LED! In the
next chapter, we’ll add more
LEDs to the circuit to make
a pedestrian crossing.
[ Light an LED ] 39
ESSENTIALS
ESSENTIALS
[ CHAPTER EIGHT ]
LED TRAFFIC
LIGHTS
Following on from the previous chapter,
we’ll use three LEDs and a push button to
make a pedestrian crossing
40 [ Chapter Eight
One ] ]
[ LEARN TO CODE WITH SCRATCH ]
A piezo buzzer is
wired up to the
ground rail and
GPIO pin 16, for
our pedestrian
crossing beeps
Each LED is
connected to a
different GPIO
pin, so it can be
triggered during
the traffic light
sequence
Need
components or add-on boards. In this second GPIO tutorial,
we’ll create some traffic lights with a pedestrian crossing using LEDs,
> Solderless a push button, and a buzzer. Again, all the components required are in
breadboard the CamJam EduKit #1 (magpi.cc/1OcXtim).
>3
× LEDs: red,
yellow, and >STEP-01
green Connect the LEDs
>3
× 333Ω It’s best to turn the Pi off when building your circuit. The breadboard
resistors features numbered columns, each comprising five connected holes.
>P
ush button Add the LEDs to it, as shown in the diagram. If you’ve just finished
>P
iezo buzzer chapter 7, you can leave those components, including the red LED,
in place. As before, the shorter (negative) leg of each LED should be
>5
× male-to-
female jumper connected via a resistor to the ‘–’ row (common ground rail), which
wires is wired to a GND pin on the Pi. Each LED’s longer (positive) leg
>2
× male-to- should be connected to the respective GPIO pin via a male-to-female
male jumper jumper cable.
wires
>STEP-02
Configure Scratch GPIO
First, we need to turn on Scratch’s
GPIO server. Under a when
green flag clicked block, add
a broadcast Control block, click
its arrow, select new/edit, and
enter gpioserveron. We also
need to configure our LEDs’ GPIO
pins as outputs, so add three
more broadcast blocks and
change them to config17out,
config23out, and config25out
respectively. While we’re at it,
we’ll configure the pins for the
buzzer (config16out) and button
(config21in) we’ll use later – your
code should look like Listing 1.
Above:
While there’s quite >STEP-03
a jumble of wires, Traffic light sequence
it’s relatively easy
to connect all We’ll now test our circuit by creating a traffic light sequence: red,
the components red/amber, green, amber. Add the code from Listing 2. Here, within
a forever block, are blocks to turn the LEDs on and off in the correct
sequence, waiting a few seconds between each change. Try running it
to check that all the LEDs are connected correctly and working.
.01 >STEP-04
Connect the button
For our pedestrian crossing, we’ll
need a push button. Again, you
can use the one already placed
in chapter 7, which straddles the
central groove of the breadboard
and is connected to the ground
rail and GPIO pin 21. We’ve
already configured it as an output
in step 2; run and stop that code.
42 [ Chapter Eight
One ] ]
[ LEARN
[ LEARNTOTOCODE
CODEWITH
WITHSCRATCH
SCRATCH] ]
Left:
Four
pieces of
code are
used for GPIO
configuration,
light sequence,
.02 button press
Now, click Sensing in the top- detection, and
buzzer beeping
left pane. Find the sensor value
block and change it to gpio21.
Click its tickbox to show its value
on the stage: when the button is
pressed, it’ll change from 1 to 0.
>STEP-05
Stop the lights
We need to get a button press to
cause the traffic lights to stay
on red for a few seconds. Select
Variables from the top-left, then
click ‘Make a variable’ and enter
‘pushed’ in the text field. Add
the code from Listing 3, keeping
it separate from the rest. Using
an if block, this sets pushed to .03
True when the value sensed from
GPIO pin 21 is zero, i.e. when
the button is pressed. Next, we
need to add an if…else block to
our traffic light sequence code,
to stop it when pushed is True.
After moving the light sequence
>STEP-06
Add a buzzer
Finally, we’ll add a piezo buzzer,
connected to the ground rail
(short leg) and GPIO pin 16 (long
leg), to make a beeping noise
when it’s safe to cross the road.
Add the code from Listing 5
as a separate script. This runs
whenever beep is broadcast,
.05 after the button is pressed and
the light sequence ends. It shows
a red light and uses a repeat
loop to turn the buzzer on and off
for a beeping sound. Finally, it
turns off the red LED and resets
the pushed variable to False.
Test out your pedestrian crossing
by pressing the button!
44 [ Chapter Eight
One ] ]
[ LEARN TO CODE WITH SCRATCH ]
ESSENTIALS
[ CHAPTER NINE ]
MULTIPLE-CHOICE
QUIZ
Dazzle your friends with your own
quiz game, containing hundreds
of questions! How many can they
get right in 30 seconds?
[ Multiple-Choice
[[ High Quiz ]
High Fliers
fliers 45
ESSENTIALS
Click to answer;
the answer data
comes from a list
on Wikipedia
You’ll L items to them block by block can take a lot of time and Scratch
Need
code. In this project, you’ll see how you can import (or bring
in) large lists from other places, so you can easily make a quiz game
with hundreds of questions. As you create this game, you can use
> LibreOffice –
if not installed,
your own favourite background and sprites, and arrange them with
open a enough space for the answers to appear. Perhaps you can add your own
terminal and question list? Anything works, as long as each answer only applies to
type sudo
apt-get one question.
install
libreoffice >STEP-01
> List of capitals Gather your data
by size – For this game, you’ll need two text files: one for the questions and one
wki.pe/List_
of_national_
for the answers. We’re going to make a quiz about capital cities, so one
capitals_by_ file will contain a list of capitals, and the other will contain the countries
population they are in, in the same order. Start by finding the list of capital cities by
> Internet access population on Wikipedia. Click and drag over the table to highlight it and
then press CTRL+C to copy it. It’s easier if you highlight from the bottom
up. Be patient when the screen scrolls!
46 [ Chapter Nine
One ]]
[ LEARN
[ LEARNTOTOCODE
CODEWITH
WITHSCRATCH
SCRATCH] ]
>STEP-02 .01
Create your question files
Start LibreOffice Calc and paste in
the table using CTRL+V. Click OK.
This might take a minute or two to
work. Click above your cities column
to highlight it. Press CTRL+C to
copy the column. Open your text
editor, Leafpad, which is in the
Accessories menu. Press CTRL+V to .02
paste. You should now have a text
file containing just capital cities,
each one on a new line. If you have
a heading at the top (the word
‘Capital’), delete it, and remove
any blank lines at the end too. Save
this file as cities.txt. Open a
new file in Leafpad and repeat the
process with the countries column
in LibreOffice Calc. This time, save
your Leafpad file as countries.txt.
>STEP-03
Importing your data into Scratch
Start Scratch. Click the Variables
button and make a list. Call it cities
and make sure it’s for all sprites.
When the empty list appears on the
Stage, right-click it and click import
in the menu. Browse to the files you
just created, and double-click your .03
cities text file. The list on the Stage
will be filled with the cities from your
file. Repeat the process to make a list
called countries and fill it with your
countries file. Your list files should be
the same length. Right-click the list
boxes on the Stage and choose hide.
[ Multiple-Choice Quiz ] 47
ESSENTIALS
>STEP-04
Set up your variables
Through the Variables part of the Blocks Palette, make variables called
question number (used to remember which question/answer pair we’re
asking), score, shuffle choice and temporary storage (used for
shuffling the list of options), and wrong answer (used when making the
list of wrong options). You also need to make a variable called player
guessed to remember which answer the player chooses, and a list called
possible answers. Make all these variables and the list ‘For all sprites’.
>STEP-05
Make the main game code
The main game code uses three scripts (Listings 1-3). Add them all to the
cat sprite. The game uses broadcasts to pass control to the various parts
of the program, including on the same sprite. The ‘ask a question’ section
picks a random question number from the list of countries and makes a
list of possible answers. It includes the correct answer, and two wrong
answers which must be different from the correct answer. The code then
shuffles this list to put the answers in a random order, before using a
broadcast to make the answer sprites appear and show their answers.
.04 >STEP-06
Make the answer sprites
Import a new sprite to use for
showing the answer; we’re using
Gobo. This sprite has five short
scripts (Listing 4). Make the
variable answer choice, but click
the button to make it ‘For this
sprite only’. If the game shows all
the same answers when you run it,
you probably made a mistake here!
When you’ve finished this sprite,
right-click it and duplicate it twice.
In the copies, change the value of
the answer choice variable at the
top to 2 for the first one and 3 for
the second one. Happy quizzing!
48 [ Chapter Nine
One ]]
[ LEARN TO CODE WITH SCRATCH ]
ESSENTIALS
[ CHAPTER TEN ]
ADD A TITLE
SCREEN
To make a professional-looking game,
follow these steps to add a title screen
with instructions and a fun animation
[ Add a [Title
[ High
High fliers ]
Screen
Fliers 49
ESSENTIALS
Add an animated
sprite to your
title screen and
use ‘say’ blocks
to tell players
how it works
book has a cover, a film has its credits, and an album has its
A artwork. Only with the right presentation do these things
feel professional and complete. In the same way, a great
game starts with a title screen that draws players in and provides
instructions. It’s especially important if you want to share your game,
as you won’t be there to explain it when it’s played. In this article,
you’ll see how you can add a title screen to a basic game. The same
techniques will work for most simple games, so why not try adding
a title screen to your own games, too?
>STEP-01
Write your game
We recommend you try adding a title screen to our example game Cat
Catcher before you add one to your own game. To make Cat Catcher,
first bring in the sprite Gravity Marble from the Things folder. It comes
with some scripts for controlling it with the cursor keys. Add Listing 1
to your cat sprite. Together, these two sprites make a game where
you’re challenged to see how quickly you can catch the cat ten times
with the marble. We’ve added the playing field background.
50 [ Chapter Ten
One ]]
[ LEARN
[ LEARNTOTOCODE
CODEWITH
WITHSCRATCH
SCRATCH] ]
.01
.02
>STEP-02
Create your title screen
background
Create a new background image
that you’ll be using for your
game’s title screen. Ours is just
a bright colour with the game
title on it, but you could make
something more elaborate if you
like. On the background, add
the scripts shown in Listing 2.
They change the background
between the title screen and the
in-game background, and tell
all the sprites to go into ‘title
screen’ mode when the green
flag is clicked. Ultimately, this
should be the only time you use a
when green flag clicked script.
.03 >STEP-03
Create your title screen sprite
This is the sprite that will tell the
player how to play, and it can be
animated too. For our game, we’ve
brought in another cat sprite. Add
Listing 3 to it. There are three
parts to this: one part displays the
title animation and instructions;
another part starts the game when
the sprite is clicked; and a third
part hides the sprite when the
game begins. You’ll need to make
a variable called game status,
which all sprites will use to tell
whether the game is running or
the title screen is on. You can add
more sprites to your title screen.
Include the when I receive
play game script from Listing 3 to
hide them when the game begins.
Use a when I receive title
screen script to show them on the
title screen.
>STEP-04
Replace your green flag scripts
Now you need to go through
your game sprites (the game cat
and the marble in our example)
and change their scripts so they
don’t start when the green flag
is clicked anymore. For each sprite and each of its scripts, replace
the block when green flag clicked with the block when I receive
play game. Add Listing 4 to your game sprites to make them hide
when the title screen is on, and appear when the game begins. If
a sprite shouldn’t be there at the start of the game, you can leave
out the show script.
52 [ Chapter Ten
One ]]
[ LEARN
[ LEARNTOTOCODE
CODEWITH
WITHSCRATCH
SCRATCH] ]
.04
>STEP-05
Replace the forever loops
Some of your in-game sprites might have forever loops. These will
keep running even when the title screen is showing and the sprite is
hidden. To avoid this causing unwanted results, replace the forever
block on your in-game sprites with the forever if block. Give the
block the condition game status = game, using your variable game
status and the = Operator block. You might also have events that are
triggered, such as when there’s a key press. To stop these working on
the title screen, wrap an if block around the entire script after the
when [space] key pressed block and give it the condition game
status = game, too.
>STEP-06
Start a new game
When your game finishes, you can show the title screen again by
adding a Control block to broadcast title screen. For example, you
could add it to the end of Listing 1 in our game. Players can once again
start a new game from the title screen. That will keep them in the
game and encourage them to keep playing until they’ve got a score
they can brag about! You might need to make some other tweaks for
your game - each one is different, after all - but following these steps
should enable you to add a title screen to most simple games, to make
them look more polished.
ESSENTIALS
[ CHAPTER ELEVEN ]
ADD A HIGH
SCORE TABLE Keep players coming back for more by keeping
a record of the best scores, and telling them
how they measure up
54 [ Chapter Eleven
One ] ]
[ LEARN TO CODE WITH SCRATCH ]
>STEP-01
Make your game
You’ll need a game to add this script to – either one of your own, or
one that you’ve programmed from a book or magazine. Try playing
the game a few times to work out the likely scores. Some games award
a few points, some hundreds, and some thousands. The starting
numbers in your high score table should present a challenge to players,
but not be completely unachievable. Take care with your own games: if
you’ve spent days playing them in development, they’ll be much easier
for you than anyone else.
.01
>STEP-02
Add your high score sprite
The scripts for the high score can all go on the same sprite.
This sprite will tell players if they got a high score. It could be the
main character of your game, the sprite used on the title screen
>STEP-03
Set up your list
Your high score table will be stored in a list. Click the Variables button
above the Blocks Palette, click the button to make a list, and call it
‘high scores’. In the Blocks Palette, you can click the tickbox beside
the list name to show or hide the list on the Stage. This is a handy
way to view the whole list, and you can edit the values in it by clicking
them and typing on them. The list gets in the way of your game, so we
recommend unticking the box.
56 [ Chapter Eleven
One ] ]
[ LEARN
[ LEARNTOTOCODE
CODEWITH
WITHSCRATCH
SCRATCH] ]
.02
>STEP-04
Set your starting scores
You can type some starting scores into the list on the Stage, but it’s
better to use a script to generate your high scores. Listing 2 does this.
It runs if it receives the broadcast reset high scores, but you can also
click the script once to reset your scores. To change the lowest score,
change the value in the set high score loop block. To change how
much scores go up by, edit the value in the change high score loop
block. Note: the pointed Operator blocks are shown as rounded in our
code because of limitations in the Scratchblocks software we’ve used
for laying out code for this book.
.03
>STEP-05
Add your high score code
Listing 3 checks the score and adds it to the high score table in the
correct position if it’s high enough. It also tells the player how well
they did. Add it to your high score sprite. Take care with building the
script that goes in the hole of the repeat until block. You’ll need to
drag in blocks in a similar order to this: or, >, item 1 of high scores,
high score loop, =, high score loop. When the next highest score is
announced, add blocks in the order: say Hello! for 2 secs, join hello
world, item 1 of high scores, -, high score loop.
>STEP-06
Insert it into your game
To finish, connect your high score script to your game. If the game doesn’t
already use the variable score, click on Variables and make that variable
for all sprites. You want the high score script to run when your game ends,
so you need to add some code at that point in your game. Add a block to
set score to your game’s score variable, if you’re not already using the
variable score in the game. Finally, add a block to broadcast check high
scores. To keep your high scores, simply save your game. When you save
a Scratch program, the list values – including your high score table in this
case – are saved too.
58 [ Chapter Eleven
One ] ]
[ LEARN TO CODE WITH SCRATCH ]
ESSENTIALS
[ CHAPTER TWELVE ]
BUILD A
SPACE
SHOOTER
How to create an impressive 3D space shooter,
using nothing more than Scratch and some
clever coding techniques…
[ Build a Space
[[ High
High fliers ]
Shooter
Fliers 59
ESSENTIALS
60 [ Chapter Twelve
One ] ]
[ LEARN
[ LEARNTOTOCODE
CODEWITH
WITHSCRATCH
SCRATCH] ]
Infinity
Viewing plane
y-axis
x-axis
Perspective
In real life, objects that are far away appear to be smaller. One example
of this is a set of railway tracks. Looking down railway tracks and into
the distance, the tracks appear to become closer together. This can be
applied to a computer game, where objects need to be shown as being
in the distance. When an object becomes closer to a player, the object
should become larger on the screen.
In this game, a one-point perspective is used. This means that distant
objects appear to come from the centre of the screen. Rather than draw
a lot of very small images at the vanishing point, it’s more sensible to
assume a viewing plane. The viewing plane corresponds to the distance at
which objects become visible. The two diagrams – at the top of this page
and overleaf – show the position of the viewing plane, and the vanishing
point as it appears on the screen. In the illustration of the viewing plane,
the z-axis points from the centre of the screen straight towards the player
and is perpendicular to the x-y plane.
y-axis
x-axis
Vanishing point
If the spaceship has no velocity along the x-y plane, and an object
appears at the viewing plane with a position that’s not in the centre of
the screen, then the object appears to have a velocity that’s proportional
to its distance from the centre of the screen. This isn’t a real velocity,
but is the effect of the perspective used to display the z-axis. This effect
can be observed when driving along a straight road: a vehicle that’s on
the other side of the road, but far in the distance, appears to move to the
other side of the road as it approaches.
62 [ Chapter Twelve
One ] ]
[ LEARN
[ LEARNTOTOCODE
CODEWITH
WITHSCRATCH
SCRATCH] ]
Lasers
The lasers were drawn as another
sprite. The size of the Laser
sprite was carefully matched to
the SpaceShip sprite by copying
the SpaceShip costume, to check
where the lasers would appear on
the screen.
When the green flag is pressed,
the Laser sprite is set to appear
just below the SpaceShip sprite
(Listing 4, overleaf). So it’s in
the foreground, but not as close
as the cockpit. The lasers are
fired by pressing the space bar.
To make the game a bit harder,
64 [ Chapter Twelve
One ] ]
[ LEARN
[ LEARNTOTOCODE
CODEWITH
WITHSCRATCH
SCRATCH] ]
Space debris
Two types of space debris were
created: LavaBall and Scrap.
The script for the LavaBall sprite
(Listing 5, overleaf) was copied
and modified slightly for the Scrap
sprite (Listing 6) to prevent both
sprites appearing at exactly the
same time. The two sprites were
also given two costumes, to show
them as being normal or exploded.
When the green flag is pressed, the LavaBall is placed below
the cockpit, shield display, and lasers, then it’s hidden from view.
The main loop continues while the game is being played. When the
SpaceShip sprite switches to the destroyed costume, it finishes the
game by stopping all scripts. This includes the main loops of the space
debris sprites.
To show that it’s in the distance, the LavaBall appears at the viewing
plane at 1% of its normal size. To make the game more interesting, its
starting position is chosen at random in the x-y plane. Due to the one-
point perspective used, objects that are closer to the edge of the screen
will quickly disappear from this location. Therefore, objects were chosen
to appear within a 100 by 100 box around the centre of the screen. The
initial position of the sprite, along the x- and y-axes, is stored in the
initial_x and initial_y variables. Since these variables are only
needed for this sprite, they were created as local variables for this sprite
only. The initial position components are rescaled to produce an apparent
velocity offset associated with the perspective. They are rounded to
.04
integers, since the sprite moves in numbers of pixels. The sprite is then
shown on the screen. Next, the script enters another loop that continues
until the sprite is full-size, has touched the edge of the screen, or has
been hit by the laser beams. The point where the two laser beams meet
was given a pink colour, so that this colour could be used to test if the
laser beams had hit the LavaBall. The relative velocity of the debris
along the z-axis can be raised by increasing the change size by 5 (5%)
command, or by reducing the size of the wait within the motion loop.
In this game, the space debris is spinning but is otherwise stationary
with respect to the rest of the universe. The spaceship is drifting
through the debris field at a constant speed, and starts the game at rest
in the x-y plane. When the spaceship thrusters are fired, the spaceship
moves along the x-y plane with respect to the universe. However, the
game is played from the pilot’s point of view, rather than from the point
of view of the universe or the space debris. Therefore, when the player’s
spaceship is moving to the left, the LavaBall is shown as moving to the
right. If the spaceship moves downwards, then the LavaBall moves
upwards. This can be demonstrated by looking at a cup on a desk: if the
person looking at the cup moves to the left, then the cup moves to the
right with respect to the person’s line of sight. The motion of the sprite
66 [ Chapter Twelve
One ] ]
[ LEARN
[ LEARNTOTOCODE
CODEWITH
WITHSCRATCH
SCRATCH] ]
.05
.06
68 [ Chapter Twelve
One ] ]
[ LEARN
[ LEARNTOTOCODE
CODEWITH
WITHSCRATCH
SCRATCH] ]
is therefore the sum of the relative velocity and the apparent velocity,
due to the object being created at a point on the viewing plane
that’s not in the centre of the screen.
If the LavaBall has been hit by the laser beams, then the score is
incremented and the costume is switched to the exploded version.
The program waits for half a second for the player to view the
exploded sprite. If the LavaBall hasn’t been hit by the lasers and it
hasn’t touched the edge of the screen, then it has hit the spaceship.
If the LavaBall has hit the spaceship, then the number of shield
points is reduced by one and the LavaBall costume is switched to
the exploded version. If the LavaBall has missed the spaceship,
then it disappears behind the spaceship harmlessly. After these logic
conditions, the LavaBall sprite is hidden and reappears somewhere
else on the screen.
Possible extensions
Other features could be added to the game. The spaceship could collect
shield tokens or be able to use a wider laser beam to destroy more than
one object at once. Alternatively, the principles demonstrated within
this program could be used to create a first-person car racing game.
ESSENTIALS
[ CHAPTER THIRTEEN ]
QUICK
REFERENCE To help you get started, here’s a handy
reference guide to Scratch’s interface, GPIO
functionality, and all of its code blocks
70 [ Chapter Thirteen
One ] ]
[ LEARN TO CODE WITH SCRATCH ]
Blocks Palette:
This contains blocks
for programming,
which you drag into
the Scripts Area to
add them to your
code. There are
eight colour-coded
categories, selected
from the top, each
offering a different
selection of blocks.
BLOCK SHAPES
Blocks are shaped according to the way in which they are used.
There are six main types…
[ Quick Reference ] 71
ESSENTIALS
SCRATCH GPIO
Scratch on the Pi now features a GPIO server
for physical computing
72 [ Chapter Thirteen
One ] ]
[ LEARN
[ LEARNTOTOCODE
CODEWITH
WITHSCRATCH
SCRATCH] ]
BLOCK
REFERENCE
GUIDE
A guide to all the blocks in each of the eight colour-coded
categories, including tips for their usage…
Motion
Motion blocks deal with the movement of sprites. They relate mainly
to the x and y position and direction of the sprite.
[ Quick Reference ] 73
ESSENTIALS
74 [ Chapter Thirteen
One ] ]
[ LEARN
[ LEARNTOTOCODE
CODEWITH
WITHSCRATCH
SCRATCH] ]
Looks
Looks blocks are used to control the appearance of sprites and the stage.
Functionalities include changing costumes and applying graphic effects.
[ Quick Reference ] 75
ESSENTIALS
76 [ Chapter Thirteen
One ] ]
[ LEARN
[ LEARNTOTOCODE
CODEWITH
WITHSCRATCH
SCRATCH] ]
Sound
These blocks are related to playing various sounds, which can be
recorded or imported. 128 built-in MIDI instruments are also available.
[ Quick Reference ] 77
ESSENTIALS
78 [ Chapter Thirteen
One ] ]
[ LEARN
[ LEARNTOTOCODE
CODEWITH
WITHSCRATCH
SCRATCH] ]
Pen
Pen blocks enable a sprite to draw lines and shapes,
including its own ‘stamp’ image, on the stage when moved.
[ Quick Reference ] 79
ESSENTIALS
Control
Control blocks provide functions for looping scripts and only running
them if certain conditions are met. The broadcast block can be used
with the Raspberry Pi’s GPIO pins.
80 [ Chapter Thirteen
One ] ]
[ LEARN
[ LEARNTOTOCODE
CODEWITH
WITHSCRATCH
SCRATCH] ]
The equivalent of an if
forever if block within a forever one.
Continually checks whether
condition is true; whenever it is,
it runs the blocks inside.
[ Quick Reference ] 81
ESSENTIALS
82 [ Chapter Thirteen
One ] ]
[ LEARN
[ LEARNTOTOCODE
CODEWITH
WITHSCRATCH
SCRATCH] ]
Sensing
Sensing blocks can be used to detect when one sprite touches another.
The sensor value block can be used to obtain a Pi GPIO pin’s input.
[ Quick Reference ] 83
ESSENTIALS
84 [ Chapter Thirteen
One ] ]
[ LEARN
[ LEARNTOTOCODE
CODEWITH
WITHSCRATCH
SCRATCH] ]
Operators
These provide various mathematical and Boolean operations, along
with functions for handling strings.
[ Quick Reference ] 85
ESSENTIALS
86 [ Chapter Thirteen
One ] ]
[ LEARN
[ LEARNTOTOCODE
CODEWITH
WITHSCRATCH
SCRATCH] ]
Variables
These blocks only appear in the palette once a new variable
(changeable value) or list (containing multiple items) is created.
[ Quick Reference ] 87
ESSENTIALS
88 [ Chapter Thirteen
One ] ]
[ LEARN
[ LEARNTOTOCODE
CODEWITH
WITHSCRATCH
SCRATCH] ]
[ Quick Reference ] 89
ESSENTIALS
ESSENTIALS
LEARN | CODE | MAKE
AVAILABLE NOW:
GET THEM
DIGITALLY:
91
ESSENTIALS
raspberrypi.org/magpi