EXCITED ABOUT
CODING! - AN
INTRODUCTION TO
CODING USING
S C R AT C H 2 S O F T WA R E
O N T H E R A S P B E R RY
PI 4 COMPUTER
Grant Williams
Copyright © 2020 Grant Williams
All rights reserved.
No part of this book may be reproduced, or stored in a retrieval system, or transmitted in any form or
by any means, electronic, mechanical, photocopying, recording, or otherwise, without express written
permission of the publisher.
This book is dedicated to my brother Mark Williams, who showed me
by example that it is possible for one person to have a big impact on
the education of young people around the world. Mark was a prolific
composer and arranger of music for student band and orchestra, and
co-authored the popular music education method book series “Accent
on Achievement” and “Accent on Performance” (Alfred Publishing).
CONTENTS
Title Page
Copyright
Dedication
Chapter 1: The Raspberry Pi Computer & Scratch Software
Chapter 2: Hardware Overview
Chapter 3: User Interface Basics
Chapter 4: Set Up Your Raspberry Pi Hardware
Chapter 5: Set Up Your Raspberry Pi Software
Chapter 6: Customize Your Desktop
Chapter 7: More Raspberry Pi Basics
Chapter 8: Software Development Process
Chapter 9: Project - Quick Draw Cat
Chapter 10: Exercises - Quick Draw Cat
Chapter 11: Project - Paint Pong
Chapter 12: Exercises - Paint Pong
Chapter 13: Project - Rocket Pilot
Chapter 14: Exercises - Rocket Pilot
Chapter 15: Backing Up Your Work
Chapter 16: Exercise Answers
Acknowledgement
About The Author
Chapter 1: The Raspberry Pi
Computer & Scratch Software
Welcome to the exciting world of computer coding!
In our modern world, computers are everywhere. They are contained in an
ever-increasing number of common objects in our lives, including such
things as phones, cars, and airplanes. Learning to write computer code is
fun and it gives you an understanding of how these amazing machines
work. This book is designed to get you coding quickly, with lots of
descriptive pictures included so that you won't get stuck along the way. And
while you are learning how to write computer code (known as “coding”,
“computer programming,” or “programming”), you will be creating
computer games that are fun to play! This is an excellent first book on
computers for kids (ages 9 and up), and is also a great book for a person of
any age who wants to get started learning about computers and coding. This
book makes no assumptions about the readers current knowledge of
computers, and covers all of the basic information that you will need.
Children of ages 9-11 may need some assistance from an adult or older
child in reading this book and doing the coding projects. However the
coding projects have detailed diagrams which guide a student with less
advanced reading abilities through all of the coding steps. For teachers and
parents, this book provides easy-to-follow instructions on how to set up a
low cost and child-friendly computer lab, and provides a foundation for
developing teaching materials, with the option of using this book as the
student’s textbook.
To write code, you need both hardware and software.
The term “hardware” refers to the physical computer (made of plastic,
computer chips, memory cards, electronic circuits, and metal connectors)
that you can hold in your hand. The term “software” refers to the
instructions (also called computer code or programs) that come built-in on
your computer (such as the “operating system” and “pre-installed
applications”), as well as code that you write yourself to do such things as
create a game or control a robot, and optionally any code that you obtain
from another person or company that you install on your computer. In its
simplest form, all software consists of “bits” of information that are
electrically or magnetically set as zeroes and ones on computer hardware.
The hardware that we will be using is the “Raspberry Pi ” computer, which
was originally developed in England at the University of Cambridge's
Computer Laboratory. As a shortcut, I will refer to the Raspberry Pi
computer as “the Pi computer” or simply “the Pi.” The Pi was designed to
be a small, cheap computer that kids could use to begin learning about
computers at an early age. If you want a low cost, easy to set up, and child-
friendly computer for learning computer coding, the Pi is a fantastic choice.
The Pi has become incredibly popular, with world-wide sales totaling over
25 million sold.
The software that we will be using is “Scratch,” which is a computer
program (also referred to as an “application”) that was developed in the
United States at Massachusetts Institute of Technology (MIT). Scratch was
developed as a tool for kids to use to create their own computer programs.
Scratch is used by millions of people around the world, and is considered
the standard for introductory coding classes for children. Scratch comes
preinstalled on the Micro SD memory card that is included in Pi computer
kits.
Create your own computer coding lab.
Pi computers can be purchased at several online stores, such as
Amazon.com and other sellers listed under the “Products” link at the
Raspberry Pi Foundation website (www.raspberrypi.org). I recommend
purchasing a kit that contains all of the components that you will need
including the Pi computer circuit board, Micro SD memory card, power
cord, HDMI cable, heat sinks, and plastic computer case. You can purchase
the individual components separately, but the kits can be a simple (and
often cheaper) way to get all the required parts. (NOTE: Plastic computer
cases come in different colors, but I personally like a clear plastic case,
since it allows you to see the Pi computer circuit board inside, which I think
is kind of cool.) Several companies sell Pi 4 kits online for under $100
(keyboard and mouse not included). Another option is to purchase a
“Raspberry Pi 4 Official Desktop Kit” which includes a keyboard and
mouse (the plastic computer case, keyboard, and mouse are all a matching
red and white color scheme). If you buy a Desktop kit, verify that it
includes the heat sinks.
Figure 1 - Home Computer Coding Lab
To complete your Pi setup, you will also need to get a monitor or TV, a
keyboard and mouse (unless you purchase a Desktop kit), and an electrical
surge protector. Figure 1 shows a home computer coding lab that I set up
for my niece's children. I recycled an old LCD TV and bought a colorful
keyboard and a small-sized mouse (both designed for kids). I also bought a
mousepad with the Raspberry Pi logo. For the lowest cost setup, see if
someone you know has old computer equipment that you can have (monitor
or TV, keyboard, mouse). If that’s not possible, see if you can find a store in
your area that sells used computer equipment, or check sites on the Internet
such as Craigslist. In Chapter 2 “Hardware Overview,” you will find a
complete list of the required equipment.
Scratch software versions – In the summer of 2017, Scratch version 2.0
(or simply called Scratch 2) became available for the Pi. This was a major
update to Scratch, and replaced the older Scratch version 1.4 (shown back
in Figure 1 ). The layout of the main window for Scratch 2 is shown below
in Figure 2 . In this book, you will learn how to use Scratch 2 (The newest
software version, Scratch 3.0 will reportedly be available for the Raspberry
Pi in 2020, and will be the topic of a future book in the “Excited About
Coding!” series).
Figure 2 – Scratch version 2 software
Raspberry Pi computer versions – Figure 3 below lists the models that
will run Scratch 2, and also shows the models that I recommend. The price
difference between the models is not large (between $10 to $20).
Figure 3 - Pi models that run Scratch 2
Chapter 2: Hardware
Overview
The Raspberry Pi is a very small computer, but it is
surprisingly powerful and capable!
One thing that is often not appreciated by today’s computer users is the
fascinating construction of a computer circuit board, with all of the
amazingly small computer chips, electronic components, and associated
connections between chips and components. It is truly an engineering
marvel. In most modern computers (desktops, laptops, tablets, phones), the
circuit board is hidden inside a metal or plastic case. One great thing about
the Raspberry Pi is that you get to see the circuit board up close, and you
are actually involved in assembling the computer. The assembly is not
difficult, but it gives owners of Raspberry Pi computers the feeling that they
participated in building the computer themselves. The assembly steps
include installing the heat sinks on the computer chips, inserting the circuit
board into the plastic case, inserting the Micro SD memory card into the
circuit board, and for some Pi cases, wiring up a cooling fan.
Figure 4 - Raspberry Pi 4 computer circuit board
IMPORTANT : Please wait until Chapter 4 “Set Up Your Raspberry Pi
Hardware” before connecting your equipment together.
Equipment list:
1. Raspberry Pi kit (TIP: Buy a kit that includes ALL of the
following items ).
a. Pi 4 computer circuit board
b. Micro SD memory card preloaded with NOOBS software.
NOOBS stands for “New Out-Of-the-Box Software.”
Verify that your kit includes this card!
c. Cables
i. Power cable
ii. HDMI video cable (with Micro HDMI connector
& Full size HDMI connector)
d. Heat sinks
e. Plastic case (some cases include a cooling fan)
2. TV or monitor (preferably with an HDMI port, or you can use an
HDMI-to-VGA adapter if needed)
3. Keyboard (USB, wired or wireless)
4. Mouse (USB, wired or wireless) & mouse pad
5. Surge protector
6. Headphones or AC-powered speakers (ONLY required if using a
monitor without a built-in speaker)
Figure 5 – Pi 4 external connections
Figure 6 - Data cable types
The Pi's memory card, RAM, and CPU
When you buy a Pi computer as part of a kit, the tiny Micro SD memory
card (let's just call it the “memory card”) will be pre-loaded with the
required operating system (also called “OS”) and application software. The
memory card is the place in your Pi where software (the OS, your
programs, and associated data) is read from when your Pi is powered on.
This kind of memory is referred to as “permanent” or “non-volatile”
memory. Such permanent memory is often referred to as “storage.” The
memory card keeps all of the software permanently stored on it, regardless
of whether the computer is powered on or off. In the Pi computer, the
memory card plays the role that a hard disk or solid state drive does in
larger computers such as the PC or Mac.
Your Pi computer also includes RAM (Random Access Memory), and it is
contained inside one of the large silver or black computer chips on the Pi’s
green circuit board (Figure 7 ). RAM is referred to as “temporary,”
“volatile,” or “working” memory. When you power up your Pi, the OS
software is loaded from your memory card into RAM. Also, when you run a
program, the software for that program is loaded from your memory card
into RAM. RAM has very fast data access speeds, which allows the OS and
your programs to run very fast without any annoying delays. But as implied
above by the names “temporary/volatile/working,” all software disappears
from RAM when your computer is powered off. During your usage of the
Pi computer, you won't need to worry about such details, since the Pi OS
software will take care of managing hardware resources automatically.
In addition to memory, a computer needs a CPU (Central Processing Unit)
to function. The CPU is the “brains” of a computer, executing the OS and
application software. On earlier models of the Pi, the CPU and RAM were
contained in the same computer chip, but the Pi 4 now has separate chips
for the CPU and RAM (Figure 7 ).
Figure 7 - CPU & RAM
Networking
To avoid computing security and parental control issues, we will not be
connecting the Pi to the Internet. We will disable the WIFI and Bluetooth
wireless connections, and will not be connecting an Ethernet cable (wired
connection to the Internet) to our Pi. This is a good configuration for a first
computer for a child or for schools where a simple child-safe computer lab
is desired.
CAUTION: If you decide that you do need to connect your Pi to the
Internet, be sure to implement strong computer security measures
(passwords, firewalls, etc).
Figure 8 - No Internet connection required
Hardware notes
Check TV/monitor connector : Look on the back of your TV or monitor
and verify that it has a port labeled “HDMI.” Most modern TVs and
monitors have a HDMI port, but very old TVs and monitors might not have
one. Using a TV/monitor with an HDMI port is the easiest way to go, but if
you want to use an older monitor that does not have an HDMI port, you can
get a HDMI-to-VGA adapter. However, if you use such an adapter, you will
need to use headphones or AC-powered computer speakers to hear sounds
generated by your Pi.
Surge protector : As with all electronic devices, it is recommended to use a
surge protector. That will protect your equipment from possible damage due
to power spikes that can sometimes occur in building electricity sources.
The following features are recommended for your surge protector:
1. At least two power outlets (one to plug-in the Pi power cord, one to
plug-in the TV/monitor power cord). And if you will be using AC-
powered speakers, then you will want to have three power outlets.
2. ON/OFF switch.
3. “Protected” status light. This light indicates that your surge
protector is working correctly, and will protect your equipment from
any electricity surges. If this light is not lit when the surge protector
switch in ON, then your surge protector is not working correctly,
and it should be replaced.
Figure 9 - Surge protector
Backup device (optional, but recommended)
If you want to safeguard your Scratch projects, you can take the extra step
of saving a copy of your “My Code” folder to a removable USB memory
stick (also called a flash drive or thumb drive). By saving your projects to a
removable memory stick, you will have a backup (i.e. extra) copy from
which you can recover your projects if your Pi ever gets damaged or is lost.
When working with computers in general, it is a good habit to backup your
valuable files to a removable drive periodically. Chapter 15 “Backing Up
Your Work” describes the process for saving your code to a USB memory
stick.
Figure 10 – Backing up your work
Chapter 3: User Interface
Basics
Before we set up the Pi hardware and software, let's review
some of the basics of the Pi user interface.
(If you are already familiar with using a computer, you can skim
through this chapter quickly.)
Computer mouse - A mouse is a plastic handheld “pointing device” that
allows you to select things that you see on the computer monitor or TV
(let's call it the “screen”). When you slide your mouse on a desk or table, an
arrow-shaped pointer moves on the screen. Often a rubber mouse pad is
used on the desk or table to provide a cushioned surface on which to move
the mouse and rest your wrist. Figure 11 shows how moving the mouse on
a mouse pad results in the mouse pointer moving on the screen.
Figure 11 - Using a mouse
Figure 12 shows how you can move the mouse pointer long distances on
the computer screen by sliding the mouse to the edge of the mouse pad,
then lifting the mouse and moving it back to where you started from, and
then continuing to slide the mouse in the same direction.
Figure 12 - Moving the mouse pointer a long distance on the screen
A mouse usually has two buttons (left & right). The mouse operations that
we will use are:
1. Left-click – Press the left mouse button and then quickly release it.
This tells the computer that you want to select the thing on the
screen that the mouse pointer is pointing to. NOTE : If you read
instructions that simply say “click” (without specifying left or
right), a left-click will usually work.
2. Right-click – Press the right mouse button and then quickly release
it. NOTE : In many situations, a right-click will have the exact same
effect as a left-click. But sometimes, a right-click will have a
different behavior, such as displaying a menu (list of things) that
you can then select from.
3. Double click – While holding the mouse steady, quickly press the
left mouse button two times and then release the button. NOTE :
The double click might be hard to learn at first. If you have trouble
double clicking, then use the alternate method of single clicking
(left mouse button) the item to select it and then press the
Enter/Return key.
4. Drag and drop – Some objects on the computer screen can be
copied or moved by placing the mouse pointer on top of the object,
and then holding down the left mouse button while sliding the
mouse on the mouse pad (you will see the object moving on the
screen along with the mouse pointer). When the object reaches the
place on the screen where you want to place it, you take your finger
off the mouse button, and the object will be dropped there.
5. Selecting from a menu – Menus are lists of things. In a restaurant,
a menu is a list of the food and drinks that you can select from.
When working with computers, a menu is often used for selecting
an item from a list. See Figure 13 for a demonstration of how to
select from a “cascading” menu. One definition of the word
“cascade” is “anything that resembles a waterfall.” Cascading
menus have steps that look like a waterfall (especially when there
are many steps).
Figure 13 - Example of using a cascading menu
Computer windows - Just as a house or apartment has four-sided windows
which provide you with a view of the outside world, computer operating
systems have four-sided windows that provide you with a view into some
program or feature of the computer software (Figure 14 ).
Figure 14 - Windows
Just like a window in a house, windows on a computer have frames that
surround the window. The top part of the window frame contains words
which are called the “window title.” When the top part of the window frame
is left-clicked, that window is “selected” and the top of the frame turns a
darker color. Once selected, you can drag the window around by that top
bar, and drop it on the computer desktop wherever you want to put it.
In the upper right corner of the window frame, there are three buttons that
you can left-click to control the state of the window (Figure 15 ). These
buttons are:
1. Minimize (left button) – This button is labeled with “_,” and its
function is to hide the window. NOTE : When a window is created,
a bar labeled with the window's title is added along the top of the Pi
desktop. If the window has been minimized (in other words
“hidden”) and you left-click this bar, then the window is re-opened
to the same position on the desktop that it was when the window
was minimized.
2. Maximize (middle button) – This button is labeled with “r,” and
expands the window to fill up the entire desktop. Left-clicking the
button a second time, returns the window to its prior size.
3. Close (right button) – This button is labeled with “X” and its
function is to close the window.
Figure 15 shows two computer windows and the links to them (at the top of
the Pi desktop).
Figure 15 - Window details
Here are some other window operations that you will find useful:
1. Move – Left-click on the window title bar and drag and drop the
window at a new location (Figure 16 ).
2. Resize – Left-click on the window frame in the lower right corner
and drag and drop the corner to change the window size (Figure 16
).
3. Bring forward – If the window is partially hidden behind another
window and you want to bring the window forward so that it is fully
visible, you can left-click on the title bar of the window.
Figure 16 - Move and resize window
Chapter 4: Set Up Your
Raspberry Pi Hardware
Now let's connect everything, apply power, and see your Pi
come to life!
NOTE: Read and follow the safety instructions that came with your Pi
computer.
Step 1 - Remove the plastic Pi case from its box. If the top and bottom
halves of the case are attached, then separate them. Place the bottom half of
the case on a flat surface. The bottom of the case is usually the thinner of
the two. Pi cases come in various designs, some with more than two pieces,
and some are easier to put together than others. If you have questions, refer
to any instructions that were provided with the case.
Step 2 - Discharge any static electricity from your hands by touching your
fingers to a large metal object, such as a refrigerator. Computer circuit
boards can be damaged by even small electric shocks, so you want to get rid
of any static electricity that you might have on your hands before handling
the Pi circuit board.
Step 3 - Remove the Pi computer (circuit board) from the box or wrapper,
and snap it into the bottom of the plastic case (Figure 17 ). The top of the
circuit board is the side with the Raspberry Pi logo on it.
Figure 17 - Attach Pi circuit board to case bottom
Step 4 - Attach the heat sink blocks to the computer chips on your Pi. If
chips get too hot, they can fail. The heat sink blocks help to transfer heat
from the chips to the air. Remove the paper backing from the heat sink
blocks to expose the sticky side. It’s recommended to check the user manual
that came with your Pi for proper placement, but the typical installation
locations for the Pi 4 are shown in Figure 18 .
Figure 18 - Installing heat sink blocks
Step 5 - The Pi 4 runs hotter than earlier models, so some cases include a
fan to help cool the computer chips. If your Pi case has a built-in fan,
connect the two wires from the fan to the circuit board, as described in the
user manual that came with your Pi case (example wiring for Vilros Pi 4 kit
shown in Figure 19 ).
Figure 19 – Example of fan wiring (Vilros Pi 4 kit)
Step 6 - Attach the top half of the plastic case and snap it into place.
(Figure 20 ). If your Pi case came with rubber feet, peel off the backing
from the feet, and stick them onto the four corners of the case bottom.
Figure 20 - Attach case top
Step 7 – Flip your Pi over, and insert the Micro SD memory card (Figure
21 ). IMPORTANT : Make sure you have the Micro SD memory card
oriented the right way before inserting it into the slot in the bottom of the Pi
(see figure below). NOTE: The large black “adapter card” (shown below)
might not be included in your Pi kit, and that is fine since we will not be
using it.
Figure 21 – Insert Micro SD memory card
Step 8 - Set the power switch on your surge protector to the OFF position.
Plug the surge protector into wall power.
Step 9 -Plug the TV/monitor into the surge protector.
Step 10 – Remove any plastic covers from the ends of the HDMI cable.
Connect the small end of the HDMI cable to the left HDMI port on the Pi
(flat side of the HDMI connector is up) as shown in Figure 22 . Connect the
other end of the HDMI cable to your TV/monitor. NOTE: The other HDMI
port can be used to connect a second TV/monitor to the Pi (not
recommended).
Figure 22 - Connect HDMI cable
Step 11 - Connect the mouse and keyboard to the Pi. (NOTE: USB cables
only fit into USB ports one way. If the cable is not fitting into the connector,
flip it over and try the other side.)
Step 12 - Connect the Pi power cord from the Pi to the surge protector
(Figure 23 ).
Figure 23 - Connect power cord
Step 13 - Apply power to the Pi by turning the surge protector switch to
ON. (NOTE: Some Pi kits come with a power cord that has a built-in power
ON/OFF switch. If you have one of those, then also push in or toggle the
switch on the power cord). The Pi’s red power status light (labeled “PWR”
on the circuit board) should light up (Figure 24 ). If the red light does not
turn on, see the “Troubleshooting” page at the end of this chapter.
Step 14 - Turn on your TV/monitor. You should see a Pi startup screen
which says “NOOBS” at the top. The next chapter will explain what to do
on the startup screen. If you are using a TV and the screen is blank, then
check that the TV’s “source” selection is “HDMI.” If your TV has multiple
HDMI input ports (typically on the back side), then verify that the “source”
matches the correct HDMI port number that your cable is plugged into
(HDMI1, HDMI2, …). For further help with a blank screen, see the
troubleshooting steps on the next page.
Figure 24 - Pi status lights
TROUBLESHOOTING :
1. PROBLEM – Pi’s red PWR (power) status light is OFF
a. CHECK #1 : Some wall power outlets have an ON/OFF
switch on the wall. If you are using such a switched
power outlet, verify that the wall switch is in the ON
position.
b. CHECK #2 : Verify that your surge protector ON/OFF
switch is in the ON position. There should be an indicator
light on the surge protector that shows that power is
switched ON.
c. CHECK #3 : If your Pi power cord has a built-in ON/OFF
switch, make sure that the switch is pushed in or toggled
to the ON position.
d. CHECK #4 : Verify that your Pi’s power cord is plugged
firmly into your Pi on one end, and is plugged firmly into
your surge protector on the two-prong end.
e. CHECK #5 : Confirm that your wall power outlet is
providing electrical power by plugging in some other
device (like a lamp) into the power outlet, and see if that
works properly.
2. PROBLEM - Monitor/TV screen is blank
a. CHECK #1 : Verify that your monitor/TV is plugged in
and powered ON. Most monitors and TVs have a power
status light (red, green, or blue) that is lit when power is
ON.
b. CHECK #2 : Verify that your monitor/TV has “HDMI”
selected as the “source.” A monitor/TV will have controls
(either buttons on the monitor/TV or via a remote control
device) that allow you to select the video source. If there
is more than one HDMI port on your monitor/TV, then
make sure that you have selected the source (e.g. HDMI1,
HDMI2) that corresponds to the port on the back of the
unit that you plugged the cable into.
c. CHECK #3 : If the memory card is not inserted into the
slot in your Pi:
i. Turn OFF Pi power (using the power cord switch
or at the surge protector).
ii. Insert the memory card into your Pi, with the
orientation shown in Figure 21.
iii. Turn ON Pi power.
d. CHECK #4 : If the memory card was inserted into the slot
in your Pi, then it’s possible that the metal contacts on the
memory card are not making a good connection to the Pi.
Try “reseating” the card:
i. Turn OFF Pi power (using the power cord switch
or at the surge protector).
ii. Remove and re-insert the memory card. The card
should snap into place when it has been inserted
properly.
iii. Turn ON Pi power.
e. CHECK #5 : If you have access to another Pi (such as a
classroom with many Pi computers), try using your
memory card in the other Pi, to see if the failure is due to
a bad Pi. If the light is still OFF using a different Pi, then
there is a problem with your memory card. In this case,
use a computer that is connected to the Internet, and
download a fresh version of NOOBS to the memory card
(www.raspberrypi.org/downloads) . To do this, you will
need a USB micro SD memory card reader. If, after
downloading a fresh version of NOOBS onto your
memory card, the light is still OFF, then your memory
card is probably defective, and should be replaced.
3. PROBLEM - Monitor/TV screen is frozen with a rainbow of colors
for more than a minute.
a. CHECK #1 : Turn off your Pi’s power, unplug all of the
cables that are connected to your Pi, firmly plug the
cables back in, and then turn on power.
b. CHECK #2 : Turn off your Pi’s power, remove any static
electricity from our hands (touch a large metal object),
remove the memory card from your Pi, and reinsert the
memory card.
c. CHECK #3 : Follow the instructions for CHECK #5
above to reload your memory card.
Chapter 5: Set Up Your
Raspberry Pi Software
Let’s install and configure the Raspian Operating System
software.
Configuring the software for your Pi computer is very simple. When you
power up your computer for the first time, there are four configuration steps
that you should perform (Figure 25 ).
Figure 25 - Software configuration steps
Select Keyboard Type - At the bottom of the startup screen (Figure 26 ),
there is a pulldown menu that allows you to change the keyboard type.
Since the Pi was developed in England, the default keyboard type is
“English (UK).” If you live in the United States, change the keyboard type
to “English (US”).
Install the Operating System (OS) Software – An operating system is the
software that allows a computer to perform basic functions, such as window
and file management. There are several different types of operating systems
that can run on a Pi computer. The most popular OS is Raspian and it is
officially supported by the Raspberry Pi Foundation. For this book, we will
install the Raspian OS. If you purchased your computer as part of a kit
(includes memory card, power cord and cables), then your micro SD card
will be preloaded with the NOOBS installer software. This software is
activated the first time that you power on your Pi computer, and the
NOOBS startup screen is shown in Figure 26 . Left-click the checkbox to
the left of “Raspian OS” to select it for installation.
Figure 26 - Pi startup screen
After left-clicking the Install icon, you will be asked to confirm that you
want to proceed with the OS installation. Left-click the “Yes” button
(Figure 27 ).
Figure 27 - Confirm that you want to install OS
An installation status window is displayed. This status window has a
“progress bar” at the bottom that fills in with color as the installation
proceeds. It will take up to 20 minutes for the OS to be installed. When the
installation is complete, you will see a completion message window appear
(shown on the right side of Figure 28 ). NOTE: Even if the progress bar
shows 100% complete, please wait until you see the completion message
window that says “OS(es) Installed Successfully.” Then left-click the OK
button to continue.
Figure 28 - OS installation status window & completion message
Next, your Pi will initialize the “desktop” software. This process takes
about one minute. Left-click the “Next” button when you see a window that
says “Welcome to the Raspberry Pi Desktop” (Figure 29 ).
Figure 29 – Desktop “Welcome Screen”
A window will appear that allows you to set your country, language, and
timezone. Select your country and language. You don’t need to set the
timezone because we will not be using the clock (which is set from the
Internet), and we will remove it from the desktop during the desktop
configuration steps. We are not going to use the clock because it requires an
Internet connection.
Figure 30 - Set country
Next, select a strong password for your Pi. To create a strong password, use
at least 12 characters, and include upper and lower case letters, numbers,
and special characters (such as ! @ # $ *). Write down the password so that
you don’t forget it. After typing your new password a second time to
confirm it, left-click the “Next” button (Figure 31 ).
Figure 31 - Change password
Since we are not connecting our Pi to the Internet, click the Skip button on
the “Select WiFi Network” window.
Figure 32 - Skip WiFi Network selection
You can skip checking for Raspian OS updates, since the Pi will not be
connected to the Internet. Finally, as the last step in the installation process,
left-click the “Restart” button (Figure 33 ).
Figure 33 –Skip software update and restart Pi
Turn Off Bluetooth & Remove Control – Along with not connecting your
Pi to the Internet, turning off the Bluetooth wireless connection locks
another network access door to your Pi to keep hackers out. We will also
remove the control from the desktop. CAUTION : Skip this step and
leave Bluetooth ON if you are using a wireless keyboard and mouse
that use Bluetooth to communicate with the computer . Your wireless
keyboard and mouse do NOT require Bluetooth if they came with a small ¾
inch USB plug (called a “dongle”). That dongle (when plugged into your
Pi) provides a non-Bluetooth wireless connection to your keyboard and
mouse, and is not affected if you turn off your Pi’s Bluetooth.
Figure 34 - Disable Bluetooth
Remove WiFi Connection Control – Since we are not connecting our Pi to
the Internet, we will remove the WiFi connection control feature from the
desktop.
Figure 35 – Remove WiFi control
Fan Test – If your Pi case has a built-in cooling fan, put your hand above
the fan and see if it is blowing air. If you don’t feel any air moving, it’s
possible that you didn’t connect the two wires from the fan to the correct
GPIO pins on the Pi. IMPORTANT : Don’t make any wiring changes
unless your Pi is powered off. If your fan is not working, see the
instructions in Chapter 7 (“More Raspberry Pi Basics”) on how to shutdown
your Pi. After shutting down your Pi, turn off power, and verify that the fan
wires are firmly connected and are attached to the correct pins. Refer to the
user manual that came with your Pi to verify that you have used the
recommended wiring. After checking the wiring, apply power, and check
again to verify that the fan is blowing air.
Figure 36 – Fan test
Chapter 6: Customize Your
Desktop
Let’s customize the desktop to make it simpler and easier to
use.
The word “desktop” is used to refer to this main computer screen because it
is similar to the top of a desk in a home or business, where you have placed
out some commonly used items that help you get your work done. You will
see the Pi desktop every time that you power on your Pi. It takes the Pi
about 10 seconds to “boot up” to the desktop screen after you turn on
power.
In this chapter we will customize the desktop so that your Pi is easier to use.
Figure 37 shows the default desktop (left) and the desktop after our
customizations (right). The most noticeable change is the replacement of
the desktop photo with the Raspberry Pi logo picture. Even though photos
can be attractive on a computer desktop, they can also make it harder to
read text items on the desktop due to the mix of different colors in a photo.
A solid color background, like the light gray background of the Raspberry
Pi logo picture provides a nice consistent background for text labels on the
desktop. Other desktop changes that we will make include changing the text
color to black (for good contrast), adding a folder on the desktop for your
code, creating a clickable shortcut to the Scratch program, and removing
items on the desktop that will not be used in this book.
Figure 37 –Desktop customization
Remove the Web Browser from the task bar – Since we will not be using
the Internet, we will remove the Web Browser icon from the Task Bar.
Figure 38 - Remove Web Browser from task bar
Remove the Terminal from the task bar – A terminal window allows the
user to send text-based commands to the Pi. We will not be using that
window, so we will remove the terminal icon from the Task Bar.
Figure 39 - Remove Terminal from task bar
Select Desktop Picture and Text Color – The Raspian OS has a default
desktop picture, but you can choose a different picture. The steps to change
the desktop picture and text color are shown below in Figure 40 , Figure
41 , Figure 42 , and Figure 43 . I recommend selecting the picture
“raspberry-pi-logo” for the desktop. After selecting that picture, we will
change the text color to black (default is gray) to make it easy to read (best
contrast).
Figure 40 – Changing the desktop picture
Figure 41 –Changing the desktop picture (continued)
Figure 42 – Changing the desktop text color
Figure 43 - Updated desktop picture and text color
Create Code Folder – A folder is a container in your SD card memory
where you can store files and other folders. The computer “icon” (small
picture on the screen) for a folder looks like a paper folder. Folders are
important for organizing your work, allowing you to find the files that you
have created in the past. Figure 44 shows some of the high-level folders on
your Pi. The folders are ordered in a “hierarchy,” with the “Pi” folder at the
top of the hierarchy. The lines on the hierarchy diagram show which folders
are contained inside other folders. In the folder hierarchy, the Desktop is a
folder, and it is contained inside the Pi folder. Initially, the Desktop folder is
empty. Any files and folders that you add to your Desktop folder will show
up as individual icons on the desktop screen when your Pi boots up. For
easy access to your Scratch code projects, we will create a “My Code”
folder on your desktop. The steps are shown in Figure 45 .
Figure 44 – Your SD memory card is organized into folders
Figure 45 - Create “My Code” folder on desktop
Create Scratch Shortcut – For fast startup of your Scratch software, create
a clickable shortcut icon on your Pi desktop. The steps are shown in Figure
46 . IMPORTANT : In Step 3, right-click the “Scratch 2” menu item, not
the “Scratch” menu item (without the “2”). Clicking the “Scratch” menu
item would create a link to the older software version, Scratch 1.4.
NOTE: If the shortcut that is created looks different than the Scratch Cat
icon shown in Figure 46 , then perform a Pi reboot as described in Chapter
7 “More Raspberry Pi Basics”, and see if that fixes it.
Figure 46 - Create Scratch 2 shortcut on desktop
Remove the clock – The Raspberry Pi does not have an internal time clock.
Since we are not going to connect the Pi to the Internet, there is not an
external time source available to keep the desktop’s clock updated. So
rather than leaving an incorrect clock on our desktop, we will remove it.
Right-click the clock in the upper right corner of the desktop. In the popup
menu, left-click “Remove Digital Clock from Panel.”
Figure 47 - Remove clock from desktop
Chapter 7: More Raspberry Pi
Basics
Here are a few more Pi basics that you should know about
before we get ready to start coding.
Shutdown – You should always perform a shutdown before removing
power from your Pi. The shutdown steps are shown in Figure 48 . If you
power off your Pi without first performing a shutdown, your Pi’s software
might get damaged and you might lose some of the files that you have
created. After commanding a shutdown, wait until the screen goes blank
before turning off the Pi’s power.
Figure 48 – Shutdown
As you may have noticed, your Pi does not have its own ON/OFF power
switch. Power can be removed from your Pi in the any of following ways
(with the best methods listed first):
1. If your Pi’s power cord has an ON/OFF switch (button or toggle),
use that switch to turn it OFF .
2. Turn your surge protector’s power switch to the OFF position.
3. Unplug the surge protector from the wall outlet.
4. Unplug the Pi’s power cord from the surge protector. NOTE: It is
not good to disconnect the power cord end that plugs directly into
the Pi while power is on. You can get a spark that jumps from the
power cord to the Pi, which may damage the Pi’s circuits or
computer chips.
Reboot – A reboot performs a shutdown, followed by an automatic restart
of your Pi. The reboot steps are shown in Figure 49 .
If your Pi is having unexplained problems, you should try rebooting your Pi
software to see if that helps.
If the problem is not resolved by a reboot, then the next thing to try is to
command a shutdown (as shown earlier in Figure 48 ), then after the screen
goes blank, turn off Pi power, and then turn Pi power back on.
Figure 49 - Reboot
Recovering from mouse or keyboard problems – If you run into a
problem where your mouse or keyboard had been working properly, and
then one or both suddenly stop working, try the following possible fixes:
1. Verify that the USB cables from your mouse and keyboard are
firmly plugged into your Pi.
2. Disconnect the USB cable for the item that is not working (mouse
or keyboard), wait a few seconds, and then plug it back into your Pi.
There a four USB ports on your Pi that you can try using.
3. If your keyboard is having a problem, but your mouse is still
working, perform a shutdown and restart as described at the
beginning of this chapter.
4. If you are using Scratch and your mouse clicks stop working, try
hitting the “Esc” key on the upper left corner of your keyboard.
5. If all other attempts to fix the problem have failed, then restart your
Pi by switching its power off, wait a few seconds, and then turn
power back on. This is the only situation where directly powering
off your Pi is recommended without first performing a shutdown.
6. If none of the above fixes resolve the problem, then try using the
mouse or keyboard on another computer to see if the device has
failed.
Recovering from a frozen “rainbow screen” – As mentioned earlier in the
Troubleshooting section, if your Pi gets stuck for more than one minute
during the booting process with a screen that looks like a multi-colored
rainbow, it could be due to a bad connection of a cable to the Pi. To attempt
to fix that problem, turn off your Pi’s power, unplug and firmly plug-in all
of the cables that are connected to your Pi, and then turn on power. If that
doesn’t solve the problem, turn off Pi power and check that the memory
card is inserted fully.
Chapter 8: Software
Development Process
Coming up with an idea and turning that idea into something
real is very rewarding .
In this book, you will get an introduction to the process that is used by
software developers around the world to create a wide range of things
including computer games, smart phone apps, and software that controls
airplanes in flight.
Before we jump into coding our first project, let’s briefly review the process
that we will be using. As shown in Figure 50 , the four main development
steps (Define Requirement, Design, Code, Test) can be divided into two
groups. It’s a good comparison to think of coding in Scratch as being
similar to building something with Lego blocks. Before you start attaching
Lego blocks together, you come up with an idea in your head of what type
of object you want to build, and you might also think about some of the
details of how you are going to build it. These initial “thought” steps in the
software development process are “Define Requirements” and “Design.”
After completing those steps, you will be ready to start writing your code
(connecting Scratch blocks) and testing it.
Figure 50 – From ideas to computer code
Step definitions:
1. Define Requirements – Before you can start building a software
project, you need to decide what the software is going to do. This
“What does it need to do? ” information is written down as
“software requirements.” These are often written as a set of
numbered paragraphs in a text document. In some situations it is
more important to write down detailed requirements before you
start building your software. If you are going to be selling your
software to a customer, then a document containing the software
requirements can become an important part of the contract between
the software developer and the software purchaser. In a school
setting, the requirements for a coding assignment might be provided
by your teacher. If you are working on a software project just for
fun at home, then you might decide to skip writing down (also
called “documenting”) the requirements and just start writing code,
with the requirements just residing in your head.
2. Design – In the design step, you create a basic (“high-level”)
outline that shows how your computer code will be organized. For
small programs, you may choose to skip documenting your design,
and just jump into coding your program. But for larger programs,
documenting your design is very helpful because it allows you to
organize your thoughts at a simpler level before getting tangled up
in the code details. You can think of creating a software design as
being similar to how an architect creates a blueprint for a building
before having the construction workers assemble the structure.
3. Code – Computer code is written in a “programming language”
(which in our case is Scratch) and is a set of instructions that tells a
computer what you want it to do. A collection of computer code is
called a computer program (or project), and in this book we will be
writing computer programs that are games.
4. Test - Run your program on a computer, and...
a. Find any software problems (i.e. “bugs”).
b. Think about how existing features might be improved.
c. Think about new features that you may want to add.
d. Think about removing features that aren’t really needed
or cause problems.
One fun thing about building computer games is that during the
process of testing your software, you will be playing your game.
Initially, when you don’t have a lot of code in your program, it
won’t feel like you are playing, but as your code becomes more
complete, you will basically be playing the game as you test it.
While coding, you can run tests as often as you want to prove that your
code is working correctly. It feels good to run a test and see that your code
does exactly what you expected. But, of course, your code will often have
problems that are apparent when you run a test. Or you might not find a
problem, but when you see how your code works, you may think of an
improvement that you can make. The arrow back from “Test” to “Code” in
Figure 50 and Figure 51 represents the process of running a test, and then
either finding a problem or identifying an improvement, and then updating
your code.
It is helpful to frequently run tests as you add new sections of code. This
will give you confidence that the code that you are writing is correct as you
write it, and will narrow down the possible parts of the code that are
causing you problems.
Figure 51 – Pi 4 hardware mapped to Code, Test, and Save
In Figure 51 , there is an arrow from the “Test” step to a “Save” location.
This represents the step where you have run a successful test, and you want
to save your code. While you are writing code, your work is being stored in
your Pi’s RAM (temporary computer memory). But everything that is
stored in RAM is erased when your Pi is powered off, so when you have
run a successful test of your code, it’s a good time to save it to permanent
memory (your Pi’s micro SD card). When you follow these coding steps, if
you suddenly find that you have introduced a bug in your program by
adding new code, and if you are having difficulty fixing the problem, you
will have the option of simply closing the Scratch application, and selecting
“Don't Save” when asked if you want to save your project. Then you can
reopen your Scratch project and start over from the time when you last
saved it. This is not something that would happen very often, but it is nice
to have the option to discard recent changes and restart at a point where
your software was last working well. In the next chapter, we will learn the
details of how to save Scratch projects.
Chapter 9: Project - Quick
Draw Cat
Now let’s start coding our first Scratch project!
REQUIREMENTS (“What does the code need to do?”):
1. The player will click the green flag to start the game. This is the
standard way to start a Scratch program.
2. The player will use the arrow keys (up, down, left, right) to
control the movement of a cat who walks around the screen. Each
time an arrow key is pressed, the cat will move a small distance.
3. As the cat walks, it will leave a colored trail behind.
4. The trail will be a different color depending on the direction of
travel (up/blue, down/green, left/yellow, right/red).
5. As the cat moves, it will appear to be walking (legs move).
DESIGN (“How will your code be organized?”):
1. When the green flag is clicked:
a. Place the cat at the center of the screen.
b. Erase any pen markings on the screen.
c. The cat makes a “meow” sound, and a popup balloon
displays the text “Hello.”
NOTE: This is not listed in the software requirements, but it’s
just a fun little feature that we can add!
2. When the right arrow key is pressed:
a. Set the pen color to red.
b. Set the pen down (ready to draw a line when the cat
moves).
c. Move the cat 10 steps to the right.
d. Lift the pen up.
3. When the left arrow key is pressed:
a. Set the pen color to yellow.
b. Set the pen down.
c. Move the cat 10 steps to the left.
d. Lift the pen up.
4. When the up arrow key is pressed:
a. Set pen color to blue.
b. Set the pen down.
c. Move the cat 10 steps in the up direction.
d. Lift the pen up.
5. When the down arrow key is pressed:
a. Set pen color to green.
b. Set the pen down.
c. Move the cat 10 steps in the down direction.
d. Lift the pen up.
CODE & TEST : Start the Scratch program by double-clicking the
shortcut on your desktop. The first thing that we want to do is to give
ourselves the largest possible view of our coding area. As shown in
Figure 52 below, we do this by shrinking the stage (the game area in the
upper left corner of Scratch window) down to its smallest size. Left-click
the little gray triangle in the lower right corner of the stage. Notice that left-
clicking the gray triangle many times will alternately shrink and expand the
stage size. Try that.
Figure 52 – Expand the coding area
When you create large programs, you might like even more workspace for
your coding. In the lower right corner of the coding area, there are zoom
controls that shrink and expand the size of your code blocks.
Figure 53 – Zooming the coding area
In the top center section of the Scratch window, you will see the “block
palette” (Figure 54 ). For an artist, a palette is a board with different colors
of paint on it. In Scratch, the block categories are each a different color. You
can change the block category that you want to work with by left-clicking
on a category (like Motion, Looks, or Pen) on the palette.
Figure 54 – Block palette
The categories of blocks are:
1. Motion – Control the position and movement of your sprite (the
sprite in this project is a cat).
2. Looks – Change the looks of your sprite (size, color, costumes,
show/hide).
3. Sound – Play sounds and control volume.
4. Pen – Control the pen to draw colored lines on the stage.
5. Data – Create and update named variables that contain number
values (such as “Score = 101”).
6. Events – Trigger your code to execute when events happen such as
clicking objects and pressing keys.
7. Control – Code that controls the pathways that your code follows
(wait, repeat, if, else, forever loop).
8. Sensing – Test various things (touching, distance, key pressed) and
ask the player questions.
9. Operators – Math and logic “operators” (add, subtract, multiple,
divide, >, <, =, and, or, not).
10. More Blocks – Allows you to create custom blocks. We will not be
using this feature in this book.
Before we start coding, let’s first review how to work with code blocks.
Writing code with Scratch is kind of like building with Legos, where you
snap small colorful blocks together to build something. In Scratch, you drag
and drop colorful code blocks from the block palette into the coding area.
When two blocks are close to each other, they will snap together. You will
see a white line appear between the two blocks when they are close enough
to snap together. Then if you drop the block, it will snap into place, attached
to the nearby block.
Figure 55 – How to connect blocks
You can disconnect blocks by left-clicking on a block and dragging it away
from the block above it. Try this.
Figure 56 – How to disconnect blocks
To replace a block, you disconnect the block that you want to replace,
delete it, and add the new block.
Figure 57 – How to replace a block
Now let’s get ready to start our coding by clearing the coding area.
IMPORTANT : If you need to power off your Pi before completing this
Quick Draw Cat project, skip ahead to Step 37 to learn how to save your
project file before powering off your Pi.
Figure 58 - Clear the coding area
The first block category that we will use is “Events.” Event blocks cause
your code to start executing.
Step 1 - Left-click on the “Events” code block category in the block palette.
NOTE: All of the coding steps in this chapter are shown in the diagrams
that follow the written instructions for each coding step. See Figure 59
below.
Figure 59 – Select Events block category
Step 2 - Drag and drop the “when green flag clicked” block at the top of the
coding area. Left-clicking the green flag is the standard way to start your
program running in Scratch.
Figure 60 – When green flag clicked
Positioning your sprite – You can place your sprite (in this project, it’s the
cat) on the stage by setting the X and Y positions of the sprite. The center of
the stage has an X value of 0, and Y value of 0 (Figure 61 ). Positions on
the right half of the stage have positive X values, while positions on the left
half of the stage have negative X values. Positions on the top half of the
stage have positive Y values, while positions on the bottom half of the stage
have negative Y values.
Figure 61 – Your sprite can be placed at XY positions on the stage
Figure 62 – Examples of setting sprite XY positions
Step 3 - Left-click the “Motion” block category.
Figure 63 – Select Motion block category
Step 4 – Drag and drop the “go to X=0 Y=0” block underneath the first
block (Figure 64 ). The two blocks will snap together when they get close.
This will place the cat at the center of the stage. NOTE: If the X and Y
numbers in the “go to” block are not zero, then left-click on the numbers
and type in a zero.
Figure 64 – Place cat on stage
Sprite direction – When creating a video game, you will often want to
change the direction that your sprite is facing. Scratch has a code block
named “point in direction” which allows you to rotate your sprite by an
angle (in degrees).
Figure 65 – The "Point in direction" block rotates the sprite by and angle
Figure 66 below shows some of the angle values that you can use to change
your sprite's direction.
Figure 66 – Sample sprite directions
Step 5 – Add (drag and drop) a “point in direction” block. The default
direction of 90 degrees (cat facing right) is a good starting direction, so you
don't need to change the direction initially.
Figure 67 – Set cat direction
Figure 68 shows how one line in our design can end up being two blocks in
our code. Placing a sprite on the stage involves setting both its location and
direction.
Figure 68 – Design mapped to code
Step 6 – Left-click the “Pen” block category.
Step 7 – Add a “clear” block.
Figure 69 - Clear the stage
Step 8 – Left-click the “Sound” block category.
Step 9 – Add a “play sound” block.
Figure 70 – Cat says “Meow”
Step 10 - Left-click the “Looks” code category.
Step 11 - Add a “Say Hello! for 2 secs” block.
Figure 71 – “Hello” popup balloon
Test - Left-click the green flag in the upper right corner of the stage and see
(and hear) what happens. NOTE: If you don’t hear anything, left-click the
“sound control” icon which is located in the upper right corner of the Pi
desktop, and left-click and drag the volume slider up to increase the
volume. If increasing the volume doesn’t work, drag the volume slider
back down to a low volume , and try using headphones or AC-powered
computer speakers (connect as shown back in Figure 5 ). To direct sound to
the audio port for headphones or speakers, right-click on the Sound Control
icon and select “Analog” (the default is HDMI).
Figure 72 - Test A
Step 12 - Left-click the “Events” code category.
Step 13 - Drag and drop the “When space key pressed” block to your
program and place it in the coding area alone by itself (Figure 73 ). Note
that the “Events” code blocks with rounded tops cannot be attached to other
blocks on their top side. These type of blocks allow you to create “event
handlers”, which are parts of your code that are executed when you take an
action, such as clicking a mouse button or pressing a key on your keyboard.
In this project, we will be creating several event handlers.
Figure 73 - Add keyboard event handler
Step 14 - Left-click the little black triangle to the right of the word “space,”
and then select “right arrow” from the events menu. REMINDER: To select
an item in a menu, you left-click on your selection.
Figure 74 - Right arrow key event handler
Next we will set the pen color for drawing the red line that trails the cat
when walking to the right on the stage. The easiest way to set the pen’s
color is to set it to the number from the color wheel. The color number for
red is zero.
Figure 75 - Pen color wheel
Step 15 – Left-click the “Pen” code category.
Step 16 – Add a “set pen color to <number>” block. Note the caution in
Figure 76 below, so you avoid picking the wrong block (they look very
similar).
Figure 76 - Set pen color to red
Step 17 – Add a “pen down” block. When the pen is down, a trailing line is
drawn behind the cat when it moves.
Figure 77 – Set the pen down
Step 18 – Left-click the “Motion” block category.
Step 19 – Add a “point in direction <number>” block.
Figure 78 – Point in direction
Step 20 – Add a “move <number> steps” block.
Figure 79 - Move 10 steps
Figure 80 below shows how the code that we just added maps to our
design.
Figure 80 - Code mapped to design
Step 21 – Left-click the “Pen” block category.
Step 22 – Add a “pen up” block. When the pen is up, no lines are drawn as
the cat moves.
Figure 81 - Lift up pen
Test - Press the right arrow key on your keyboard several times. You should
see a thin red line trailing the cat when it moves.
Figure 82 - Test B
Step 23 – Add a “set pen size to <number>” block. This block allows you
to change the thickness of the line that is drawn by the pen.
Figure 83 – Make the trailing line thicker
Step 24 – To increase the line thickness, left-click inside the white circle in
the “set pen size to <number> block. Type in the number 10.
Step 25 – To enter the pen size change, left-click anywhere on the
background area of the coding area.
Figure 84 - Increase pen size to 10
Test – Left-click the green flag and then press the right arrow key. The red
trailing line should be thicker.
Figure 85 - Test C
Now let’s create an event handler for the other arrow keys (left, up, down).
We can take a short cut and do this fast by copying our event handler for the
right arrow key, and then modifying the copied code in the few places that
are required for the different direction of travel and different line color.
Figure 86 - Copying event handler
Step 26 – Right-click on the “when right arrow key pressed” block in your
code, and select “duplicate” from the menu that pops up.
Step 27 – Move the copied set of blocks to the open space to the right, and
left-click to drop them.
Figure 87 – Duplicating a code block
Steps 28 & 29 – Repeat steps 26 & 27 two more times, so that we have a
total of four arrow key event handlers. Place those two new event handlers
below the two existing arrow key event handlers.
Figure 88 - Copies of arrow key event handler
Step 30 – Set up the left arrow key event handler as shown below in Figure
89 .
Figure 89 – Set up event handler (left arrow key)
Step 31 – Set up the up arrow key event handler as shown below in Figure
90 .
Figure 90 – Set up event handler (up arrow key)
Step 32 – Set up the down arrow key event handler as shown below in
Figure 91 .
Figure 91 – Set up event handler (down arrow key)
NOTE: Researchers did a study to learn how “bugs” (coding errors) end up
in our code. The study found that a common source of bugs was the use of
code duplication (also called “copy/paste”), where the person doing the
coding forgot to make all of the required changes to the copied section of
code. So just be careful when duplicating code that you make all of the
necessary changes for the new code usage.
Test – Left-click the green flag. Press the right, left, up and down arrow
keys, moving the cat around the stage.
Figure 92 - Test D
Sample test results are shown below. Note that you can view the stage in
“Full Screen” mode by left-clicking on the blue icon in the upper left corner
of the stage (see below). Left-click the blue icon a second time to exit Full
Screen mode.
Figure 93 – Zooming to Full Screen is nice for testing
Let’s review our requirements and see what else needs to be done.
Figure 94 - Review of requirements
Step 33 – When creating a video game, we sometimes want to “animate” a
sprite so that the character appears to be walking or running. In Scratch, we
can do this using a sprite's “costumes.” Some sprites that come with Scratch
have multiple costumes, and some sprites don't. To see which costumes a
sprite has, you can left-click on the “Costumes” tab in the coding area. The
cat sprite that we are using has two costumes, with the legs and arms being
in different positions. As shown below in Figure 95 , if we alternately
display the two available costumes for our sprite, the cat will appear to be
walking. The two costumes have the names “cat1-a” and “cat1-b.”
Figure 95 - Sprite animation
Step 34 – Left-click the “Scripts” tab to return to the coding view.
Step 35 – Left-click the “Looks” block category.
Step 36 – Add the “next costume” block at the bottom of each of the four
arrow key event handlers.
Figure 96 - Next costume block
NOTE: Scratch has an optional “cleanup” feature that will rearrange your
code blocks in the coding area into a more compact and precisely aligned
format. To use this feature, right-click on an empty spot in the coding area,
and then left-click on “Cleanup” in the popup menu.
Test – Select a large stage size. Left-click the green flag. Press the right,
left, up and down arrow keys, moving the cat around the stage. The cat’s
legs should now appear to be moving while walking.
Figure 97 - Test E
Now all of our requirements have been completed and successfully tested!
Figure 98 – All requirements are satisfied
Congratulations! You have learned about the
Requirements/Design/Code/Test development process, learned some of the
basics of working in the Scratch programming environment, and learned
how to use keyboard inputs and mouse clicks to interact with your code.
Save your project – While you are coding, your work is being stored in
temporary RAM. When you reach a point where you are happy with your
code, you should save it to the SD memory card that is plugged into your
Pi. The SD card is permanent memory (also called “storage”) and will keep
your code stored even after power is removed from your Pi.
Figure 99 – Save your work to the SD memory card
When you save a file (such as your Scratch project) onto your SD memory
card, you need to select a folder to store your file in. We will use the “My
Code” folder that you created on the desktop back in Chapter 6 “Customize
Desktop.”
Step 37 – Left-click the “File” menu in the upper left corner of the Scratch
window.
Step 38 – Left-click the “Save Project” menu item.
Figure 100 – Save your project
Step 39 – You will see a popup window (Figure 102 ) where you will enter
a name for your Scratch project file (also called the “filename”). Choose a
filename that reminds you of what the project is about. If you are in a home
or classroom where there are other students using the same Pi, then it is
important to include your own name in the filename, so that you can easily
locate the projects that belong to you. Figure 101 below shows filename
suggestions for a student named Mary Smith (example), based on the
student’s “Pi sharing” situation.
Figure 101 - Choosing a filename
As seen at the top of Figure 102 below, the name that you enter is followed
by.”.sb2”. That is the “file extension” for Scratch 2.0 projects (NOTE: For
Scratch 1.4 projects, the file extension is ”.sb”).
Step 40 –If it’s not already selected (blue background), left-click “Desktop”
along the left side of the File Selection window (Figure 102 ). This will
display the folders and files that are contained on the desktop (shown in
Figure 103 ).
Figure 102 – Popup window for saving your project
Step 41 – Double left-click the “My Code” folder (or single left-click it and
then press the Enter/Return key). This opens the “My Code” folder
contained inside the Desktop folder (that is contained inside the pi folder).
Figure 103 - Selecting Scratch Projects folder for save
Step 42 – Left-click the Save button. After saving the project, notice that
the project name appears above the stage.
Figure 104 - Save Quick Draw Cat project
Your project is now saved! It is now safely stored on your SD memory
card, and your project will still exist if you power off your Pi.
Notes on saving your work - It can be helpful to save your work
frequently. Saving your project each time that you have run a successful
test is a good approach. That way, if you find that a change that you have
made has introduced an error (i.e. “software bug”), and you cannot easily
undo that change, then you can simply open your project again, and then
you will have discarded any code changes that you made since the last time
you saved your project. But this is just a suggestion. You can decide how
often you want to save your work. Some people like to save often, while
others don’t. Also, as an optional precaution to be extra safe, as shown in
Chapter 15 (“Backing Up Your Work”), you can save an extra copy (called
a “backup” copy) of your Scratch projects to a removable USB memory
stick. This can come in handy for the case where your Pi is lost or damaged.
You just need to make sure that you keep your USB memory stick in a safe
location that is separate from your Pi, so that they are not lost together.
Opening your project - Now before we move on to the student exercises,
let’s go through the steps for opening a Scratch project that you have
previously saved to your SD memory card.
Step 43 – Let’s start from the very beginning, by closing the Scratch
application first.
Step 44 – Start the Scratch program using the shortcut on the desktop.
Figure 105 - Close and restart Scratch
One important thing to know about opening an existing Scratch project file
is that you must only do it using the File menu. You will get a bad result if
you open your “My Code” folder on your desktop and then double-click the
project file (or single left-click it and then press the Enter/Return key). The
Scratch software will be started, but your code will appear to be missing
(it’s not really, but it looks like it). This is shown in the following figure.
Figure 106 – Caution on opening existing project files
Step 45 – Left-click the “File” menu in the upper left corner of the Scratch
window.
Step 46 – Left-click the “Load Project” menu item. A file selection window
will popup.
Figure 107 - Open a project
Step 47 – A file selection window is displayed. At this point, there is only
one Scratch project file (Quick Draw Cat.sb2), and it is selected
(highlighted in blue). If there are multiple files listed, then you need to left-
click on the one that you want to open to select it. To open the selected file,
left-click the Open button.
Figure 108 – File selection window (Open)
Step 48 – When asked “Replace contents of current project?” left-click OK.
Working on the coding exercises – At the end of this chapter are exercises
that will test your coding skills. You will be creating a separate project file
for each exercise, and we want to keep the original Quick Draw Cat project
file unchanged. In most of the exercises you will be making small changes
to either 1) the original project, or 2) the code of a prior exercise. In the
exercise instructions, the “starting point” will be named as either the
original project, a numbered exercise project, or you will be asked to create
a completely new project (as in Exercise 5). The relationships of the
exercise projects are shown in Figure 109 .
Figure 109 - Quick Draw Cat exercises
For the exercises where the starting point is an existing project (Exercises 1,
2, 3, 4), a good way to protect your starting point project from being
accidently overwritten (as you work on a new exercise) is to make a copy of
the starting point project before you start an exercise, and then make your
coding changes to that copy. That copy will have a filename that includes
the exercise number (like “Quick Draw Cat EX1”). This process is shown
in Figure 110 . We will create the exercise copy by saving the starting point
project using the “File> Save Project” menu item, and entering the new
filename. This method of saving a file as a copy with a new filename is
often referred to as “Save As”. NOTE: Don’t worry if this seems
confusing. The specific steps that you need to follow will be listed in the
exercise descriptions in the next chapter.
Figure 110 – How to work on an exercise
Chapter 10: Exercises - Quick
Draw Cat
(see Chapter 16 for the answers)
1. Use a pen size of 20 when walking to the right
a. Starting point - Original Quick Draw Cat project.
b. Save As - Add “EX1” at the end of your original filename
(use “File>Save Project” menu option). NOTE:
Remember to save it into your “My Code” folder as
shown earlier in Figure 102, Figure 103, and Figure 104.
c. Code change - Set pen size to 20 in the event handler for
the right arrow key.
d. Test - When walking in the right direction, you should see
a colored line trailing the cat that is 2 times wider than in
the original version.
e. Save - Save your completed exercise.
2. Use a pen size of 100 when walking in all directions
a. Starting point - Exercise 1 project.
b. Save As - Add “EX2” at the end of your original filename
(use “File>Save Project”).
c. Code change - Set pen size to 100 in the event handler for
each arrow key.
d. Test - When walking in all directions, you should see a
colored line trailing the cat that is 10 times wider than in
the original version.
e. Save - Save your completed exercise.
3. Change pen shade with each step
a. Starting point - Exercise 2 project.
b. Save As - Add “EX3” at the end of your original filename
(use “File>Save Project”).
c. Code change - In the block palette, for “Pen,” you will
find the “change pen shade by <number>” block. Insert
that block above the “pen down” block in each arrow key
event handler. Set the number value to 5.
d. Test - When walking in all directions, you should see the
shade of the color change with each step.
e. Save - Save your completed exercise.
4. Increase the pen size with each step
a. Starting point - Original Quick Draw Cat project.
b. Save As - Add “EX4” at the end of your original filename
(use “File>Save Project”).
c. Code change
i. Set pen size to 1 in the program startup code
(executes when green flag clicked).
ii. In each arrow key event handler, replace the “set
pen size to <number>” block with a “change pen
size by <number>” block, where the number is
1. TIP: It is helpful to zoom out the coding area
(previously shown in Figure 53), and then drag
the arrow key event handlers further apart to
have some room to work. If you need to refresh
your memory on how to replace a block, refer
back to Figure 56 (disconnecting blocks) and
Figure 57 (replacing blocks).
d. Test - As the cat walks, the width of the colored trail
should continue to grow.
e. Save - Save your completed exercise.
5. Control the pen using letter keys
a. Summary - In this exercise, you will add 4 new event
handlers to your program. You will use these event
handlers to control the pen. These new events correspond
to pressing specific letter keys on the keyboard (u, d, b,
y). So far in this book, you have only used the arrow keys
and mouse clicks as events. But many of the keys on your
keyboard can be used as events too. The full list of the
keys that you can use as events is shown when you left-
click on the little black triangle on the “when <key> key
pressed” block (Figure 111 on the next page). In this
exercise, pressing those 4 letter keys (u, d, b, y) will cause
the pen to be lifted up (letter “u” for up), placed down
(letter “d” for down), colored blue (letter “b” for blue),
and colored yellow (letter “y” for yellow). As an
additional challenge in this exercise, you will use those
new controls to draw the picture shown in Figure 112.
b. Starting point - Create a new project using the
“File>New” menu option.
c. Save As - Add “EX5” at the end of your original filename
(use “File>Save Project”).
d. Design
i. When green flag clicked
1. Shrink the cat to half size (NOTE: In the
“Looks” section of the block palette, use
the “set size to <number>%” block and
set the number to 50).
2. Place the cat at the center of the stage
and pointing in the right direction.
3. Erase any pen markings on the screen.
4. Start with a red pen that has a size of 1.
5. Lift the pen up.
ii. When right arrow pressed
1. Point cat in right direction.
2. Move cat 10 steps (walking).
iii. When left arrow pressed
1. Point cat in left direction.
2. Move cat 10 steps (walking).
iv. When up arrow pressed
1. Point cat in up direction.
2. Move cat 10 steps (walking).
v. When down arrow pressed
1. Point cat in down direction.
2. Move cat 10 steps (walking).
vi. When “d” key pressed (“d” is for down, as in
pen down)
1. Place pen down.
vii. When “u” key pressed (“u” is for up, as in pen
up)
1. Lift pen up. (TIP: To find the “u” key in
the menu of keys, place your mouse
pointer over the small white triangle at
the bottom of the menu, and the lower
half of the menu will be displayed.)
viii. When “b” key pressed (“b” is for blue)
1. Set pen color to blue.
2. Set pen size to 200. (NOTE: This large
pen size will make it easy to quickly
color the stage background with blue
before drawing the yellow letters.)
ix. When “y” key pressed (“y” is for yellow)
1. Set pen color to yellow.
2. Set pen size to 30.
e. Code - Translate the design shown above into code.
f. Test/Challenge - Using the arrow keys and the “b,” “y”
and “u” keys, spell the word “CAT” with yellow letters on
a blue background. The result should look something like
Figure 112.
g. Save - Save your completed exercise.
Figure 111 - Key menu
Figure 112 – Control the pen using letter keys (Challenge)
Chapter 11: Project - Paint
Pong
Paint Pong is a colorful twist on the classic game Ping Pong. As the ball
moves across the stage, a colored line is painted, following the path of the
ball. Each time a player hits the ball with a paddle, the color of the paint
changes. All of the colored lines are erased when a player misses the ball
with their paddle. So the longer that you are able to hit the ball back-and-
forth without missing, the more colored lines will fill up the stage, resulting
in an interesting and unique work of art!
The coding for this game is more complicated than Quick Draw Cat, which
only used one sprite (the cat). Paint Pong will use multiple sprites. The ping
pong ball is one of the sprites. Two other sprites, the paddles, are controlled
by two players. While you are developing your code, you will perform the
role of both players, controlling the paddle for Player 1 with your left hand,
and controlling the paddle for Player 2 with your right hand. After you have
finished coding and testing the game, you can invite a friend or family
member to play it with you, or you can play it by yourself and see how long
you can keep hitting the ball back-and-forth without missing.
The code for Paint Pong introduces the concept of “interaction” between
sprites, where specific things will happen when two sprites touch each
other. For example, when the ball sprite touches a paddle, the ball will
bounce off the paddle by changing the direction that it is moving. Another
example of sprite interaction is where an “edge” sprite is used to detect
when a player has missed the ball. interaction of the ball and the edge
sprites will become clearer later in this chapter.
REQUIREMENTS :
1. The instructions on how to play the game will be displayed when
the green flag is clicked.
2. Game play will start when the “s” key is pressed.
3. It will be a 2 player game, played like ping pong, with each player
controlling one paddle. NOTE: The game can also be played by one
person controlling both paddles.
4. Player 1 will control the left paddle using the “a” and “z” keys on
the keyboard (a = UP, z = DOWN). Player 2 will control the right
paddle using the “up arrow” and “down arrow” keys.
5. As the ball moves on the screen, a colored line will be drawn
following the ball.
6. When a player hits the ball with the paddle, the color of the trailing
line is changed.
7. When a player misses the ball with the paddle, all lines on the
screen are erased, and the ball will be re-launched from the center
of the screen.
8. The game score will be displayed along the top of the screen. When
a player misses the ball with the paddle, a point is awarded to the
other player.
DESIGN (Sprite definition) :
We will use 6 different sprites for this game. Each sprite will have its own
code that defines the look and behavior of the sprite.
The sprites are:
1. Instructions – Includes the game title, and explains how the game
is played.
2. Ball – The ping pong ball.
3. Paddle1 – Player 1’s paddle (positioned at the left side of the
screen).
4. Paddle2 – Player 2’s paddle (positioned on the right side of the
screen).
5. Goal1 – Scoring zone for Player 2.
6. Goal2 – Scoring zone for Player 1.
Some of the sprites have obvious roles in the game, such as the ball and the
paddles. Those sprites move in response to player actions, and correspond
to real-world objects. But there are also sprites, such as Goal1 and Goal2
that are simply used as unmoving “sensors,” for which a section of your
code can be triggered when another sprite (in this case, the ball) touches the
sensor sprite. This is the way that points are scored in Paint Pong. When the
ball touches either goal sprite, a point is scored for the opposite player, and
the ball position is set back to the center of the stage to be relaunched. The
6 sprites used for this game are shown in Figure 113 .
Figure 113 - Sprites (Paint Pong)
SPRITE #1: Instructions
DESIGN (Instructions):
1. When green flag is clicked:
a. Show sprite (this makes the Instructions sprite appear on
the stage).
2. When “s” key is pressed (“s” is short for “start game”):
a. Hide sprite (this makes the Instructions sprite disappear).
CODE & TEST (Instructions):
In Scratch, you can use either pre-built sprites (such as the default cat sprite
that we used in “Quick Draw Cat”) or you can build your own sprite using
Scratch’s Paint Editor tool. To create the Instructions sprite, we will use the
Paint Editor.
An Instructions sprite should include the following:
1. Title of the game (“Paint Pong”).
2. A brief description of how to play the game.
3. A list of the keyboard controls that are used to play the game.
4. The keyboard control that is used to start the game (we will use
the “s” key).
Step 1 - Left-click the gray triangle to shrink the stage and expand the
coding area.
Step 2 – Right-click on the Cat sprite.
Step 3 - Left-click the “Delete” item from the popup menu.
Figure 114 - Delete cat sprite
Step 4 - Left-click the paint brush icon to paint a new sprite.
Figure 115 - Paint new sprite
Step 5 – Right-click inside the gray “Sprite1” box.
Step 6 – Left-click “info” in the popup menu.
Figure 116 - Update sprite name
Step 7 - Left-click after “Sprite1”, and delete it (repeatedly press the
Delete/Backspace key).
Step 8 - Type in the new sprite name “Instructions”.
Step 9 - Click the “back” button (white triangle inside blue circle).
Figure 117 - Update sprite name (continued)
Step 10 - Left-click the “T” to enter text mode.
Figure 118 – Paint Editor tool
Step 11 - Left-click in the Painting Area where you want to start writing the
game instructions.
Figure 119 – Adding text to the Painting Area
Step 12 - Write your game instructions. NOTE: Press the Return/Enter key
to continue on the next line.
Figure 120 - Game instructions
Step 13 - Click the Scripts tab after you have entered the game instructions.
Figure 121 –Switch to Scripts tab
Step 14 – Left-click on the Scripts tab. Add the event handler code as
shown in Figure 122 .
Figure 122 - Instructions sprite code
Test - Left-click the green flag. Press the “s” key. You should see the results
shown below.
Figure 123 - Test A
Figure 124 – Requirements (after Test A)
SPRITE #2: Ball
Figure 125 - Ball sprite functions
DESIGN (Ball):
1. When the green flag is clicked:
a. Hide the Ball sprite. We only want the Instructions sprite
to be seen at the beginning.
b. Set the ball size, and place the ball at the center of the
screen. NOTE: We can do this setup even though the Ball
sprite is not yet displayed.
c. Set the launch angle for the ball (using “point in
direction” block).
d. Set the pen color and pen size, and then place the pen
down (ready to draw).
e. Erase any pen markings on the screen from previous
game play.
2. When the “s” key is pressed (“s” is short for “start game”):
a. Show the sprite (it was hidden when the green flag was
clicked).
b. Display a countdown that reads “Ready” (for 1 second),
“Set” (for 1 second), and “Go” (for 1 second).
c. Loop forever, doing the following:
i. Move the ball forward a few steps.
ii. If the ball touches an edge of the stage
1. Bounce the ball off the edge of the stage
(use the “if on edge, bounce” block)
iii. If the ball touches a paddle:
1. Bounce the ball off the paddle by
changing the ball’s direction.
2. Change the pen color.
3. Play a “pop” sound.
iv. If the ball touches a goal:
1. Place the ball in the center of the stage.
2. Erase any pen markings on the screen
and reset the pen color.
3. Add one point to the score for the
appropriate player.
CODE & TEST (Ball):
Step 15 - Left-click this icon to choose a sprite from the library.
Figure 126 – Choose a sprite from the library
Step 16 - Left-click the Ball sprite.
Step 17 - Left-click the OK button.
Figure 127 – Select the Ball sprite
Figure 128 - Ball sprite on stage
Step 18 - Left-click on Costumes tab.
Step 19 - OPTIONAL: Left-click on a colored ball (costume), if you want
to use a color other than yellow.
Figure 129 - Ball sprite costumes
Step 20 - Left-click on the Scripts tab.
Step 21 - Add event handler code for:
green flag
“s” key
Figure 130 - Ball sprite code (partial)
Test - Left-click the green flag. Press the “s” key. The ball bounces around
the stage.
Figure 131 - Test B
To stop your code, click on the red octagon that is located above the stage
(next to the green flag).
Figure 132 - Stop your code
Figure 133 - Requirements (after Test B)
SPRITES #3 & #4: Paddle1 & Paddle2
Figure 134 – Paddle sprite functions
DESIGN (Paddle1):
1. When green flag is clicked:
a. Hide sprite (only the instructions are shown).
b. Position sprite on the stage (so it’s in the right place when
the game starts).
2. When “s” key is pressed (start game):
a. Show sprite.
3. When “a” key is pressed:
a. Move the paddle up by adding 30 to its y position.
4. When “z” key is pressed:
a. Move the paddle down by subtracting 30 from its y
position.
DESIGN (Paddle2):
1. When green flag is clicked:
a. Hide sprite.
b. Position sprite on the stage.
2. When “s” key is pressed (start game):
a. Show sprite.
3. When “up arrow” key is pressed:
a. Move the paddle up by adding 30 to its y position.
4. When “down arrow” key is pressed:
a. Move the paddle down by subtracting 30 from its y
position.
CODE & TEST (Paddle1):
Step 22 - Left-click on the icon shown below to choose a sprite from the
library.
Figure 135 – Choose a sprite from the library
Step 23 - Left-click and drag the slider down to find the Paddle sprite.
Step 24 - Left-click the Paddle sprite.
Step 25 - Left-click the OK button.
Figure 136- Select the Paddle sprite
Figure 137 – Paddle sprite is added
Step 26 – Right-click inside the Paddle sprite box.
Step 27 - Left-click “info” in the popup menu.
Figure 138 – Get ready to change the Paddle sprite name
Step 28 - Left-click after “Paddle”.
Step 29 – Type “1”.
Step 30 - Left-click the “rotate” icon to allow you to point the sprite in any
direction.
Step 31 - Left-click the “back” button.
Figure 139 - Update sprite name to Paddle1
Step 32 - Add the event handler code shown below.
Figure 140 - Event handler code (Paddle1 sprite)
Test - Left-click the green flag. Press the “s” key. Press the “a” and “z” keys
to move Paddle1.
Figure 141 – Test C
Step 33 - Left-click the Ball sprite, so that you can update its code.
Step 34 - Left-click the “Control” block type.
Figure 142 – Select the “Control” palette
Step 35 – Add an “if then” block.
Figure 143 – Add an “if then” block
Step 36 - Left-click the “Sensing” block type.
Step 37 – Drag and drop a “touching” block inside the “if then” block.
Figure 144 - Add a "touching" block
Step 38 - Left-click the little black triangle.
Step 39 - Left-click “Paddle1”.
Figure 145 – Select touching Paddle1.
Step 40 - Left-click the “Motion” block type.
Step 41 – Add a “point in direction” block. Leave the angle as 90 degrees
for this step.
Figure 146 – Add a “point in direction” block
Test - The ball bounces off the paddle at a 90 degree angle.
Figure 147 –Test D
Step 42 - Left-click the “Operators” block type.
Step 43 – Drag and drop an addition (+) operator block inside the “point in
direction” block.
Figure 148 – Add an addition operator block
Step 44 – Drag and drop (on the right side of the “+” sign) a “pick random”
block.
Figure 149 – Add a “pick random” block
Picking a random number in Scratch is like rolling dice, where you don’t
know which specific number will result, but you do know the range
numbers. If you roll two dice, then the result (the sum of the numbers on the
top of the dice) will always be between 2 and 12. In the “pick random”
Scratch block, you specify two numbers; the lowest number that can be
picked (the number on the left), and the highest number that can be picked
(the number on the right). When the “pick random” block is executed in
your code, your Pi randomly picks a number within that range. Using
random numbers in your code can make your game more interesting, since
the behavior is not so predictable. A game can get boring if you always
know what is going to happen next in a given situation. In Paint Pong, if the
ball always bounced off the paddle at the same angle (like in the prior test
that you ran), the game would be too easy and wouldn’t be very fun.
Instead of repeatedly using the same bounce angle for a given paddle, we
will update the “point in direction” block to include a more complicated
bounce angle calculation. As shown in Figure 150 below, the bounce angle
is calculated by adding a “base angle” (90 degrees for Paddle1) to a
randomly selected number from within the range of -45 and 45 (meaning
numbers such as -45, -44, -43, -42, ..., 42, 43, 44, 45). This will bounce the
ball back towards Player 2’s side of the gaming area, but in an
unpredictable way. The bounce angle will randomly change each time that
the ball hits Paddle1, although the angle will be somewhere between the
two blue dashed lines (shown in the figure below) which represent the
bounce angles that are computed when the random number picked is at
either of the outer limits of your specified range (-45 or 45).
NOTE: In Step 45 on the next page, we will be set up the “point in
direction” block in our code as shown below in Figure 150 .
Figure 150 – Ball bounce angle (Paddle1)
Step 45 - Left-click (in white areas) and type in the following:
Base angle = 90
Random range (low) = -45
Random range (high) = 45
Figure 151 – Set up “point in direction” block
Test - The ball bounces off the paddle at random angles. IMPORTANT: If
the ball is moving too fast for you, you can use a smaller number in the
“move <number> steps ” block. For example trying changing the number
from 5 to 4. If it’s still too fast, try 3 or 2. Different models of the Pi
computers run at different speeds, so you may need to try different numbers
of steps per loop before you find the one that you like best.
Figure 152 - Test E
Step 46 - Left-click the “Pen” block type.
Step 47 – Add a “change pen color by <number>” block, and set the
number to 20.
Figure 153 – Add “change pen color” block
Test – The pen color changes when the ball touches the paddle.
Figure 154 – Test F
Step 48 - Left-click the “Sound” block type.
Step 49 – Add a “play sound <pop>” block.
Figure 155 –Add a “play sound” block
Test – When the ball hits the paddle, there is a pop sound.
Figure 156 – Test G
CODE & TEST (Paddle2):
Step 50 - Left-click on “Paddle1” to select the sprite.
Step 51 – Right-click on “Paddle1” to popup the menu.
Step 52 - Left-click on “duplicate”. This creates a 2nd paddle (named
Paddle2) with the same code as Paddle1.
Step 53 - Left-click on “Paddle2” to select that sprite.
Figure 157 – Duplicate Paddle1 to create Paddle2
Figure 158 - Paddle2 code is copied from Paddle1
Step 54 – On the “go to” block, left-click in the white area, and type in x
value “210” (changes it to positive). That will position Paddle2 on the right
side of the stage (once the green flag is clicked).
Step 55 – On the “when ‘a’ key pressed” block, left-click the little black
triangle and select “up arrow” from the menu.
Step 56 – On the “when ‘z’ key pressed” block, left-click the little black
triangle and select “down arrow” from the menu.
Figure 159 – Update Paddle2 code
Test – Paddle2 moves, but the ball passes through the paddle.
Figure 160 – Test H
CODE & TEST (Ball - continued):
Step 57 - Left-click the Ball sprite.
Step 58 - Right-click on the “if then” block. A menu will popup.
Step 59 - Left-click on “duplicate.”
Figure 161 – Duplicate the “if then” block
Step 60 – Using the mouse, move the duplicated set of code down to the
bottom of the forever loop.
Figure 162 – Move the duplicated code
To calculate the bounce angle off of Paddle2 (the paddle controlled by
Player 2), the only difference from the “point in direction” block used for
Paddle1 is that the base angle is -90 degrees (pointing left) instead of 90
degrees (pointing right). Now each time that the ball touches either Paddle1
or Paddle2, it will bounce at an unpredictable angle, but in the direction of
the other player’s side of the gaming area.
Figure 163 – Ball bounce angle (Paddle2)
Here’s a refresher on angle definitions (from Quick Draw Cat).
Figure 164 – Angle refresher
Step 61 – In the duplicated “if then” block, left-click on the little black
triangle and left-click on Paddle2.
Step 62 – In the duplicated “point in direction” block, left-click in the white
area and type in “-90”.
Figure 165 – Ball code
Test – Both paddles are now working!
Figure 166 - Test I
Figure 167 – Requirements (after Test I)
SPRITES #5 & #6: Goal1 & Goal2
Figure 168 – Goal sprites
DESIGN (Goal1 & Goal2):
1. When green flag is clicked:
a. Hide sprite (only the instructions are shown).
b. Position sprite on the stage.
2. When “s” key is pressed (start game):
a. Show sprite.
CODE & TEST (Goal1):
Step 63 - Left-click on the paint brush icon to paint a new sprite.
Step 64 – Right-click on the new sprite.
Step 65 - Left-click on “info” in the popup menu.
Figure 169 – Create new sprite
Step 66 - Left-click after “Sprite1”, and delete it (repeatedly press the
Delete/Backspace key).
Step 67 – Type in the new sprite name “Goal1”.
Step 68 - Left-click the “back” button (white triangle inside blue circle).
Figure 170 – Name the new sprite Goal1
Step 69 - Left-click on the rectangle icon in the Painting area.
Step 70 - Left-click on the medium gray color in the color palette.
Figure 171 – Select color for Goal1
Step 71 - Left-click in the upper left corner of the painting area (cross-
hatched background), and while holding down the left mouse button, move
the mouse down and to the right to draw a thin rectangle as shown in
Figure 172 below. The Goal1 sprite should be as tall as possible, so that the
ball cannot get past it.
Figure 172 – Draw the outline of Goal1
Step 72 - Left-click on the “Fill with color” icon (looks like a paint bucket).
Step 73 - Left-click inside the rectangle that you drew to fill it with gray
color.
Figure 173 – Fill in Goal1 with gray color
Step 74 – Add the Goal1 event handler code shown below for the green
flag and the “s” key.
Figure 174 – Goal1 event handler code
Test – Goal1 appears on the left edge of the stage.
Figure 175 – Test J
CODE & TEST (Goal2):
Step 75 - Left-click on Goal1 to select that sprite.
Step 76 – Right-click on Goal1 to popup the menu.
Step 77 - Left-click on “duplicate.” This makes a 2nd goal (named Goal2)
with the same code as Goal1.
Step 78 - Left-click on Goal2 to select that sprite.
Figure 176 – Duplicate Goal1 to create Goal2
Step 79 – Left-click on the Costumes tab, and then left-click on the
“Select” tool.
Step 80 – Move the mouse pointer above the upper left corner of the gray-
filled goal. Press and hold down the left mouse button and move the mouse
pointer below the lower right corner to create a “selection” box that
surrounds the gray-filled goal. Then release the left mouse button to select
the goal.
Figure 177 – Select Goal2
Step 81 – Move the gray-filled goal by dragging and dropping it at the right
edge of the painting area. Another way to move the gray-filled goal is to use
the arrow keys on your keyboard (up, down, left, right).
Step 82 – After dropping the goal, left-click anywhere in the painting area
to finish the move.
Figure 178 – Move Goal2
Step 83 - Left-click the Scripts tab. Notice that the code is already done
(duplicated from Goal1 sprite). You will not need to make any code
changes.
Figure 179 – Goal2 code
Test – Goal2 appears on the right edge of the stage.
Figure 180 – Test K
CODE & TEST (Ball - continued):
Step 84 - Left-click the Ball sprite.
Step 85 - Left-click the “Control” block type.
Step 86 – Add an “if then” block.
Figure 181 – Add “if then” block
Step 87 - Left-click the “Sensing” block type.
Step 88 – Drag and drop a “touching” block inside the “if then” block.
Step 89 - Left-click the little black triangle.
Step 90 - Left-click “Goal1” in the pulldown menu.
Step 91 – If the ball touches Goal1:
Place Ball at the center of the stage.
Erase all pen lines.
Reset pen color to red.
Figure 182 – If Ball touches Goal1
Step 92 – Right-click on the newly added “if then” block.
Step 93 - Left-click “duplicate” in the pulldown menu.
Step 94 – Move the duplicated blocks down so that the white “insertion”
line is below the “if then” block that was duplicated.
Figure 183 – Duplicate “If then” block
Step 95 - Left-click on “Goal2” in the pulldown menu.
Figure 184 – Update sprite to “Goal2” in duplicated “touching” block
Test – When the ball hits Goal1 or Goal2, all painted lines are erased.
Figure 185 - Test L
Figure 186 – Requirements (after Test L)
For Paint Pong, we will be using the “Data” block category to create
“variables”.
A “variable” is an object in your code that has the following things:
1. A name (like “Player 1 Score”)
2. A value (like 12).
Figure 187 - Data block category
Reasons to use variables:
1. Varying value - You need a place to keep a data value that will
change as the game is played (like ”Player 1 Score” and ”Player 2
Score”). See Figure 188 .
2. Constant value - You have a data value that will not change during
the game, but you want to make your code more organized and
easier to read by giving a name to the data value. This is especially
helpful if the same constant value is used in multiple places in your
code. Using a variable allows you to change the value in one place,
and then just reference the name elsewhere in your code.
Variables can be shown on the stage or hidden from view. In Paint Pong, we
want the players to see their scores, so the variables “Player 1 Score” and
“Player 2 Score” will be displayed on the stage.
Figure 188 - Variables on the stage
We will now create and position the player score variables on the stage.
Start by erasing any painted lines that are on the stage from your last test.
To do that, left-click the green flag, press the “s” key to start the game, and
then immediately left-click the red stop icon (to the right of the green flag).
Step 96 - Left-click the “Data” block category. NOTE: It doesn’t matter
which sprite is selected when you create your variables, since all of the
variables that you create in a Scratch project are shared by all of your
sprites (unless you limit the variables to a specific sprite, which we won’t
be doing).
Step 97 - Left-click the “Make a Variable” button.
Step 98 – Type in “Player 1 Score” and click the OK button.
Figure 189 – Create ”Player 1 Score” variable
Step 99 - Left-click on the “Make a Variable” button.
Step 100 – Type in “Player 2 Score” and click the OK button.
Figure 190 - Create "Player 2 Score" variable
Step 101 - Left-click on the “Player 1 Score” and “Player 2 Score”
variables and drag them to the center top of the stage. NOTE: If you are not
able to move the variables, set the stage to its smallest size and try again.
Figure 191 - Position the variables on the stage
Step 102 – Add a “set <variable>” block.
Step 103 - Left-click on the little black triangle.
Step 104 - Left-click on “Player 1 Score”.
Figure 192 - Add a "set variable" block
Step 105 – Add another “set <variable> block.
Figure 193 - Add another "set variable" block
Step 106 – Add a “change <variable> by <number> block. The variable is
“Player 2 Score”. The number is 1.
Figure 194 - Add a "change variable by number" block
Step 107 – Add another “change <variable> by <number> block.
Figure 195 - Add another "change variable by number" block
Step 108 - Left-click on the little black triangle.
Step 109 - Left-click on “Player 1 Score”.
Figure 196 – Set up 2nd "change variable by number" block
Test – Player scores are displayed. NOTE: Don’t worry if the player scores
overlap with the game instructions (after clicking the green flag). We’ll fix
that in the next step.
Figure 197 - Test M
Finally, let’s add code to hide the player scores when the game instructions
are displayed.
Step 110 – Add a “hide variable <variable>” block.
Step 111 - Left-click on the little black triangle.
Step 112 - Left-click on “Player 1 Score”.
Figure 198 - Hide player 1 score on instructions screen
Step 113 – Add another “hide variable <variable>” block. The variable
should already be set to “Player 2 Score”.
Figure 199 – Hide player 2 score on instructions screen
Step 114 – Add a “show variable <variable>” block.
Step 115 - Left-click on the little black triangle.
Step 116 - Left-click on “Player 1 Score”.
Figure 200 - Show player 1 score on stage
Step 117 – Add another “show variable <variable>” block. The variable
should already be set to “Player 2 Score”.
Figure 201 - Show player 2 score on stage
Test – Player scores are hidden on the instructions screen, but are displayed
on the game screen.
Figure 202 - Test N
Now all the requirements are satisfied!
Figure 203 – Requirements (after Test N)
Congratulations! You have learned how to create a complex Scratch
program that contains multiple sprites, instruction screens, random number
generation, and variables (like the player scores).
Save your project – Follow the same steps that you used to save the prior
project (Quick Draw Cat), but save this project with the name Paint Pong.
Chapter 12: Exercises - Paint
Pong
(see Chapter 16 for the answers)
1. Play a drum sound when a point is scored.
a. Starting point - Original Paint Pong project.
b. Save As - Add “EX1” at the end of your original filename
(use “File>Save Project”).
c. Code hint - For the ball sprite, select the Sound block
type, and add a “play drum <number> for 0.25 beats”
block. You can choose the drum sound that you want by
changing the number that follows “play drum” in the
block.
d. Test - When a point is scored by either player, you should
hear the drum sound. NOTE: You should also still hear
the pop sound when the ball touches either paddle.
e. Save - Save your completed exercise.
2. Change ball color each time a point is scored.
a. Starting point - Exercise 1 project.
b. Save As - Add “EX2” at the end of your original filename
(use “File>Save Project”).
c. Code hint - For the ball sprite, select the Looks block
type, and add a “next costume” block.
d. Test - When a point is scored by either player, the ball
should change color.
e. Save - Save your completed exercise.
3. Change the pen size by 1 during each forever loop, and set the pen
size to 1 when a point is scored.
a. Starting point - Exercise 2 project.
b. Save As - Add “EX3” at the end of your original filename
(use “File>Save Project”).
c. Code hint - None.
d. Test - When the ball is launched, the width of the colored
trail that follows the ball will continuously increase until a
point is scored. Once a point is scored, the colored trail
will go back to the original small size.
e. Save - Save your completed exercise.
4. Increase the ball size by 10 each time the ball bounces off a paddle,
and reset the ball to its original size when a point is scored.
a. Starting point - Exercise 3 project.
b. Save As - Add “EX4” at the end of your original filename
(use “File>Save Project”).
c. Code hint - Use the “change size by 10” block to increase
ball size. Use the “set size to 50%” block to reset the ball
to its original size.
d. Test - Each time the ball bounces off the paddle, it should
get larger. When a point is scored, the ball should return
to the size that it was at the start of the game.
e. Save - Save your completed exercise.
5. Switch between two new costumes (can be silly ones like bananas)
when points are scored.
a. Starting point - Original Paint Pong project.
b. Save As - Add “EX5” at the end of your original filename
(use “File>Save Project”).
c. Code hint - For the ball sprite, on the Costumes tab, under
“New costume”, left-click the left-most icon (inside the
red circle in Figure 204). The “Costume Library” window
will be shown. Scroll down the window and left-click on
any costume that you want to use. Then left-click on the
OK button to add it to the ball sprite’s set of costumes.
Repeat these steps to add a 2nd new costume. Click the
Scripts tab to return to the ball sprite code, and select the
costume that you want using the “switch costume to
<name>” block.
Figure 204 - Adding a new costume
d. Test - When points are scored, the ball’s costume should
switch between the two new costumes that you added.
e. Save - Save your completed exercise.
6. When either player reaches a score of 15, display “Player (1 or 2)
Won!” and stop the game.
a. Starting point - Exercise 1 project.
b. Save As - Add “EX6” at the end of your original
filename (use “File>Save Project”).
c. Code hint - Where the players score points, add the
following code (example shown below is for when
Player 1 scores a point):
Figure 205 - Game over
d. Test - The winner is declared when the first player reaches
15 points. The next game is started (with a score of 0-0)
when the green flag is clicked and the “s” key is pressed
again.
e. Save - Save your completed exercise.
7. Add controls to select one of 3 different ball speeds (easy, medium,
hard).
a. Starting point - Exercise 6 project.
b. Save As - Add “EX7” at the end of your original
filename (use “File>Save Project”).
c. Code hint
i. Instructions sprite
1. Update the Instructions sprite to add
the following line at the bottom, to
show the keys that are pressed to
select the ball speed:
a. “(e=easy, m = medium, h =
hard)”
Figure 206 - Update the Instructions sprite
Figure 207 - Instructions sprite
ii. Ball sprite
1. Select the “Data” block type, and click the
“Make a Variable” button. Create a variable
named “Ball Speed”. Make sure that the “For
all sprites” button is selected (as shown
below). This means that the variable can be
used by all sprites. Click the OK button.
Figure 208 - Create the Ball Speed variable
2. You will now see that the “Ball Speed” variable
is displayed on the stage. Drag it down to the
bottom center of the stage.
Figure 209 - Ball Speed variable on stage
3. Drag and drop the “Ball Speed” variable from
the Data block palette to the “move <number>
steps” block.
Figure 210 - Use the Ball Speed variable
iii. New sprites to show the ball speed selection
1. Click the icon (in red circle below) to choose
a new sprite from the library. Scroll down in
the list of sprites and select (left-click) a
sprite which is the letter “E”. Click the OK
button to create the sprite. Then repeat these
steps to create a sprite for the letter “M” and
the letter “H”. In this game, these letters
represent the ball speed (E = easy, M =
medium, H = hard) and one of them will be
shown on the stage to let the players see
which ball speed has been selected.
Figure 211 - Add new sprites to show ball speed selection
2. On the stage, you will see that these new sprites
have appeared. Drag them to the left of the
variable “Ball Speed” at the bottom of the stage.
We will add code later to shrink the size of these
letter sprites, and also to hide 2 of the 3 letter
sprites, so that the only one that is shown is the
one that the player has selected. So for now you
can place the sprites on top of each other at the
same location. The figure below shows the
placement of the “E” sprite. Don’t worry that
your letter sprites are big right now, we’ll fix that
in the code later.
Figure 212 - Stage with letter E (easy ball speed)
3. Select the “E” sprite (left-click it in the sprite list
in the lower left corner of the Scratch window).
Add the “E” sprite code shown in Figure 213
(section on left). Look at the code, and think
about what the 4 event handlers are doing. You
will want to set the Ball Speed variable to a
number that results in easy play. You might need
to try some different numbers before you find the
one that you like best. Notice that in addition to
setting the Ball Speed variable to the “easy”
number when the “e” key is pressed, we are also
setting the Ball Speed variable to the “easy”
number when the green flag is clicked so that the
game will operate in the easy mode if the players
do not select a ball speed.
4. Select the “M” sprite. Add the “M” sprite code
shown in Figure 213 (section in middle).
5. Select the “H” sprite. Add the “H” sprite code
shown in Figure 213 (section on right).
Figure 213 - Code for "E", "M", and "H" sprites
d. Test
i. Verify (check) that if no action is taken to change
the ball speed, that the game play starts with the
easy (slow) ball speed, and “E” is displayed at the
bottom of the stage.
ii. Verify that while the Instructions sprite is
displayed, pressing the “e”, “m”, and “h” keys
changes the ball speed variable value and also that
the associated letter (E, M, H) is displayed at the
bottom of the stage.
iii. Verify that while the ball is moving during game
play, pressing the “e”, “m”, and “h” keys changes
the ball speed appropriately and also that the
associated letter (E, M, H) is displayed at the
bottom of the stage.
e. Save - Save your completed exercise.
Chapter 13: Project - Rocket
Pilot
Rocket Pilot is a game where you control a rocket that flies around popping
balloons. You can pop the blue and purple balloons. But you should avoid
the yellow balloons, because if you hit one, your rocket will explode. Also,
if your rocket crashes into the ground, it will explode. You score a point for
each balloon that you pop.
As with all Scratch games, you first start by clicking the green flag. One
thing that is different in this game from the first two games that you coded
(Quick Draw Cat, Paint Pong) is that you can play this game multiple times
without clicking the green flag. If your rocket explodes (from hitting a
yellow balloon or the ground), the message “GAME OVER!” is displayed
and the score is reset to zero, but you can launch the rocket again (by
pressing the space bar on your keyboard) and keep playing as long as you
want.
REQUIREMENTS :
1. Game instructions are shown when the green flag is clicked.
2. The game has one player and starts when the “s” key is pressed.
3. The game has a background with ground at the bottom and sky
above.
4. The rocket is launched from the ground when the space bar is
pressed.
5. The rocket is steered by pressing the “left arrow” and “right arrow”
keys.
6. Three balloons (blue, purple, yellow) start floating when the “s” key
is pressed.
7. When the rocket hits a blue or purple balloon, the balloon pops, a
point is scored, and after a short delay the balloon reappears at its
starting position and continues floating.
8. If the rocket hits a yellow balloon, the rocket explodes, the score is
reset to zero, and the rocket reappears at its launch position. NOTE:
The yellow balloon does not pop.
9. If the rocket crashes into the ground, the rocket explodes, the score
is reset to zero, and the rocket reappears at its launch position.
DESIGN (Sprite definition) :
The sprites are:
1. Instructions
2. Rocket
3. Blue Balloon
4. Purple Balloon
5. Yellow Balloon
Figure 214 - Sprites (Rocket Pilot)
SPRITE #1: Instructions
DESIGN (Instructions):
1. When the green flag is clicked:
a. Show sprite.
2. When the “s” key is pressed:
a. Hide sprite.
CODE & TEST (Instructions):
Create a new project and select a background with ground and a sky.
Figure 215 - Create the project
Create the Instructions sprite.
Figure 216 - Create the Instructions sprite
Figure 217 shows how to adjust the position of the instructions text on the
stage.
Figure 217 - How to adjust the text position
Add the code for the Instructions sprite and run a test.
Figure 218 – Instructions sprite code & Test A
SPRITE #2: Rocket
DESIGN (Rocket):
1. When the green flag is clicked:
a. Hide sprite.
b. Set the pop count to zero.
c. Set the rocket size and costume.
d. Set the rocket’s launch position on the ground with nose
up.
2. When the “s” key is pressed:
a. Show sprite.
3. When the space bar pressed:
a. If the game has started (by the player pressing the “s”
key):
i. Loop forever, doing the following:
1. Move the rocket forward a few steps.
2. If the rocket is touching a yellow
balloon or the ground:
a. Play explosion sound.
b. Show animation of rocket
explosion (costume changes).
c. Hide sprite.
d. Display message “GAME
OVER!”.
e. Reset the pop count to zero.
f. Set the rocket back to its launch
position.
g. Set costume back to rocket.
h. Show sprite.
i. Stop the forever loop.
4. When the “left arrow ” key pressed:
a. Turn left 3 degrees.
5. When the “right arrow ” key pressed:
a. Turn right 3 degrees.
CODE & TEST (Rocket):
Create the Rocket sprite.
Figure 219 – Paint a sprite
Draw the rocket costume.
Figure 220 – Draw the rocket
Figure 221 – Add nose to rocket
Figure 222 – Attach nose to rocket
Figure 223 - Add back edge of tail fins
Figure 224 – Finish outline of tail fins
Figure 225 – Add engine flames
Figure 226 – Color in tail fins with white
Draw the two costumes for the rocket explosion. The names of those new
costumes will be “big explosion” and “small explosion”.
As shown in Figure 227 below, we’ll create an animation for the rocket
explosion, where the Rocket sprite starts with the “rocket” costume, then
switches to the “big explosion” costume for a small amount of time, then
switches to the “small explosion” costume for a small amount of time, and
finally the Rocket sprite is hidden. After the rocket explosion is complete,
the Rocket sprite will reappear at its launch point (with the rocket costume),
ready to be launched again.
Figure 227 - Animation of rocket explosion
Figure 228 – Add rocket explosion costumes (big and small)
Sprite variables – In the Rocket Pilot project, we will use a lot of
variables. Using variables is necessary for data that is shared by several
sprites such as “pop count”. Using variables can also help to make your
code easier to read and understand because instead of seeing a number in
your code, you see the words that describe what the number represents (like
“start delay” or “x step value”). Using variables also helps you organize the
data that you might want to customize in your code. For example, we are
setting all of our variables to their starting values (also called “variable
initialization”) when the green flag is clicked for a sprite. That provides you
with one place to go to customize the values of the variables in a sprite’s
code, rather than having different numbers spread around throughout your
code. As you work on this project, you will see how this is helpful,
especially when we are customizing the code for the different colored
balloons to make them behave slightly different.
Variable Scope – The word scope refers to whether a variable is visible to
only one sprite (called a “private” variable) or whether it is shared by all of
the sprites. As mentioned earlier, the variable “pop count” is shared among
all of the sprites. Any sprite can set or read the “pop count” variables. We
want each balloon sprite to be able to up the game’s pop count when it
pops. A shared variable is only created once for one sprite, and it will
automatically appear in the variables list for all other sprites. Figure 229
below lists all of the variables used in the Rocket Pilot project, and it shows
which variables are shared (green dashed line) and private (red dashed line).
Notice that the “For all sprites” selection (in the “New Variable” popup
window) is used for the shared variables, and the “For this sprite only”
selection is used for private variables.
Customization of sprites using variables – In Figure 229 , you can see
that the three balloon sprites (blue, purple, yellow) have variables with the
same names. In the case of the private variables (inside the red dashed box),
the variables can be assigned different values for each of the three balloon
sprites. This allows the three balloon sprites to have very similar code, but
their behavior can be made different by setting some of the private variables
to different numbers. For example, you can see in Figure 229 that the “start
delay” variable has different values for each balloon sprite. The start delay
is the number of seconds that passes before the balloon starts floating after
the game starts (or the balloon pops). Having different start delays for the
three balloons causes them to be spread out as they float on the stage. If all
of the balloons had the same start delay, then they would be all clumped
together as they started floating, and that would not be very good.
Figure 229 - Variables for Rocket Pilot project
Note that the table shown in Figure 229 on the previous page is not
something that you will see in the Scratch user interface. The table is a
combination of variable lists from the four different sprites, and I created
the table to help explain what variable scope is and how variables are used
in this project.
You might wonder how you can see what the scope (shared or private) is for
a variable after you have created it. The left side of Figure 230 shows how
you can tell which variables are shared and which are private. When you
look at a pulldown menu of variables, the ones above the black separator
line are the shared variables, and the ones below the line are the private
variables. However, if all of the variables have the same scope, then you
can’t determine which scope they are. If you decide that you want to change
the scope of a variable, you must delete the variable and then recreate it
with the correct scope (shown on the right side of Figure 230 ).
Figure 230 - Viewing and changing variable scope
Create the variables for the rocket sprite.
Figure 231 - Create variables for rocket sprite
Add the code for the Rocket sprite (Figure 232 ). Figure 233 and Figure
234 show more code details.
NOTE: I selected a turn angle of 3 degrees for the rocket so that it flies in a
way that is realistic for a real rocket (when running this code on a
Raspberry Pi 4 Model B computer). Real rockets don’t turn very quickly. If
you feel that the rocket is not turning as fast as you want, you can increase
the turn angle to a number larger than 3 degrees.
Figure 232 – Rocket sprite code
Figure 233 – Rocket sprite code details
Figure 234 – Rocket sprite code details (continued)
Test – The rocket is launched by pressing the space bar, and is steered in
flight by the left and right arrow keys. NOTE: You can fly the rocket in a
tight loop by pressing and holding down the right or left arrow key.
Figure 235 – Test B
Figure 236 – Requirements (after Test B)
SPRITE #3: Blue Balloon
DESIGN (Blue Balloon):
1. When green flag is clicked:
a. Hide sprite.
b. Set the balloon size and costume.
c. Set the variables for the floating area.
d. Set the balloon starting position.
2. When “s” key is pressed:
a. Wait for the “start delay” time.
b. Show sprite.
c. Loop forever, doing the following:
i. Move the balloon a small distance along the
floating pattern.
ii. If the balloon has reached the top of the floating
area:
1. Set the balloon position back to its
starting point.
iii. If the balloon is touching the rocket:
1. Add one to the pop count.
2. Play a pop sound.
3. Show animation of the balloon popping
(costume changes).
4. Hide sprite.
5. Wait for the “start delay” time.
6. Set balloon position back to its starting
point.
7. Set costume back to balloon.
8. Show sprite.
CODE & TEST (Blue Balloon):
Create the Blue Balloon sprite.
Figure 237 - Create a balloon sprite
Set the sprite name to Blue Balloon, change the name of the blue balloon
costume to “balloon”, and delete the yellow and purple balloon costumes.
Figure 238 – Setting up the Blue Balloon sprite
To make the balloon look like it’s popping, we will add two new costumes
(big pop & small pop). This is similar to how we made the rocket explode
back in Steps 37 through 44.
Figure 239 – Adding the pop costumes
Figure 240 shows the area where balloons will float. The three balloons
will start at slightly different positions (indicated by the black dots in the
lower left corner). The red dashed rectangle shows the area where the blue
balloon will float. The blue balloon will not float outside of that area. The
purple and yellow balloons will float in almost the same area, but the
bottom edge of their floating areas will be a little lower, based on their
lower starting positions.
Figure 240 - Where do the balloons float?
A balloon will float sideways (horizontally) until it runs into an edge of the
floating area, then it will float up (vertically) a small number of steps, and
then reverse direction and float sideways. Figure 241 shows the code
blocks for moving sideways and reversing direction. NOTE: Wait until Step
59 to add this code.
Figure 241 – Floating pattern (moving right and left)
Figure 242 shows the code block for moving up. NOTE: Wait until Step
59 to add this code.
Figure 242 - Floating pattern (moving up)
We will use four variables to define the corners of the floating area (x min,
x max, y min, y max). Remember that the X-axis runs horizontally (the blue
double-headed arrow in Figure 243 ) and the Y-axis runs vertically (the
green double-headed arrow). Min is a short way to say minimum (meaning
the smallest), and max is a short way to say maximum (meaning the
largest).
Figure 243 - Variables for floating area (Blue Balloon)
Create the variables for the Blue Balloon sprite.
Figure 244 - Create variables for balloon sprite
Add the code for the Blue Balloon sprite (Figure 245 ). See code details on
the next two pages in Figure 246 , Figure 247 , and Figure 248 .
Figure 245 - Blue Balloon sprite code
Figure 246 – Event handler (green flag clicked)
Figure 247 - How to build the “if” block
Figure 248 – Event handler (s key pressed)
Test – The blue balloon floats through the sky and pops when the rocket
hits it. After popping, the balloon reappears and starts floating again from
the lower left area of the sky. When a balloon pops, a point is scored.
Figure 249 - Test C
SPRITE #4: Purple Balloon
DESIGN (Purple Balloon): Same design as the Blue Balloon sprite.
CODE & TEST (Purple Balloon):
Create the Purple Balloon sprite by duplicating (copying) the Blue Balloon
sprite. Change the name of the duplicated sprite to Purple Balloon.
Figure 250 – Create the Purple Balloon sprite
Delete the blue balloon costume and add the purple balloon costume from
the library.
Figure 251 – Add purple balloon costume
Update the costume name to “balloon”. After clicking the Scripts tab, notice
that all of the code has been copied (duplicated) from the Blue Balloon
sprite. Almost all of that code can be used without any changes. But there
are two customizations that we will do by changing the variable values for
“start delay” (to 2) and “y min” (to -70).
Figure 252 – Customize the Purple Balloon sprite code
Test – The purple balloon floats like the blue balloon, but it starts floating
two seconds after the blue balloon, and it’s starting position is slightly
lower. Both balloons can be popped by the rocket, and they both reappear
after popping. Popping either balloon scores a point. The score is displayed
on the stage.
Figure 253 – Test D
Figure 254 - Requirements (after Test D)
SPRITE #5: Yellow Balloon
DESIGN (Yellow Balloon): Same design as the other balloon sprites,
except that the yellow balloon doesn’t pop.
1. When green flag is clicked:
a. Hide sprite.
b. Set the balloon size and costume.
c. Set the variables for the floating area.
d. Set the balloon starting position.
2. When “s” key is pressed:
a. Wait for the “start delay” time.
b. Show sprite.
c. Loop forever, doing the following:
i. Move the balloon a small distance along the
floating pattern.
ii. If the balloon has reached the top of the floating
area:
1. Set the balloon position back to its
starting point.
CODE & TEST (Yellow Balloon):
Create the Yellow Balloon sprite by duplicating the Purple Balloon sprite.
Change the name of the duplicated sprite to Yellow Balloon.
Figure 255 – Create the Yellow Balloon sprite
Delete the purple balloon costume and add the yellow balloon costume
from the library.
Figure 256 - Set the costume to the yellow balloon
Change the costume name to “balloon”, and customize the sprite code by
changing “start delay” to 4 and “y min” to -80 .
Figure 257 – Customize the Yellow Balloon sprite code
Delete the code that pops the yellow balloon if it touches the rocket.
Figure 258 – Delete the pop code
Test – The three balloons float. The blue and purple balloons pop when hit
by the rocket. The yellow balloon does not pop when hit by the rocket.
Figure 259 – Test E
Back to the Rocket sprite - Add the code to make the rocket explode if it
touches the yellow balloon or crashes into the ground (Figure 260 ). After
exploding, display “Game Over!” and set the rocket back to the launch
position. See Figure 261 for details on how to build the if block to check if
the rocket should explode.
Figure 260 – Add code for rocket explosion
Figure 261 – How to build the “if” block
Test – The rocket explodes when it hits the yellow balloon or when it
crashes into the ground. When that happens, “GAME OVER!” is displayed
for two seconds, and then the rocket appears at its launch position on the
ground. The pop score is reset to zero. The balloons keep floating. The
message “Press the space bar to launch.” is displayed for two seconds, and
the rocket can be launched again by pressing the space bar.
Figure 262 – Test F
Figure 263 - Requirements completed
Save – Save your project as “Rocket Pilot”.
Chapter 14: Exercises -
Rocket Pilot
(see Chapter 16 for the answers)
1. After the blue balloon pops, it is smaller when it reappears. After
the purple balloon pops, it is faster when it reappears.
a. Starting point - Original Rocket Pilot project.
b. Save As - Add “EX1” at the end of your original filename
(use “File>Save Project”).
c. Code hints
i. To shrink the balloon, use the Looks block
“change size by -5”.
ii. To make the balloon faster, change the “x step
value” variable using the Data block “change x
step value by 1”.
d. Test – The blue balloon keeps getting smaller each time it
is popped, and the purple balloon keeps getting faster
each time it is popped.
e. Save - Save your completed exercise.
2. After the blue balloon pops, it is larger when it reappears.
a. Starting point - Exercise 1 project.
b. Save As - Add “EX2” at the end of your original filename
(use “File>Save Project”).
c. Code hints – None.
d. Test – The blue balloon keeps getting larger each time it is
popped.
e. Save - Save your completed exercise.
3. Add two more balloons (one blue, one purple).
a. Starting point – Original Rocket Pilot project.
b. Save As - Add “EX3” at the end of your original filename
(use “File>Save Project”).
c. Code hints
i. Start with your original Rocket Pilot project (do
not include the changes made in Exercise 1 or
Exercise 2).
ii. Right-click on the blue and purple balloons, and
select “duplicate”.
iii. Use a different starting y position (y min) for
each new balloon.
iv. Use a different start delay for each new balloon.
d. Test – There are two blue balloons, two purple balloons,
and one yellow balloon .
e. Save - Save your completed exercise.
4. Add Turbo Boost (the rocket flies faster for 5 second when the “t”
key is pressed).
a. Starting point – Exercise 3 project.
b. Save As - Add “EX4” at the end of your original filename
(use “File>Save Project”).
c. Code hints
i. Create a larger space for game play, by using
smaller sprites (rocket, balloons) and slowing
down the normal rocket speed. Set the following
variable values when the green flag is clicked:
1. Rocket size = 10%
2. Rocket speed = 2
3. Balloon size = 25% (for all balloon
sprites)
ii. One quick way to provide some simple
instructions to the player is to use a “say” block
for a sprite when the game is started. We’ll do
that in this exercise to tell the player how to
activate the Turbo Boost. In the Rocket sprite “s”
key event hander, add a block to say “Press t key
for Turbo Boost” for 2 seconds. (Figure 264. ).
Figure 264 - Show instructions for Turbo Boost
iii. For the Rocket sprite, add an event handler for the “t”
key (Figure 265. and Figure 266. ).
1. When the t key is pressed
a. Set rocket speed to 4 (fast “turbo”
speed)
b. Play a loud engine sound (we’ll use the
“car passing” sound)
c. Wait 5 seconds
d. Set rocket speed to 2 (back to normal
speed)
Figure 265 - Select a sound from the library
Figure 266 - Turbo Boost ("t" key event handler)
d. Test – The rocket and all of the balloons are smaller. When the
“t” key is pressed, the rocket moves faster for 5 seconds and
you hear the engine sound. NOTE: If you have trouble flying
the rocket, you can try changing the values used for rocket
speed and turn angles (left & right).
e. Save - Save your completed exercise.
5. Add a “High Score” feature. This will tell the player at the end of a
game if they have scored more points than any other game played
since the green flag was clicked.
a. Starting point - Exercise 4 project.
b. Save As - Add “EX5” at the end of your original filename
(use “File>Save Project”).
c. Code hints – In the Rocket sprite code:
i. Add a variable named “high score”. It can be a
private variable since it doesn’t need to be
shared with other sprites (select “For This Sprite
Only” when you create it).
ii. On the stage, drag and drop the high score
variable at the upper right corner.
Figure 267 - Move high score variable on stage
iii. Hide the “high score” variable and set it to 0 when the
green flag is clicked.
iv. Show the “high score” variable when the “s” key is
pressed to start the game.
v. Add the following code after the block that says “GAME
OVER!”:
1. If pop count > high score
a. Play a sound of your choice (from the
Sound Library)
b. Say “High Score!” for 2 seconds.
c. Set the “high score” variable to the pop
count.
Figure 268 - High score code
d. Test – At the end of a game, the player will see a message
“High Score!” (and hear a sound) if they have scored more
points than any other game since the green flag was clicked.
e. Save - Save your completed exercise.
6. Space Game – Change the game to be located in space, with robots
(instead of the blue and purple balloons) and a star (instead of the
yellow balloon).
a. Starting point - Exercise 5 project.
b. Save As - Add “EX6” at the end of your original filename
(use “File>Save Project”).
c. Code hints
i. Change the backdrop - In the lower left corner of
the Scratch window, choose the backdrop named
“space” from the library.
ii. Change the Balloon sprite costumes
1. For each Blue and Purple Balloon sprite,
add the “robot1” costume. Then in the
code, set the costume to “robot1”
everywhere that it is set to “balloon”.
2. For the Yellow Balloon sprite, add the
“star1” costume. Then in the code, set
the costume to “star1” everywhere that
it is set to “balloon”.
3. For the Yellow Balloon sprite, make it
larger by changing the size to 50% (was
25%).
Figure 269 - Space game
d. Test – The game backdrop is a space scene. The game plays
the same as in Exercise 5, but the blue and purple balloons are
robots and the yellow balloon is a star.
e. Save - Save your completed exercise.
Hurray! You have completed all of the projects and exercises in this
book! Now you can use your imagination and create your own exercises
which make some fun modifications to the projects in this book. You can
also create entirely new Scratch projects, using the software development
skills (requirements, design, code, test) that you have learned.
Additional project ideas:
1. Look at the sprites that are available in the Sprite Library. Those
sprites might spark an idea in your mind for a new game.
2. Look at the backdrops in the Backdrop Library, and see if they give
you an idea for a game.
3. Recreate part of a video game that you play on your phone,
computer or gaming console.
4. Create a game based on a story from a book, video or movie.
5. Create a simple game for a young friend or relative to play.
Want more?
Send an email to [email protected] to get notified of future
books.
Chapter 15: Backing Up Your
Work
Memory sticks (also called flash drives or thumb drives) are a cheap and
easy way to save copies of your Scratch project files. Project files are not
very large, and the smallest memory stick that you can buy will be fine.
Currently, the smallest memory stick that you can buy is 4 GB, and costs
about 5 dollars.
How to perform a backup:
Step 1 - Plug your memory stick into your powered Pi (Figure 270 ).
Figure 270 - Insert memory stick into powered Pi
Step 2 - A window will pop up stating “Removable medium is inserted”
(Figure 271 ). Left-click the OK button to open the memory stick contents
in a File Manager window.
Figure 271 – Window pops up when memory stick is inserted
Step 3 - Drag and drop your “My Code” folder from your desktop to the
memory stick’s File Manager window as shown in Figure 272 below.
Figure 272 – Copy “My Code” folder to memory stick
For your first backup to a memory stick, you will see your “My Code”
folder appear in the File Manager window (Figure 273 ).
Figure 273 - "My Code" folder copied to memory stick
Step 3a - If you have backed up your “My Code” folder before, you will
see a “Confirm File Replacing” window, and be asked if you want to
overwrite the existing folder on your memory stick. Left-click the checkbox
that reads “Apply this option to all existing files” (Figure 274 ).
Step 3b – Left-click the “Overwrite” button (Figure 274 ).
Figure 274 – Confirm you want to overwrite (if already exists)
Step 4 – Double left-click the “My Code” folder (or single left-click and
press the Enter/Return key) to open the folder (Figure 275 ).
Step 5 – Verify that your files are present (Figure 275 ).
Step 6 – Left-click the “X” button to close the File Manager window
(Figure 275 ).
Figure 275 - Verify that files were copied
Step 7 – Before removing your memory stick from your Pi, you must first
perform a step called “ejecting” the memory stick. If you skip this step and
just unplug your memory stick, the files on your memory stick might
become damaged. First, left-click the “Eject” icon in the upper right corner
of the desktop (Figure 276 ).
Step 8 – In the menu that pops up, left-click the item that corresponds to
your memory stick (Figure 276 ).
Step 9 – Unplug your memory stick from your Pi and store it in a safe
place.
Figure 276 – Eject and remove memory stick
Chapter 16: Exercise Answers
1. Quick Draw Cat
a. Exercise 1 (Use a pen size of 20 when walking right)
Figure 277 - Exercise 1 Code (Quick Draw Cat)
Figure 278 - Exercise 1 Test (Quick Draw Cat)
b. Exercise 2 (Use pen size of 100 when walking in all
directions)
Figure 279 - Exercise 2 Code (Quick Draw Cat)
Figure 280 - Exercise 2 Test (Quick Draw Cat)
c. Exercise 3 (Change pen shade by 5 with each step)
Figure 281- Exercise 3 Code (Quick Draw Cat)
Figure 282 - Exercise 3 Test (Quick Draw Cat)
d. Exercise 4 (Increase pen size with each step)
Figure 283 - Exercise 4 Code (Quick Draw Cat)
Figure 284 - Exercise 4 Test (Quick Draw Cat)
e. Exercise 5 (Control the pen using letter keys)
Figure 285 - Exercise 5 Code (Quick Draw Cat)
Figure 286 - Exercise 5 Test (Quick Draw Cat)
How to draw “CAT” with blue background and yellow text:
a. Click the green flag
b. Press “b” to set the pen color to blue.
c. Press “d” to place the pen down, ready to draw.
d. Using the arrow keys, walk the cat around the stage until it
is totally colored blue.
e. Press “u” to lift the pen up.
f. Press “y” to set the pen color to yellow.
g. Using the arrow keys, walk the cat to the position where
you want to start drawing the letter “C.” (NOTE: Nothing
will be drawn, since the pen is lifted up).
h. Press “d” to place the pen down, ready to draw.
i. Using the arrow keys, walk the cat in the shape of the letter
“C.”
j. Press “u” to lift the pen up.
k. Using the arrow keys, walk the cat to the position where
you will start drawing the letter “A.”
l. Press “d” to place the pen down, ready to draw.
m. Using the arrow keys draw the letter “A.”
n. Press “u” to lift the pen up.
o. Using the arrow keys, walk the cat to the position where
you will start drawing the letter “T.”
p. Press “d” to place the pen down, ready to draw.
q. Using the arrow keys draw the letter “T.”
r. Press “u” to lift the pen up.
s. Using the arrow keys, walk the cat away from the letter
“T.”
2. Paint Pong
a. Exercise 1 (Play a drum sound when a point is scored)
Figure 287 - Exercise 1 Code Change (Paint Pong)
b. Exercise 2 (Change ball color each time a point is scored)
Figure 288 - Exercise 2 Code Change (Paint Pong)
c. Exercise 3 (Increase the pen size by 1 during each forever
loop, and reset the pen size to 1 when a point is scored).
Figure 289 - Exercise 3 Code Change (Paint Pong)
d. Exercise 4 (Increase the ball size by 10 each time the ball
bounces off a paddle, and reset the ball to its original size
when a point is scored)
Figure 290 - Exercise 4 Code Change (Paint Pong)
e. Exercise 5 (Switch between two new costumes when points
are scored)
Figure 291 - Exercise 5 Code Change (Paint Pong)
f. Exercise 6 (Display “Player (1 or 2) Won!” and stop the
game when a player reaches 15 points)
Figure 292 - Exercise 6 Code Change (Paint Pong)
g. Exercise 7 (Add controls to select one of 3 different ball
speeds)
Figure 293 - Exercise 7 Code Change (Paint Pong)
Figure 294 - Exercise 7 Code Change (Paint Pong) – continued
3. Rocket Pilot
a. Exercise 1 (After the blue balloon pops, it is smaller when it
reappears. After the purple balloon pops, it is faster when it
reappears)
Figure 295 - Exercise 1 Code Change (Rocket Pilot)
Figure 296 - Exercise 1 Test (Rocket Pilot)
b. Exercise 2 (After the blue balloon pops, it is larger when it
reappears)
Figure 297 - Exercise 2 Code Change (Rocket Pilot)
Figure 298 - Exercise 2 Test (Rocket Pilot)
c. Exercise 3 (Two more balloons)
Figure 299 - Exercise 3 Code Change (Rocket Pilot)
Figure 300 - Exercise 3 Test (Rocket Pilot)
d. Exercise 4 (Turbo boost)
Figure 301 - Exercise 4 Code Change (Rocket Pilot)
Figure 302 - Exercise 4 Test (Rocket Pilot)
e. Exercise 5 (High score)
Figure 303 - Exercise 5 Code Change (Rocket Pilot)
Figure 304 - Exercise 5 Test (Rocket Pilot)
f. Exercise 6 (Space game)
Figure 305 - Exercise 6 Code Change (Rocket Pilot)
Figure 306 - Exercise 6 Test (Rocket Pilot)
ACKNOWLEDGEMENT
Scratch is a project of the Scratch Foundation, in collaboration with the
Lifelong Kindergarten group at the MIT Media Lab. It is available for free
at https://scratch.mit.edu.
Raspberry Pi is a trademark of The Raspberry Pi Foundation (UK
Registered Charity 1129409). See https://www.raspberrypi.org.
Reviewers (Students):
Isaac Andaluz
Joan Andaluz
Naomi Andaluz
Dave Anderson
Chloe Sow
Charlize Sow
Reasha Vora
Reviewers (Engineers):
Alan Altman
Larry Kucera
Ignatius “Stock” Stockhausen
Fay Trowbridge
Heather Van Steenburgh
Game Testers:
Alana Andaluz
Maria Andaluz
Custom Artwork & Cover Design:
Scott Trowbridge
Graphic Design Consultant:
Barbara Hartinger
ABOUT THE AUTHOR
Grant Williams
Grant Williams has a BS degree in Computer Science and has worked for
over 30 years as a software engineer in the aerospace and
telecommunications industries. When his niece Megan’s children reached
the age when they could start learning about computers, Grant thought that
the Raspberry Pi would be an ideal child-friendly computer to teach them
with, and that Scratch would be a great introductory coding language. He
set up a “Raspberry Pi Coding Lab” in their home, and started teaching
them how to code using Scratch. Driven by the kids’ enthusiasm, that
activity evolved into him writing this book.