Scratch 2.0 Beginner S Guide, 2nd Edition

User Manual: Pdf

Open the PDF directly: View PDF PDF.
Page Count: 296 [warning: Documents this large are best viewed by clicking the View PDF Link!]

www.allitebooks.com
Scratch 2.0 Beginner's Guide
Second Edition
Create digital stories, games, art, and animaons through
six unique projects
Michael Badger
BIRMINGHAM - MUMBAI
www.allitebooks.com
Scratch 2.0 Beginner's Guide
Second Edition
Copyright © 2014 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system,
or transmied in any form or by any means, without the prior wrien permission of the
publisher, except in the case of brief quotaons embedded in crical arcles or reviews.
Every eort has been made in the preparaon of this book to ensure the accuracy of the
informaon presented. However, the informaon contained in this book is sold without
warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers
and distributors will be held liable for any damages caused or alleged to be caused directly or
indirectly by this book.
Packt Publishing has endeavored to provide trademark informaon about all of the
companies and products menoned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this informaon.
First Published: July 2009
Second Edion: April 2014
Producon Reference: 1080414
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78216-072-4
www.packtpub.com
Cover Image by Ross Manges (ross@rossmanges.net)
www.allitebooks.com
Credits
Author
Michael Badger
Reviewers
Samyak Bhuta
Manuel Menezes de Sequeira
Franklin Webber
Acquision Editor
Joanne Fitzpatrick
Content Development Editor
Dayan Hyames
Technical Editors
Shubhangi Dhamgaye
Shweta Pant
Mrunmayee Pal
Aman Preet Singh
Copy Editors
Sarang Chari
Brandt D'Mello
Mradula Hegde
Project Coordinator
Binny K. Babu
Proofreaders
Simran Bhogal
Maria Gould
Ameesha Green
Paul Hindle
Indexer
Mehreen Deshmukh
Producon Coordinator
Nitesh Thakur
Cover Work
Nitesh Thakur
www.allitebooks.com
About the Author
Michael Badger is a writer and technical communicator who has worked in a range of
technical roles, including support, automated soware tesng, and project management.
He has authored several books for Packt Publishing, including Scratch 1.4 Beginner's Guide.
He also authors a regular Scratch column for Raspberry Pi Geek Magazine, which focuses on
Scratch 1.4.
I'd like to thank the team at Packt Publishing for pung up with me and
helping me make this revision the best it could be. My loving wife Chrise
and son Cameron also deserve credit for allowing me the exibility to
complete this book.
www.allitebooks.com
About the Reviewers
Samyak Bhuta is fascinated by art and technology and is always excited when they
both meet. He is a soware architect by profession with over a decade of experience.
He started programming in his childhood with GWBasic and quickly moved over to QBasic.
Professionally, he has worked on Java, JavaScript, Python, and PHP. He enjoys coding user
interfaces as well as working on backend programming. Samyak believes in the open source
philosophy and has been acve in his local community. He loves to eat dal ba, an Indian
dish, and has dreams to become a aust.
I would like to thank Packt Publishing for keeping paence when I couldn't
submit my reviews on me.
Manuel Menezes de Sequeira has been teaching programming since 1995. He started
teaching programming using C, then moved to C++, and later to Java. Nowadays, in his
lectures, he usually starts programming with Scratch and Snap!, and then moves on to
text-based languages such as Java. Manuel teaches at the Universidade Europeia | Laureate
Internaonal Universies in Lisbon, Portugal, where he also champions in CoderDojo LX, the
Lisbon-based CoderDojo, where children can learn to program for free while having fun. He
lives in Lisbon, Portugal, and has been involved for a few years in the translaon of Scratch,
SNAP!, and other projects to Portuguese.
Franklin Webber is a soware professional whose professional experience comes from
a tesng background where he sought to automate himself out of a job. A college teaching
assistant once told Frank that he was a great soware developer and a terrible computer
scienst, and that the soware he wrote cared more for the user experience than the
size of its Big O Notaon. As a soware developer, he became the resident generalist who
was always willing to step up to learn new technologies. He now spends most of his me
teaching soware design to students, both young and old.
www.allitebooks.com
www.PacktPub.com
Support les, eBooks, discount offers, and more
You might want to visit www.PacktPub.com for support les and downloads related to
your book.
Did you know that Packt oers eBook versions of every book published, with PDF and ePub
les available? You can upgrade to the eBook version at www.PacktPub.com and as a print
book customer, you are entled to a discount on the eBook copy. Get in touch with us at
service@packtpub.com for more details.
At www.PacktPub.com, you can also read a collecon of free technical arcles, sign up
for a range of free newsleers and receive exclusive discounts and oers on Packt books
and eBooks.
TM
http://PacktLib.PacktPub.com
Do you need instant soluons to your IT quesons? PacktLib is Packt's online digital book
library. Here, you can access, read and search across Packt's enre library of books.
Why Subscribe?
Fully searchable across every book published by Packt
Copy and paste, print and bookmark content
On demand and accessible via web browser
Free Access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access
PacktLib today and view nine enrely free books. Simply use your login credenals for
immediate access.
www.allitebooks.com
Table of Contents
Preface 1
Chapter 1: Welcome to Scratch 2.0 7
About Scratch 8
Encouraging everyone to think programmacally 8
Sample Scratch uses 9
Computaonal thinking 9
Finding a project for you 10
Making animaons 10
Telling stories 11
Building games 12
Programming games of chance 12
Creang art projects 13
Sensing the real world 13
Programming concepts 13
Using Scratch 2.0 15
Looking inside a Scratch project 17
The stage area 18
The sprites pane 18
The scripts area 18
The built-in image editor 20
Using Scratch 2.0 oine 21
Encountering Scratch 1.4 22
Tinkering encouraged 22
Summary 23
www.allitebooks.com
Table of Contents
[ ii ]
Chapter 2: A Quick Start Guide to Scratch 25
Joining the Scratch community 25
Time for acon – creang an account on the Scratch website 26
Time for acon – understanding the key features of your account 28
Abiding by the terms of use 30
Creang projects under Creave Commons licenses 30
Finding free media online 30
Taking our rst steps in Scratch 31
Time for acon – moving the cat across the stage 31
Using events to trigger an acon 33
Time for acon – animang a walking moon with the cat 33
Understanding the basics of a Scratch Project 35
Saving early, oen, and automacally 36
Time for acon – saving our work 36
Undoing a deleon 37
Introducing forever loops 37
Time for acon – seng the cat in moon, forever 37
Controlling a sprite with loops 39
Time for acon – ipping the cat right-side up 39
Clicking on a block runs the command 41
Adding sprites to the project 41
Time for acon – adding a second sprite and script 42
Reviewing a video-sensing project 44
Time for acon – reviewing pop the balloon - video starter 44
Sensing video 46
Summary 47
Chapter 3: Creang an Animated Birthday Card 49
Introducing the paint editor 50
Time for acon – painng a happy birthday sprite 50
Changing the size of a bitmap image 52
Choosing bitmap or vector images 53
Time for acon – drawing a vector image 53
Changing the size of the vector image 54
Reviewing the image eding tools 55
Erasing in the vector mode 56
Filling the stage with color 57
Time for acon – using the ll with color tool to paint the stage 57
Adding gradients 59
Time for acon – applying a gradient 59
Time for acon – adding more sprites to address the card 61
Inializing a sprite's starng values 62
www.allitebooks.com
Table of Contents
[ iii ]
Time for acon – hiding all sprites when the ag is clicked 62
Time for acon – displaying happy birthday 64
Specifying memorable names and comments 66
Time for acon – renaming sprites 66
Inserng comments into our code 67
Time for acon – adding comments to a script 67
Transforming sprites with graphical eects 68
Time for acon – transforming sprites 68
Graphical transformaons 71
Comparing the repeat and forever blocks 72
Time for acon – turning m in a circle 73
Time for acon – making a sprite fade in with the ghost eect 74
Two ways to control ming 76
Summary 78
Chapter 4: Creang a Scratch Story Book 79
Designing the outline of a barnyard joke book 79
Time for acon – designing a clickable table of contents 80
Time for acon – adding pages to the book 81
Time for acon – adding a sprite to the Backpack 83
Using the Backpack to store sprites and scripts 84
Building a joke with say blocks and sounds 85
Time for acon – making a horse talk with the say block 85
Time for acon – synchronizing and animang the horse 86
Time for acon – imporng a horse sound 87
Playing supported sound formats 89
Posioning a sprite by its coordinates 89
Time for acon – moving the dog based on x and y coordinates 89
Locang sprites with x and y coordinates 91
Creang a new costume 93
Time for acon – duplicang, ipping, and switching a sprite's costume 93
Comparing costumes to sprites 94
Composing custom sound eects 95
Time for acon – creang drum sound eects 96
Creang sound eects and music 96
Time for acon – integrang the dog's joke sequence 98
Navigang the story and coordinang scenes 100
Time for acon – hiding the table of contents 100
Time for acon – displaying the dog scene 101
Coordinang scenes by backdrop name 102
Time for acon – navigang back to the table of contents 103
Summary 105
www.allitebooks.com
Table of Contents
[ iv ]
Chapter 5: Creang a Mulmedia Slideshow 107
Imporng photos as backdrops 107
Time for acon – imporng photos from les 108
Working with images 111
Resizing images 112
Using cauon while resizing images 112
Adding slideshow controls to display images 114
Time for acon – ipping through the photos 114
Related backdrop blocks 116
Playing and recording sounds 118
Time for acon – adding a sound from Scratch's library 118
Time for acon – recording sounds in the sound editor 119
Understanding sound related blocks 122
Eding sounds 123
Time for acon – eding a recorded sound 123
Time for acon – appending a sound 124
Time for acon – adding sound eects to recordings 125
Reviewing available sound eects 126
Using x and y coordinates to nd the posion of the mouse's pointer 126
Time for acon – using mouse locaon to hide arrows 127
Time for acon – providing user instrucons 130
Displaying a project in presentaon mode 131
Time for acon – presenng a fullscreen slideshow 132
Summary 134
Chapter 6: Making an Arcade Game – Breakout (Part I) 135
Learning about the Breakout game 135
Discovering Pong 136
Time for acon – imporng and playing the Pong starter project 136
Remixing a legacy Scratch project 138
Moving a sprite with the mouse or arrows 138
Using reporter blocks to set values 138
Customizing the gameplay of the Pong project 139
Time for acon – adding the le and right arrow controls 139
Evaluang the y posion of the ball to end the game 140
Time for acon – determining if the ball is below the paddle 140
Time for acon – adjusng the center of a sprite costume 142
Cloning to create idencal sprites 144
Time for acon – drawing bricks 144
Time for acon – cloning bricks 145
Dealing with the cloned sprite 147
Table of Contents
[ v ]
Time for acon – breaking bricks when I start as a clone 147
Cloning explained 149
Rapid re shoong with cloning 149
Cloning related blocks 150
Ricocheng with the point in direcon block 151
Time for acon – changing a sprite's direcon 151
Figuring out the direcon 153
Time for acon – seng the starng posion and the direcon 153
Time for acon – ricocheng o bricks 154
Condional statements 156
Condional statements in real life 157
Dening a variable to keep score 157
Time for acon – adding a score variable 158
Seng variables For all sprites 159
Seng variables For this sprite only 160
Summary 161
Chapter 7: Programming a Challenging Gameplay – Breakout (Part II) 163
Implemenng lives 164
Time for acon – adding a variable to track lives 164
Time for acon – checking for game over 165
Evaluang mulple programming soluons 167
Adding more bricks to the level with a custom block 169
Time for acon – creang a second brick 169
Time for acon – drawing rows of bricks with custom blocks 170
Introducing procedures by way of custom blocks 173
Seng custom block inputs 173
Time for acon – coordinang the ball play 176
Increasing ball speed and diculty 177
Time for acon – increasing ball speed 177
Using Boolean evaluaons 179
Keeping score based on a clone's costume 180
Time for acon – decreasing the paddle size based on the clones' costume 180
Considering alternave soluons 183
Time for acon – detecng when we clear the level 184
Keeping the score using cloud variables 186
Time for acon – keeping a global scoreboard 186
Understanding cloud variables in Scratch 2.0 188
Viewing the cloud data log 188
Summary 190
Table of Contents
[ vi ]
Chapter 8: Chang with a Fortune Teller 191
Creang, imporng, and exporng lists 192
Time for acon – creang lists to store mulple values 192
Working with an item in a list 194
Imporng a list 195
Time for acon – imporng fortunes to a list 195
Exporng a list from Scratch 197
Prompng the player for a queson 197
Time for acon – asking a queson 197
Using stored quesons 200
Time for acon – validang the seeker's queson 200
Deleng the list values 201
Selecng a random fortune 202
Time for acon – selecng a random fortune 202
Time for acon – counng our fortunes with mod 203
Using magic numbers 206
Creang a custom say fortune block 206
Time for acon – creang a custom say fortune block 207
Using the if () then else block 208
Manipulang the text 209
Time for acon – ensuring grammacally correct quesons 209
Tesng your project 210
Creang a keyword scanner 211
Time for acon – scanning a text string to build a list of words 211
Summary 215
Chapter 9: Turning Geometric Paerns into Art Using the Pen Tool 217
Drawing basic shapes 218
Time for acon – drawing our rst square 218
Time for acon – building on the square 220
Drawing user-dened shapes 221
Time for acon – enabling the user to create custom shapes 222
Time for acon – turning triangles into pinwheels 224
Dening procedures for home and shapes 226
Time for acon – creang a custom shapes procedure 226
Plong the coordinates of shapes 228
Time for acon – plong x,y coordinates to draw a square 229
Understanding and using color 230
Time for acon – coloring our shapes 230
Understanding color shades 232
Working with the set pen color to () block 232
Table of Contents
[ vii ]
Time for acon – nding a color picker workaround 232
Finding a color to use by its number 233
Time for acon – creang a color palee 234
Adding color slider inputs to the shapes project 237
Time for acon – liming color values with a slider 237
Creang asymmetrical paerns 239
Time for acon – creang an explosion 240
Turning straight lines into string art 242
Time for acon – animang a radar screen 242
Time for acon – breaking out of the circle 244
Summary 246
Appendix A: Connecng a PicoBoard to Scratch 1.4 247
Using Scratch 1.4, the PicoBoard, and Raspberry Pi 248
Finding Scratch 1.4 248
Purchasing the PicoBoard 248
Time for acon – enabling and tesng the PicoBoard support in Scratch 1.4 249
Adding the PicoBoard support to Scratch 2.0 250
Animang webcam images by detecng sound 251
Time for acon – creang a talking head 251
Sharing Scratch 1.4 projects online 254
Sensing the environment with the PicoBoard 254
Measuring resistance 254
Time for acon – recording the resistance of a thermistor over me 255
Compleng a circuit 257
Time for acon – charng our measurements 258
Interpreng the graph 261
Time for acon – revising the graph 262
Summary 264
Appendix B: Pop Quiz Answers 265
Index 269
Preface
This book demyses Scratch programming through a variety of projects. The book assumes
that you have no programming experience when you begin reading, but by the me you
reach the last page, you will be ready to explore your own projects and help other people
with Scratch.
The projects start with simpler concepts and get progressively more complicated in terms of
programming concepts and design. You will learn how to make mulple-scene stories, think
through the logic of a fast-paced arcade game called Breakout, interact with a snarky fortune
teller, and more. The book's projects tend to demonstrate a programming concept rst and
then discuss the concept in more detail.
You will receive a balanced introducon to Scratch and universal programming concepts as
you create digital stores, animaons, and games. With a rm grasp on the fundamentals,
you'll be ready to take on more advanced topics and projects.
What this book covers
Chapter 1, Welcome to Scratch 2.0, introduces Scratch and the various types of projects
covered in the book.
Chapter 2, A Quick Start Guide to Scratch, takes us on a tour of the online Scratch
community. In this chapter, we will create our rst Scratch animaon while learning basic
programming concepts such as loops.
Chapter 3, Creang an Animated Birthday Card, will guide us through how to use Scratch's
built-in paint editor to draw bitmap and vector images. To create the card, we will learn
important programming concepts such as project inializaon, object naming, and event
coordinaon.
Chapter 4, Creang a Scratch Story Book, will guide us through how to build a joke book and
coordinate scene changes as a way to navigate through the book. The chapter introduces
sound and coordinates as a way to move sprites.
Preface
[ 2 ]
Chapter 5, Creang a Mulmedia Slideshow, will guide us through how to create a
personalized slideshow by uploading les from our computer. We will also work on
resizing images and recording slide narraons that can be played on demand.
Chapter 6, Making an Arcade Game – Breakout (Part I), remixes the classic Pong game into
our own brick-busng version called Breakout. We'll clone sprites, esmate direcon, and
create custom variables to develop the framework of the game.
Chapter 7, Programming a Challenging Gameplay – Breakout (Part II), builds on our
Breakout game from the previous chapter. Here, we make the gameplay more challenging by
programming the ball speed and reducing the paddle size based on the gameplay. Important
concepts include custom procedures, Boolean values, and cloud data.
Chapter 8, Chang with a Fortune Teller, deals with our game of fortune, where a fortune
teller will provide a random fortune in response to the user's typed queson. We will work
with lists, track intervals with mod, and split words apart to idenfy individual words.
Chapter 9, Turning Geometric Paerns into Art Using the Pen Tool, combines all the
programming concepts we've learned so far to draw art using simple math equaons,
polygons, and string art. The projects will show you how to take user-dened values and turn
them into shapes. This chapter also explains how to apply color and shades to Scratch projects.
Appendix A, Connecng a PicoBoard to Scratch 1.4, emphasizes on projects that use a
computer's webcam and the PicoBoard, which is an add-on device capable of running on
Scratch 1.4 on the Raspberry Pi. The PicoBoard project incorporates an experiment that
measures the resistance of warming water using a thermistor and generates graphs for it.
What you need for this book
To create projects using the Scratch 2 project editor, you need a relavely recent web
browser (Chrome 7 or later, Firefox 4 or later, or Internet Explorer 7 or later) with Adobe
Flash Player Version 10.2 or later installed. Scratch 2 is designed to support a screen
resoluon of 1024 x 768 or larger. If your computer doesn't meet these requirements,
you can try downloading and installing Scratch 1.4, which you can sll use to share
projects to the Scratch 2 website.
An oine Scratch 2 editor is also available. You can also sll use Scratch 1.4. Note that you
can have both Scratch 1.4 and 2 on your computer.
The soware to download are as follows:
The Scratch 2 oine editor can be downloaded from the following link:
http://scratch.mit.edu/scratch2download
The Scratch 1.4 editor can be downloaded from the following link:
http://scratch.mit.edu/scratch_1.4
Preface
[ 3 ]
Who this book is for
The author approaches the content in this book with the belief that we are all teachers and
that you are reading this book not only because you want to learn, but also because you
want to share your knowledge with others. Movated students can pick up this book and
teach themselves how to program because the book takes a simple, strategic, and structured
approach to learning Scratch.
Parents can grasp the fundamentals so that they can guide their children through
introductory Scratch programming exercises. It's therefore perfect for homeschool
families. Teachers of all disciplines from Computer Science to English can also quickly
get up to speed with Scratch and adapt the projects for use in the classroom.
Conventions
In this book, you will nd several headings that appear frequently.
To give clear instrucons of how to complete a procedure or task, we use:
Time for action – heading
1. Acon 1
2. Acon 2
3. Acon 3
Instrucons oen need some extra explanaon so that they make sense, so they are
followed with:
What just happened?
This heading explains the working of tasks or instrucons that you have just completed.
You will also nd some other learning aids in the book, including:
Pop quiz – heading
These are short mulple-choice quesons intended to help you test your own understanding.
Preface
[ 4 ]
Have a go hero – heading
These praccal challenges give you ideas for experimenng with what you have learned.
You will also nd a number of styles of text that disnguish between dierent kinds of
informaon. Here are some examples of these styles, and an explanaon of their meaning.
Code words in text, database table names, folder names, lenames, le extensions,
pathnames, dummy URLs, user input, and Twier handles are shown as follows: "Condional
statements are used to check whether a statement is true or false. For example, if 4 >
0 is a condional statement."
New terms and important words are shown in bold. Words that you see on the screen, in
menus or dialog boxes for example, appear in the text like this: "The top of the page contains
the Create, Explore, and Discuss links."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this
book—what you liked or may have disliked. Reader feedback is important for us to
develop tles that you really get the most out of.
To send us general feedback, simply send an e-mail to feedback@packtpub.com,
and menon the book tle through the subject of your message.
If there is a topic that you have experse in and you are interested in either wring or
contribung to a book, see our author guide on www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you
to get the most from your purchase.
Preface
[ 5 ]
Downloading the example code
You can download the example code les for all Packt books you have purchased from
your account at http://www.packtpub.com. If you purchased this book elsewhere,
you can visit http://www.packtpub.com/support and register to have the les
e-mailed directly to you.
Downloading the color images of this book
We also provide you a PDF le that has color images of the screenshots/diagrams used in
this book. The color images will help you beer understand the changes in the output.
You can download this le from: https://www.packtpub.com/sites/default/files/
downloads/0724OT_coloredimages.pdf.
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen.
If you nd a mistake in one of our books—maybe a mistake in the text or the code—we
would be grateful if you would report this to us. By doing so, you can save other readers from
frustraon and help us improve subsequent versions of this book. If you nd any errata, please
report them by vising http://www.packtpub.com/submit-errata, selecng your book,
clicking on the errata submission form link, and entering the details of your errata. Once your
errata are veried, your submission will be accepted and the errata will be uploaded to our
website, or added to any list of exisng errata, under the Errata secon of that tle.
Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt,
we take the protecon of our copyright and licenses very seriously. If you come across any
illegal copies of our works, in any form, on the Internet, please provide us with the locaon
address or website name immediately so that we can pursue a remedy.
Please contact us at copyright@packtpub.com with a link to the suspected
pirated material.
We appreciate your help in protecng our authors, and our ability to bring you
valuable content.
Questions
You can contact us at questions@packtpub.com if you are having a problem with any
aspect of the book, and we will do our best to address it.
www.allitebooks.com
1
Welcome to Scratch 2.0
I assume you're reading this book because you want to learn how to create
interactive stories, animations, and games using Scratch, or you want to learn
Scratch so that you can teach someone else how to program. It matters not
whether your classroom is in a middle school, a home school environment, an
after-school workshop, or a weekend coding project with your son or daughter.
We are all teachers. That's the perspective of this book. You'll learn how to
create projects using Scratch so that you can teach someone else, but no
programming knowledge is expected.
In this chapter, we will:
Review what Scratch is and how we can use it
Learn more about the types of projects we will create in this book
Explore an example project from the Scratch website and review the project editor
Whether you're 8 or 80, the Scratch programming language provides a beginner-friendly
computer programming environment that enables you to create digital projects. Success
with Scratch comes quickly. You won't nd any quirky syntax to learn, and you won't make
any typing mistakes that prevent your program from running.
Creang a project in Scratch is as easy as snapping the color-coded blocks together.
This environment allows us to see the posive results quickly. In addion to this,
Scratch helps turn passive users into creators.
You'll nd comfort in Scratch's building-block approach to create animaons, games,
and stories. Aer using Scratch, programming will make sense. It will seem easy. It will
bring a smile to your face, and you'll be able to cope with technical concepts in the future.
Welcome to Scratch 2.0
[ 8 ]
About Scratch
Mitch Resnick and the Lifelong Kindergarten Group at the Massachuses Instute of
Technology (MIT) in the Media Laboratory developed Scratch as a teaching language
primarily for 8 – 16 year olds, but there's nothing stopping the rest of us from enjoying
the Scratch experience and sharpening our creave minds.
Encouraging everyone to think programmatically
The natural reacon of people is to see Scratch as a means of teaching computer science
and integrang it into classrooms of all levels. There are teachers who use Scratch across a
variety of subjects as seen on the ScratchEd site. The ScratchEd site caters to the educaonal
community and aggregates a lot of Scratch resources, including lesson plans and ps.
However, the approach and thoroughness of the included material varies greatly.
You can check out ScratchEd at http://scratched.media.mit.edu/.
While wring this book, I did not set out to write a computer science textbook. It's
quite simply a tutorial for people who want to learn how to use Scratch to create stories,
animaons, games, or art. It primarily addresses the parents, home school families, and
teachers who may not be programmers themselves but want a fun way to help their children
become more digitally literate. Everyone, however, can use this tutorial to learn Scratch, and
many young students have worked through the Version 1.4 of Scratch of this book. I expect
young scratchers will be more than capable of working through the projects in this edion.
My underlying belief is that knowing how to program can benet everyone, but not
everyone needs to be a programmer. The mental work required to create a program
inherently develops an understanding of how computers work, sharpens our crical
thinking skills, and gives us lots of pracce at solving problems.
There's also an increasingly popular idea that somemes we want to create applicaons for
personal use. Of course, system administrators have always created custom scripts to help
automate repeve tasks. However, modern applicaons such as Scratch or the MIT App
Inventor (originally developed by Google) make it incredibly easy to create programs for
personal use or with the intenon of sharing it with a small group of friends, which counters
the perspecve that learning to program is synonymous with wanng to be a professional
programmer or an applicaon developer.
When you have a lile bit of programming knowledge, you'll approach non-programming
problems in a dierent way. For example, I've used programming as a marketer to manage
search engine opmizaon and keyword research on business websites. I've also used my
programming knowledge to write automated soware tests.
Chapter 1
[ 9 ]
Boom line, programming becomes a tool in your problem-solving toolbox. This is the key to
understanding how I approach this Scratch tutorial. I want the computer sciensts to come
along for the ride, but I'm catering to a broader audience.
Sample Scratch uses
I couldn't begin to suggest every possible way for you to use Scratch; that's why we have an
imaginaon. However, here are a few ideas to get you started:
Use Scratch to teach yourself or your students how to program. That's the
obvious one.
Use Scratch to demonstrate Math concepts. Scratch can also demonstrate the
x and y coordinate system in an interacve way.
Use Scratch to inspire your kids to read and write. Find a story and animate
each scene or encourage them to animate the story. Turn their haiku into a
Scratch project.
Have a child who only wants to play video games? Make a deal. Your child can
only play the games he creates or remixes with Scratch.
As you work through the examples in this book, write down your project ideas no maer
how hard, easy, obvious, or silly they seem. The next one might be your best idea yet.
Computational thinking
Learning: we do it for life. We should help our children develop skills that will help them
keep learning and solving problems in an increasingly digital environment. Using Scratch,
we will learn how to design, think, collaborate, communicate, analyze, and program in a
computer language.
You may frame the Scratch approach as computaonal thinking. According to Wikipedia:
Computaonal thinking is a problem solving method that uses computer science
techniques. The term computaonal thinking was rst used by Seymour Papert
in 1996.
By the me we make our cat dance for the rst me, we'll forget all about the academic
research and theories behind Scratch. Instead, we'll focus on having fun and creang the
next project.
Welcome to Scratch 2.0
[ 10 ]
Finding a project for you
This book will give you a well-rounded introducon to Scratch. It's true that creang games
are incredibly popular, and young boys tend to want to create games. However, there are
other uses of Scratch, and plenty of people who want to do something other than just create
games. Generally speaking, we'll make an animaon, tell a story, build a game, create art,
and sense the real world.
Making animations
An animaon lets the sprites interact with each other. We'll use the common example
of a birthday card to demonstrate animaons. The following screenshot shows a birthday
card example from Chapter 3, Creaing an Animated Birthday Card:
However, some folks have created more complicated projects using stop-moon
animaons. You can nd some stop-moon animaons on the Scratch website at
http://scratch.mit.edu/studios/254628/.
Chapter 1
[ 11 ]
Telling stories
The rst story project we do will create a slideshow that's designed to be narrated with
Scratch's built-in audio capabilies. The following screenshot is a preview of our slideshow:
Our second story project takes a more classical approach to tell a story by creang a book with
a table of contents and then animang the individual scenes as a way of narrang the story.
Welcome to Scratch 2.0
[ 12 ]
Building games
Games are by the far the most popular Scratch project, and people tend to create all the
normal types of games: plaormer games, scrolling backgrounds, role-playing games,
mazes, and classic arcade games. We'll remix the classic Pong game into a challenging game
of Breakout, and in the process, we'll set the stage for many common game-programming
concepts. The following screenshot shows the Breakout game:
Programming games of chance
We will encounter randomness throughout the book, but we'll develop a project that applies
random outcomes to an interacve story. The following screenshot shows a Trip to the
fortune teller:
Chapter 1
[ 13 ]
Creating art projects
The Scratch site is loaded with talented illustrators, and Scratch provides all the tools needed
to draw characters and scenes, namely a paint editor and an easy way to animate them.
The other kind of art you'll nd on the Scratch site is computer-generated art, and we'll
spend me drawing geometric shapes, as seen in the following screenshot:
Sensing the real world
Scratch has historically included support for add-on hardware, such as PicoBoard and LEGO
WeDo. Scratch also includes built-in support to use the computer's webcam and senses
external sounds using the computer's microphone. We'll explore the webcam, microphone,
and PicoBoard in our project.
Programming concepts
The following table summarizes several programming concepts that can be learned with
Scratch. It's included here primarily to reinforce Scratch as a programming language and
foreshadow the concepts we'll use throughout the book. We'll introduce concepts in
greater detail as we work through the book.
Concept Description
Interface design When we design a program, we turn our imagination into a creation
that can be shared with others. We create the flow of the program,
how the user interacts with the project, and the actions each sprite
takes to tell our story.
Welcome to Scratch 2.0
[ 14 ]
Concept Description
Loops (iteration) A loop repeats (iterates) through a list of programming commands
(also known as blocks in Scratch). Often, we'll use conditional
statements to control when and how often a loop runs.
Boolean logic A Boolean command evaluates a given statement as true or false. In
Scratch, a Boolean command can check whether a specified condition
is true (for example, is the color blue?), or we can compare values with
and, or, and not operators. For example, if 4 > 0 and 4 < 2.
Variables Variables store text or numbers for reuse in the program. For example,
if x > 0 creates a conditional statement that evaluates whether
the number assigned to x is greater than 0.
Arrays (Lists) Arrays are similar to variables in that they store information that may
or may not change. However, a list stores multiple values in the same
way a grocery list stores a group of items.
Events Scratch provides an entire group of event blocks that allows us to
tell our program what to do when that event happens. For example,
events include when flag is clicked or when a space key is pressed.
Synchronization and
coordination
Programming a sprite to receive a broadcast message from another
sprite coordinates a cause and effect. Broadcasting a message and
waiting for all the other sprites to act on the broadcast synchronizes
the action. Throughout the book, broadcasts are a technique we will
use often, and they provide the fundamental communication between
the sprites in the project.
Concurrency Creating two scripts to run on the same control enables parallel
execution. For example, programming four different sprites to pixelate
when the green flag is clicked creates four concurrent actions.
Random numbers This concept picks a random number from a specified range.
Cloud data Scratch 2.0 introduces cloud variables that enable projects to store
data on the Scratch web servers so that the data is available to other
Scratch users. For example, the use of cloud data might include
keeping a high score or tracking the survey results.
Procedures Procedures can also be called as functions or methods in other
programming languages. Scratch 2.0 adds the ability to create custom
blocks that allows you to create a stack of blocks under a single name.
When you use a custom block, you can pass an argument, such as a
sprite number, into the procedure.
Vector and Bitmap
graphics
Scratch includes a built-in image editor that enables you to create
graphics and sprites for your projects. Vector graphics is a new feature
of Scratch 2.0.
Chapter 1
[ 15 ]
Concept Description
Cloning New to Scratch 2.0, cloning allows a sprite to duplicate itself while the
program is running. Clones inherit the parent sprite's costumes and
scripts. For example, many people create games that need to shoot
something, such as asteroids. Cloning in Scratch 2.0 allows us to shoot
multiple times.
Video By using the computer's built-in webcam, Scratch 2.0 can enable the
project to sense the video(s).
Using Scratch 2.0
With the release of Scratch 2.0, project creaon has primarily moved online. For users who
do not have access to the Internet, the Scratch team has launched a complementary oine
editor. I'll introduce you to both the environments.
To get started, in your Flash-enabled web browser, go to http://scratch.mit.edu.
For more informaon about installing Adobe Flash, go to
http://get.adobe.com/flashplayer/ in your web browser.
You'll get a page that resembles the following screenshot:
www.allitebooks.com
Welcome to Scratch 2.0
[ 16 ]
The top of the page contains the Create, Explore, and Discuss links. As we work through our
projects, we'll spend our me creang projects, and I'll leave the forum discussions for later.
For now, let's just look at a project.
At the me I wrote this chapter, the Following Orange project was displayed as a featured
project. It's available at http://scratch.mit.edu/projects/14852464/. If for some
reason this project is not available in the future, just click on any project on the Scratch
home page and play it. Just experience a Scratch project as a user.
The following screenshot shows the Following Orange project:
When you share your projects with the Scratch community, this is the primary view. It's a
relavely intuive design. The users provide some instrucons and credits about the project
as seen in the right-half of the previous screenshot. The project displays a green ag in a
circle, and clicking on the green ag starts (inializes) the project.
Above the stage, we see the project name with the name of the author (I have no idea who
this user is as I just selected it out of convenience). To the right of the project name is a blue
See inside buon. When you click on See inside, you'll see the project editor.
Chapter 1
[ 17 ]
Looking inside a Scratch project
Clicking on the See inside buon for a project will display the details of the project in the
project editor, as seen in the following screenshot. If you click on the Create buon from
the Scratch website, you will open a new project in the same view.
The display gets a lile more complicated because there are more things available on the
screen, but it's important to note that everything we need to create, test, and run our
projects is accessible from the single view of the project editor.
To borrow a phrase from the Scratch Wiki, the project editor is divided into palees and
panes. At this point, I'll draw your aenon to three key areas: the stage, the sprites pane,
and the script area. Using the Following Orange project as a guide, we'll discuss each one
of the three key areas in the following secons.
Welcome to Scratch 2.0
[ 18 ]
The stage area
The large space beneath the green ag and the stop sign icons is the stage. This is where
our sprites act out their scripts. It's here that we get to see the result of our programming.
The sprites pane
Sprites are the characters and objects in our Scratch projects. The list of sprites can
be found below the stage. The following screenshot shows the list of sprites available
to the Following Orange project:
The scripts area
In order to get our sprites to animate, move, or interact with one another on the stage,
we need to create one or more scripts for each sprite. If you click on a sprite from the list,
the project editor will show the exisng stacks of blocks in the scripts area.
Chapter 1
[ 19 ]
A stack of blocks is a script, and a sprite can have mulple scripts assigned to
it. In this book, I'll use either script or stack to refer to a collecon of blocks.
The following screenshot shows a script for one of the sprites in the Following
Orange project:
To create a game, story, or animaon in Scratch, we stack blocks together to form a script
that gives instrucons to the project sprites. In the middle of the project editor screen, we
have categories of blocks that are grouped by the kinds of tasks they represent. They are
Moon, Looks, Sound, Pen, Data, Events, Control, Sensing, Operators, and More Blocks.
Throughout the book, I'll refer to these categories of blocks as palees; they can be seen
in the previous screenshot.
The palees of blocks are analogous to the palee of colors an arst mixes while creang
a painng. We mix the blocks together to form our art work. Each type of block is color
coded so that we can easily idenfy them by their type in our scripts.
The commands wrien on the blocks are in plain English, and they don't require a lot
of eort to understand the basic idea behind any block. Take the script visible in the
previous screenshot as an example. You might not know exactly what these two scripts do,
but by reading the blocks, you will generally understand that these blocks are inializing the
game and changing to the next level.
Welcome to Scratch 2.0
[ 20 ]
The built-in image editor
One of the core features of Scratch is its built-in image editor, which allows us to draw our
own backgrounds and sprites. This makes it incredibly easy for users to create sprites and
project backgrounds, and it's readily available from the project editor.
Previous versions of Scratch used a bitmap image editor, but as of Version 2.0, Scratch can
also draw in vector graphics, which allows us to create images that are smooth and scalable
to any size.
The following screenshot shows the default Scratch cat in the paint editor. If you've used any
image editor in the past, including GIMP or Photoshop, then the drawing tools should have a
familiar feel to them.
Scratch's built-in paint editor is relavely basic in terms of the number of features,
but is funconal for most of our uses. In general, the paint editor will allow you to
perform the following tasks:
Create shapes and text
Import and edit images in popular formats
Apply color
Resize and change the orientaon of the image
Chapter 1
[ 21 ]
The image editor is available from mulple points within the Scratch interface, as we'll see
throughout the book. We'll cover the paint editor in greater detail in Chapter 3, Creang an
Animated Birthday Card.
Using Scratch 2.0 ofine
It's not possible to be connected to the Internet all the me, which may be an increasingly
dicult idea to accept for some people. Nevertheless, consider that your Internet
connecon may go down, that the Scratch website may be oine for updates, or perhaps
your Internet connecon is slow.
If you can't get to the Scratch website, then you can't create a project using the online
project editor. Thankfully, the Scratch team has released an oine editor. You can download
it from http://scratch.mit.edu/scratch2download/.
The download page includes an online installer that will install the prerequisite
soware, namely Adobe Air, on your computer. The following screenshot shows
the Scratch 2 Oine Editor:
Welcome to Scratch 2.0
[ 22 ]
As we see, the oine editor looks like the online editor. Using the oine editor, you can
create projects and then share them to the Scratch website. We'll review sharing projects
in Chapter 2, A Quick Start Guide to Scratch. The oine version of Scratch 2.0 has been in
development for several months following the ocial release of Scratch 2.0.
The previous screenshot indicates that the editor shown is beta. Be sure to double-check
the download page for informaon pertaining to the funconality and release stability of
the oine editor. I would highly recommend downloading the oine version as a backup to
the online version. While the Scratch team does make a great eort to protect user privacy,
creang and saving projects oine does not require an account on the Scratch website,
ensuring user privacy.
Encountering Scratch 1.4
One of the biggest liming factors of Scratch 2.0 is its reliance on Flash and Adobe Air
(for the oine version). Not all computer systems are capable of running Flash
environments; some Linux users and users of the low-cost, credit card-sized Raspberry Pi
come to mind. The Pi is a Linux-based computer that's capable of plugging into an exisng
television set and keyboard. The Pi and Linux versions in general run Scratch 1.4. My XO
laptop also runs Scratch 1.4.
All of these Flash challenges increase the likelihood of encountering Scratch 1.4. I do not
insist on the use of Scratch 1.4 unl we come across the PicoBoard projects in Appendix A,
Connecng a PicoBoard to Scratch 1.4; however, if you're a Scratch 1.4 user, most of these
projects can be adapted with lile eort. I've taken the eort to specically idenfy features
that are exclusive to Scratch 2.0 so that users of the older versions can adapt appropriately.
Tinkering encouraged
The structure of the Scratch interface makes it easy for us to nker and explore ideas.
As we create projects, we evaluate our work and determine whether the results meet
our expectaons. It's very easy because everything happens in one interface.
To check whether our project works, we don't have to compile the code, switch windows,
upload les to a server, or work around any number of other obstacles to run our project.
Scratch enables us to modify the program as it runs and see the results in real me.
Chapter 1
[ 23 ]
Summary
In this chapter, we reviewed Scratch both in terms of its possibilies and how it's used in
the book to create stories, animaons, games, and art. Whether you're a mom, a dad, a
workshop facilitator, or a young scratcher, this chapter lays the foundaon for the work
we'll do in the rest of the book. We've even explored a project and the project editor.
In the next chapter, we'll create an online Scratch account, explore the community, and then
move right into our rst Scratch project. It'll give us an easy way to nker with the Scratch
interface and take our rst steps. We'll focus on some project management fundamentals
including naming objects, sharing projects, and lots of things in between.
2
A Quick Start Guide to Scratch
The anticipation of learning a new programming language can sometimes
leave us frozen on the starting line, not knowing what to expect or where to
start. Together, we'll take our first steps into programming with Scratch, and
block-by-block, we'll create our first animation. Our work in this chapter will
focus on getting ourselves comfortable with some fundamental concepts before
we create projects in the rest of the book.
In this chapter, we will be introduced to Scratch programming. We will:
Join and tour the online Scratch community
Create a project to take our rst steps in Scratch
Introduce loops using forever and repeat blocks
Add and animate mulple sprites in a project
Remix a video-sensing project
Joining the Scratch community
If you're planning to work with the online project editor on the Scratch website, I highly
recommend you set up an account on scratch.mit.edu so that you can save your
projects. If you're going to be working with the oine editor, then there is no need to create
an account on the Scratch website to save your work; however, you will be required to create
an account to share a project or parcipate in the community forums.
Let's take a moment to set up an account and point out some features of the main account.
That way, you can decide if creang an online account is right for you or your children at
this me.
www.allitebooks.com
A Quick Start Guide to Scratch
[ 26 ]
Time for action – creating an account on the Scratch website
Let's walk through the account creaon process, so we can see what informaon is generally
required to create a Scratch account. Open a web browser and go to http://scratch.
mit.edu, and click on the link tled Join Scratch.
1. At the me of wring this book, you will be prompted to pick a username and a
password, as shown in the following screenshot. Select a username and password.
If the name is taken, you'll be prompted to enter a new username. Make sure you
don't use your real name. This is shown in the following screenshot:
2. Aer you enter a username and password, click on Next. Then, you'll be prompted
for some general demographic informaon, including the date of birth, gender,
country, and e-mail address, as shown in the following screenshot. All elds need
to be lled in.
Chapter 2
[ 27 ]
3. Aer entering all the informaon, click on Next. The account is now created, and
you receive a conrmaon screen as shown in the following screenshot:
4. Click on the OK Let's Go! buon to log in to Scratch and go to your home page.
What just happened?
Creang an account on the Scratch website generally does not require a lot of
detailed informaon. The Scratch team has made an eort to maximize privacy.
They strongly discourage the use of real names in user names, and for children, this is
probably a wise decision.
The birthday informaon is not publicized and is used as an account vericaon step while
reseng passwords. The e-mail address is also not publicized and is used to reset passwords.
The country and gender informaon is also not publically displayed and is generally just used
by Scratch to idenfy the users of Scratch. For more informaon on Scratch and privacy, visit:
http://scratch.mit.edu/help/faq/#privacy.
A Quick Start Guide to Scratch
[ 28 ]
Time for action – understanding the key features of your
account
When we log in to the Scratch website, we see our home page, as shown in the
following screenshot:
We reviewed the Create and Explore interfaces briey in Chapter 1, Welcome to Scratch 2.0;
so, we'll take a brief click-through tour of some of the primary features, starng from the
right-hand side of the navigaon and working towards the le.
1. All the projects we create online will be saved to My Stu. You can go to this
locaon by clicking on the folder icon with the S on it, next to the account avatar,
at the top of the page. The following screenshot shows my projects:
Chapter 2
[ 29 ]
2. Next to the My Stu icon in the navigaon pane is Messages, which is represented
by a leer icon. This is where you'll nd nocaons of comments and acvity on
your shared projects. Clicking on this icon displays a list of messages.
3. The next primary community feature available to the subscribed users is the Discuss
page. The Discuss page shows a list of forums and topics that can be viewed by
anyone; however, an account is required to be able to post on the forums or topics.
What just happened?
A Scratch account provides users with four primary features when they view the
website: saving projects, sharing projects, receiving nocaons, and parcipang in
community discussions.
When we view our saved projects in the My Stu page, as we can see in the previous
screenshot, we have the ability to See inside the project to edit it, share it, or delete it.
All newly created projects are unshared by default. Users will need
to explicitly share the project for others to view it.
A Quick Start Guide to Scratch
[ 30 ]
Abiding by the terms of use
It's important that we take a few moments to read the terms of use policy so that we know
what the community expects from us. Taken directly from Scratch's terms of use, the major
points are:
Be respecul
Oer construcve comments
Share and give credit
Keep your personal informaon private
Help keep the site friendly
Creating projects under Creative Commons licenses
Every work published on the Scratch website is shared under the Aribuon-ShareAlike
license. That doesn't mean you can surf the web and use copyrighted images in your work.
Rather, the Creave Commons licensing ensures the collaboraon objecve of Scratch by
making it easy for anyone to build upon what you do.
When you look inside an exisng project and begin to change it, the project keeps a remix
tree, creding the original sources of the work. A shout out to the original author in your
projects would also be a nice way to give credit.
For more informaon about the Creave Commons Aribuon-ShareAlike license, visit
http://creativecommons.org/licenses/by-sa/3.0/.
Closely related to the licensing of Scratch projects is the understanding that you as a web
user can not inherently browse the web, nd media les, incorporate them into your project,
and then share the project for everyone.
Respect the copyrights of other people. To this end, the Scratch team enforces the Digital
Millennium Copyright Act (DMCA), which protects the intellectual rights and copyrights of
others. More informaon on this is available at http://scratch.mit.edu/DMCA.
Finding free media online
As we'll see throughout the book, Scratch provides libraries of media, including sounds
and images that are freely available for use in our Scratch projects. However, we may nd
instances where we want to incorporate a broader range of media into our projects.
Chapter 2
[ 31 ]
A great search page to nd free media les is http://search.creativecommons.org.
Taking our rst steps in Scratch
From this point forward, we're going to be project editor agnosc, meaning you may choose
to use the online project editor or the oine editor to work through the projects.
When we encounter soware that's unfamiliar to us, it's common to wonder, "Where do I
begin?". The Scratch interface looks friendly enough, but the blank page can be a daunng
thing to overcome. The rest of this chapter will be spent on building some introductory
projects to get us comfortable with the project editor.
If you're not already on the Scratch site, go to http://scratch.mit.edu and let's
get started.
Time for action – moving the cat across the stage
As a warm up, we're going to make the default Scratch cat move across the stage.
1. Click on the Create buon to open a new project in the editor. The project contains
a single sprite—the Scratch cat.
2. In the blocks palee, click on the Events buon.
3. Drag the when ag clicked block to the scripts.
A Quick Start Guide to Scratch
[ 32 ]
4. In the blocks palee, click on the Moon buon.
5. Drag the move (10) steps block to the scripts area and snap it to the boom of the
when ag clicked block, as shown in the following screenshot:
How to snap two blocks together
As you drag a block onto another block, a white line is displayed to indicate
that the block you are dragging can be added to the script. When you see
the white line, release your mouse to snap the block in place.
6. Click on the green ag above the stage repeatedly to set our rst Scratch program
in moon.
If the cat reaches the end of the stage, you need to manually move the
sprite to the left side of the stage by clicking-and-dragging the cat.
What just happened?
Our rst Scratch project combined two blocks to make the cat move across the screen. The
rst block we used was the when ag clicked block from the Events block, and, very simply,
when the ag was clicked, we used the move () steps block to give the cat some moon.
As we clicked through the blocks palee, we saw that the available blocks changed
depending on whether we chose Moon, Looks, or Events. Each set of blocks is color
coded to help us easily idenfy them in our scripts.
Did you look closely at the blocks as you snapped them together? As children, most of us
probably had a game where we needed to put the round peg into the round hole. Building a
Scratch program is just that simple. We see instantly how one block may or may not t into
another block. One of the friendly design aspects of Scratch is that it's incredibly obvious
when two blocks t together, just like when you put puzzle pieces together or build with
LEGO. Scratch's building block design is heavily inuenced by LEGO. The Events block, for
example, always sit on top of a stack of other blocks. You can never put the move () steps
block on top of the when ag clicked block.
Chapter 2
[ 33 ]
The move (10) steps block accepts a numeric value that can be changed.
Throughout the book, we'll encounter many blocks that accept values,
and oen, the blocks have a default value, such as the move block. In the
exercises, you will noce block values are kept in parenthesis, and somemes
you might see the block referenced with the value, as in move (10) steps.
When we need to change the default value, you might see the block wrien in
the format move () steps, which omits the default value.
Using events to trigger an action
One of the most important groups of blocks in Scratch is the Events block. We used the
when ag clicked block as a trigger to make the cat move. There are other event blocks that
we'll encounter in future projects, but a majority of the Scratch projects developed by the
community will use the when ag clicked block to start the project.
As we develop more sophiscated projects, we'll see how the when ag clicked block can be
used to inialize the starng values, posions, and views of the project.
Have a go hero – testing the move block
Take a minute to explore our two block scripts by changing the value in the move () steps block.
Check what happens when you use a larger value such as 50 or a negave value such as -23.
Time for action – animating a walking motion with the cat
We're going to build on our script by creang an appearance of movement:
1. From the Looks palee, aach the switch to costume () block to the move () block
in our script. The default costume will be costume2.
2. Click on the green ag to move the cat. Note that the rst me we clicked on
the ag, the appearance of the cat changed, but it remained the same on
subsequent movements.
A Quick Start Guide to Scratch
[ 34 ]
3. We'll make the animaon more realisc in a minute, but let's examine the costumes
by clicking on the Costumes tab. The following screenshot shows the contents of the
Costumes tab:
4. This view opens the sprite in the paint editor, but our primary interest is the
costume thumbnails. If you've run the script as we've created, then costume2 is
highlighted. Alternavely, click on the thumbnails and observe how selecng the
costume displays on the stage.
5. Depending on the speed of your clicks, the cat has the appearance of walking or
running in place. There's no horizontal movement associated with toggling the
costumes back and forth.
6. Now, let's adjust the script to replicate this walking moon. Add another switch to
costume () to our script. Select costume1.
7. Now, repeatedly click the green ag. You will discover that our script doesn't appear
to switch the costumes like we expected.
8. Scratch is actually running our blocks faster than we can see with our naked eye.
We need to adjust the ming so that we can see the animaon. From the Control
palee, snap a wait () secs block between the switch to costume (costume1) and
switch to costume (costume2) blocks.
9. The default value in the wait () secs block is 1. Change it to a smaller number, such
as .2, to speed up the me it takes to switch the costumes.
Chapter 2
[ 35 ]
10. Our revised script can be seen in the following screenshot:
What just happened?
By adding the switch costume to () blocks, our script now gives the appearance of walking.
The wait () secs block added some ming so that the transion between the costumes could
be detected.
Costumes are a fundamental part of Scratch and can be used to change the appearance of
our sprite, as we've seen in our example. There's a liming factor in our script so in that the
cat only takes a step when the green ag is clicked.
We'll connue to rene the movement and acon of our script, but let's pause for a moment
to put our simple project into a wider Scratch context.
Understanding the basics of a Scratch Project
Inside every Scratch project, we will nd the following ingredients: sprites, costumes, blocks,
scripts, and a stage. It's how we mix the ingredients with our imaginaon that creates
capvang stories, animaons, and games. Think of each sprite in a Scratch program (also
known as a project) as an actor. Each actor walks onto the stage and recites a script, which
consists of individual lines. How each actor interacts with another actor depends on the
words the director chooses, and we are in the director's seat of our Scratch programs.
Throughout the book, we'll learn how to add and customize sprites. A sprite wears a costume
like an actress dresses up for her role in the play. Change the costume, and you change
the way the sprite looks. Blocks are commands that are grouped by their type and include
Moon, Looks, Sound, Pen, Data, Events, Control, Sensing, Operators, and More Blocks.
We snap blocks together to create scripts, as our current exercises demonstrate.
Scripts are a set of blocks that tell a sprite exactly what to do. Each block represents an
instrucon or a piece of informaon that contributes to the sprite or to the project in
general. We'll explore those relaonships in our projects.
www.allitebooks.com
A Quick Start Guide to Scratch
[ 36 ]
Saving early, often, and automatically
It's good pracce to get in the habit of saving our work.
Time for action – saving our work
The online project editor will autosave our work, but it's good pracce to manually save
our projects, especially before you close your web browser or navigate away from the
Scratch website.
1. To manually save your new project, click on Save now from the File menu at the
top of the project editor. This works whether we're working with the online or
oine editor.
2. As you review the project, you'll noce that each project has a name. Our current
project is called untled. To change the name of your project from untled, nd
the white textbox above the stage and change the project name to something
meaningful by clicking in the box and typing. The following screenshot shows the
project name in relaon to the screen. My project is named run, kiy, run.
What just happened?
Autosave is nice and will generally limit our loss should we encounter an unexpected error or
loss of Internet connecvity. The general rule whenever you're creang something is to save
early and save oen. This is especially true for users of the oine editor, where there is no
autosave feature.
Chapter 2
[ 37 ]
A variaon of saving the current project is to use Save as a copy to create a copy of the
current project. This is useful if we want to save our work at a parcular point. There is no
versioning within Scratch, so somemes saving a copy of a project before making a lot of
addional changes is the only reliable way to get back to a known starng point.
Undoing a deletion
If you deleted something you shouldn't have, there is an Undelete opon under the Edit menu
at the top of the Scratch editor. You can only undelete the most recent item that you deleted.
Introducing forever loops
Let's get back to our walking cat animaon and set it in perpetual moon. When we do
something forever, we constantly repeat it. In Scratch's context, forever means we're going
to constantly loop through a series of blocks for as long as the project is running.
Time for action – setting the cat in motion, forever
So far, the cat has moved incrementally across the screen each me we clicked the green
ag. Now, we're going to introduce the idea that the cat can stay in moon forever.
1. We want to wrap the stack of blocks in a forever block. To do this, click on the move
(10) steps block in the script and detach it from the when ag clicked.
2. Now, from the Control palee, snap the forever block onto the when ag clicked
block. Grab the stack of blocks you detached and drag it to the center of the forever
block. Your script should look like the following screenshot:
3. Run the script and watch the cat disappear from the stage.
4. Let's get the runaway cat back. From the Moon palee, add the if on edge, bounce
block to the boom of the forever block. Now, watch the cat reappear upside down
and bounce around the boom-right corner of the stage.
A Quick Start Guide to Scratch
[ 38 ]
5. To stop the cat, click once on the script or click on the stop sign above the stage.
The following screenshot shows the current state of our project:
Our script has a couple of issues to work through, such as a choppy walking moon and an
upside down cat. We'll come back and x this up some more, but rst let's consider what
we accomplished.
What just happened?
We wrapped our enre script in a forever block, which is synonymous with a loop. In
programming, a loop runs a group of commands over and over again. Aer we repeatedly
instructed the sprite to move across the stage, it didn't take long before it went o the stage.
The if on edge, bounce block did as the name implies—it turned the cat around when it hit
the edge of the stage. As the if on edge, bounce block was the last block in the forever loop,
the script checked for the edge of the stage with each step.
If you carried out the steps in the exercise as described, you will see that as soon as you
placed the if on edge, bounce block into your script, the sprite reappeared.
You can add blocks to the loop and change the block aributes as the
script runs, and the sprite automacally adjusts to the new values.
Chapter 2
[ 39 ]
Controlling a sprite with loops
Any me we need to repeat an acon within a project, we use a loop. The forever block
represents an innite loop because there is nothing in the script that tells the block to
stop running. The blocks inside the loop will run as long as the Scratch program is running.
We'll use loops throughout the book to control how a sprite behaves and to connually
evaluate the changing condions of our games, stories, and animaons.
Time for action – ipping the cat right-side up
Let's tweak our script so the cat rotates right-side up and see if we can speed up our steps:
1. Scratch 2.0 introduced the set rotaon style block in the Moon palee that will
set our cat right-side up. From the Moon palee, nd the set rotaon style () block
and add it to your script aer the set rotaon style () block. The default aribute for
the set rotaon block is le-right, which xes our problem.
2. Click on the stack of blocks to run the script. Your script should look like the
following screenshot:
3. Now, let's address the choppy movement of the sprite. From the Looks palee, drag
the next costume block into the scripts area. Don't aach it to the script yet because
we want to expose another one of Scratch's features. If the cat is sll moving, you
can stop it by clicking the stop sign.
4. Click the next costume block directly. And then, repeatedly click on the block so
that you see the cat switching between its costumes with each click of the block.
This block is mimicking the funconality we've already built into the script, but we'll
explain the full ramicaons aer we wrap up the exercise.
A Quick Start Guide to Scratch
[ 40 ]
5. Remove the following blocks from the script by clicking on them and dragging them
to an empty spot in the scripts area: switch costume to (costume2), wait (.2) secs,
and switch costume to (costume1).
Removing blocks from the middle of the script is not always a clean process.
Often, Scratch will remove more blocks than you want it to. As long as you
drag the blocks to the Scripts area, you can easily add the relevant blocks
back to the script.
6. Add the next costume block aer the move (10) steps block, replacing the three
blocks we just removed. Verify your script against the following screenshot:
What just happened?
Of primary interest to us was geng the cat's rotaon correct as it bounced o the edge
of the stage. The set rotaon style (le-right) block told the cat to rotate horizontally.
Before we set the rotaon, the cat was ipping vercally as it reversed direcon.
The next thing we did was consolidate the changing of the costumes down to a single
next costume block. This made the running moon smoother but much faster. We can
slow the cat back down by adding a wait () secs block at the end of the forever loop and
experimenng with values.
You might be wondering why we were able to replace the mulple switch costume to ()
blocks with next costume and sll see the running moon of the cat. The reason lies in
the loop. Before we added the forever loop, the script used two blocks to explicitly switch
between the costumes. These two switch costume to () blocks equaled one step. The wait
(.2) secs block put a slight hesitaon in the step. In order to get the appearance of running
or walking, we needed to manually switch between the two costumes within that one step.
Chapter 2
[ 41 ]
When we replaced the switch costume to () blocks with a single next costume block,
each step was now a costume switch. The animaon was much smoother even without the
wait () secs block. All the blocks in the loop became one step that was repeated forever.
The connual looping of the script provided the same end result that we had when we
added the mulple switch costume to () blocks.
With the next costume block, we don't need to know the name of the costume or even care
how many costumes the sprite has. If the current costume is number one, then the next me
through the loop, the costume will change to number two, and so on. When we use next
costume, we do have to be concerned that the costumes t the project we're working on.
On the other hand, if we need to explicitly display a sprite's costume, the switch costume to
() block is a beer choice. For example, if we need to make sure a sprite looks a certain way
at the start of a game, we'd use the switch costume to () block in a script that started with
when ag clicked.
Clicking on a block runs the command
Before we added the next costume block to the script, we placed it in the scripts area and
clicked on the block. This allowed us to run the block before we added it to the script and is
a feature of Scratch. Unl this point, we've been clicking on the green ag to run the script,
but we could just as easily be clicking on the stack of blocks to start to run the script.
The ability to run an individual block against a sprite gives us a chance to observe the
behavior of the block before we add the block to our script. It's a great way to test and learn.
Have a go hero – exploring sprite rotation
The set rotaon style () block we used in our script has three rotaon values available:
le-right, all around, and don't rotate. Explore the behavior of the cat by using each
rotaon style.
Adding sprites to the project
So far, we have learned that if we want something done in Scratch, we must tell a sprite to
act by creang one or more scripts. Scratch always starts a new project with a single cat.
However, we don't always want to use the cat, and our games and stories will most likely
include mulple sprites.
A Quick Start Guide to Scratch
[ 42 ]
We can add sprites to the stage in one of the four ways: paint a new sprite, choose a sprite
from the library, upload a sprite from le, or a new sprite from the camera. The icons to
insert a sprite using one of these four methods are located in the New sprite pane, between
the stage and the sprites list. The following screenshot shows the New sprite icons. Move
the mouse over each icon to see a toolp that idenes the new sprite method.
As we build future projects, we'll explore the various ways to add sprites. For now, we'll focus
on Scratch's built-in sprite library. It's a great benet to have a library of available sprites
at the click of a mouse. The following screenshot shows what you see when you select the
choose sprite from library opon:
Time for action – adding a second sprite and script
We've menoned that we can have mulple sprites acng out their scripts, but now we're
going to add a second sprite to the project to illustrate the concept and explore some
addional moon blocks and loops.
1. Add a new sprite by clicking on the Choose new sprite from library opon.
Then, browse to the Animals category and select Dog1. Click on OK to add the
dog to the project.
Chapter 2
[ 43 ]
2. Ensure Dog1 is selected in the sprite list to ensure we have the scripts area for
the dog.
3. From the Moon palee, drag one of the turn blocks into the scripts area.
Two turn blocks
If you look in the Motion palette, you'll notice that there are two turn
blocks. One has a circle arrow that points clockwise and the other turn
block points counter-clockwise.
4. Find the repeat block from the Control palee and snap it around the turn block.
5. Wrap the script in the forever block.
6. From the Events palee, add the when this sprite clicked block on top of the enre
stack of blocks.
7. From the Looks palee, snap the say () for () secs block onto the boom of the
repeat () block and above the forever block.
8. Next, we'll ne-tune the values of the blocks we just added. Change the value on the
repeat block to 100. Change the value on the turn block to 30. Change the value on
the say block to chasin' my tail.
9. Click on the dog on the stage and watch the sprite spin in a circle as if it's chasing its
tail. Click on the green ag and set the cat on its trip back and forth across the stage.
The following screenshot shows the dog and its script:
What just happened?
We have two sprites on the screen that act independently of each other. This seems simple
enough, but let's step through our script.
We added the dog sprite to the project and created a script that made the dog appear as if
it was chasing its tail. Changing the value of the turn block will make the dog spin slower
or faster.
A Quick Start Guide to Scratch
[ 44 ]
By increasing or decreasing the value of the repeat block, we can control how many mes
the dog spins before it says chasin' my tail. The repeat () blocks contained in the repeat loop
run for the number of mes specied.
The repeat loop diers from the forever loop in that a repeat loop has a specied end,
while the forever loop runs innitely. As our exercise demonstrates, we can combine
the loops, thereby providing mulple control points in our script.
Our exercise also introduced the idea of using mulple events in the same project to control
when a sprite acts. The cat acts when the ag is clicked, while the dog acts only when you
click on the dog sprite.
Reviewing a video-sensing project
We're going to leave our rst Scratch project behind, and go out to the Scratch website to
nd a project that uses some of the blocks we've used throughout this chapter. Our main
purpose is to view a complementary project in terms of blocks that can give us some ideas
to extend our introductory project and introduce a Scratch 2.0 feature.
Time for action – reviewing pop the balloon - video starter
We'll be viewing a project from the Scratch website, so open a browser and go to
http://scratch.mit.edu/projects/10126867/. Alternavely, you can download
the book's supporng code les and open Pop the balloon - video starter.sb2.
The project is from chrisg, a Scratch team member.
1. When you have the Pop the balloon - video starter.sb2 project open,
click on the See Inside buon to see the sprites and scripts of the project. If you're
using the oine editor, you'll automacally open the project in the code view.
2. This program uses a webcam, so let's see what it does. Click on the green ag to
start it.
3. You will be prompted with a message that indicates that Scratch wants access to
your microphone and webcam. Click on Allow.
4. The view of your webcam is now on the Scratch stage with oang balloons.
Touch the balloons to pop them.
Chapter 2
[ 45 ]
5. This project has one sprite with two scripts. If you take a look at the script that
begins when the ag is clicked on the block, most of these blocks look familiar, and
that's why we're looking at this script at this point in me.
Downloading the example code
You can download the example code les for all Packt books you have purchased
from your account at http://www.packtpub.com. If you purchased this
book elsewhere, you can visit http://www.packtpub.com/support and
register to have the les e-mailed directly to you.
What just happened?
In our earlier chapter exercises, we've used the set rotaon style (), forever, move () steps,
turn () degrees, and if on edge, bounce blocks to animate the cat and dog. In the balloon
project, these same blocks are moving a balloon around the stage and creang a dierent
eect, essenally by changing the values assigned to the blocks.
The biggest dierence we see is the pick random () to () block, which resides in the
Operators palee. This block takes two values, which correspond to a range, meaning the
turn block is randomly picking a number between -30 and 30. That gives the balloon the
variaon in the movement and gets it traveling up, down, right, and le. We'll encounter
the pick random () to () block again.
www.allitebooks.com
A Quick Start Guide to Scratch
[ 46 ]
Sensing video
One of the other reasons for opening this project is that it demonstrates one of Scratch
2.0's features—video sensing. This feature has a lot of eye candy because it incorporates
live video from the web cam into the project. However, we can't actually record videos for
playback. It's limited to sensing moon and direcon.
We're not going to work with video sensing in any of our future projects. Now that you know
this feature, I recommend you explore video sensing aer you learn some more of the basics
behind Scratch programming.
Have a go hero – remixing ideas with our starter project
The one thing about learning to program with Scratch (or any language) is that somemes
you can use scripts, snippets, and ideas from another project to accomplish a task in your
project. Can you take the moon of the balloon project and apply it to the cat in the starter
project? Likewise, now that you have the video-sensing project open, you can take a stab
at customizing in some way. We haven't covered much to this point, but there's nothing
stopping you from a bit of exploraon.
Pop quiz – getting started with Scratch
Q1. What are the advantages of registering an account with the Scratch website?
1. Ability to save and share projects from the online project editor.
2. Ability to post to the site forums.
3. Ability to save unshared projects in My Stu.
4. All of the above.
Q2. Which one of the following blocks represents an event?
1. move (15) steps.
2. when ag clicked.
3. repeat.
4. forever.
Q3. Why would you use a forever block?
1. To run a series of commands for a set number of mes.
2. To run a group of blocks only when a condion is true.
3. To run a group of blocks for as long as the project runs.
4. There is no good reason to use a forever block.
Chapter 2
[ 47 ]
Q4. The repeat () block does what?
1. Runs a group of blocks for the specied number of mes.
2. Runs a group of block forever.
3. Runs a stack of blocks each me the green ag is clicked on.
4. Runs a stack of blocks each me the script is clicked on.
Q5. The repeat and forever blocks represent what programming concept?
1. Variables.
2. Loops.
3. Events.
4. Synchronizaon.
Summary
In this chapter, we covered a lot of ground and got a quick introducon to creang our
rst project in Scratch. We focused on moving the sprite around the stage. We made the
cat travel across the stage connuously using a forever loop while the dog chased its tail.
We learned that sprites can have mulple costumes, and when we create a script to access
those costumes, we can animate the sprite's behavior.
In the next chapter, we will animate a birthday card, and in the process, we will learn to
use Scratch's built-in paint editor. We'll also apply graphical eects and connue to work
with events to ensure we get the me of our animaons just right.
3
Creating an Animated Birthday Card
Now that we've taken a tour of Scratch and created some sample scripts,
let's actually create a complete project, right from concept to completion.
In this chapter, we will create an animated birthday card for a friend or
family member using both sprites that we design and sprites that we import
from Scratch's library. Animating a card is an excellent introductory Scratch
programming exercise because it can be accomplished using relatively basic
concepts. We'll also be introducing Scratch's paint editor in this chapter,
which gives really young children who might not be able to read very well
a low-tech way to interact with Scratch by drawing and editing sprites.
In addion to doing something fun, praccal, and thoughul, we will also learn how to:
Design bitmap and vector images using the built-in paint editor
Inialize a sprite's starng values
Name sprites in easy-to-remember ways
Transform sprites using graphical eects, loops, and broadcasts
We'll ll in these general ideas with details as we move through the exercises in this chapter.
Creang an Animated Birthday Card
[ 50 ]
Introducing the paint editor
Tradional birthday cards that you buy ve minutes before a party are an impersonal way
to show someone you care. So, when you care enough to send a card, make it a homemade
card that you have designed yourself. Instead of cung, gluing, and stenciling paper, we're
going to make a homemade animated birthday card using Scratch.
Can't think of anyone to send a card to? Send it to yourself—I won't tell anyone.
Time for action – painting a happy birthday sprite
When we create a new project, our rst task is to add our cast of characters and props;
otherwise, we won't have any sprites to animate. Let's start by adding the most obvious
part of a birthday card—the Happy Birthday text:
1. To start a new project, click on the Create buon on the Scratch website.
2. We won't be using the cat, so you can delete that sprite by right-clicking on the
cat icon, labeled as Sprite1 in the sprites list, and choosing delete.
3. For our rst sprite, we want to draw a new one; so, click on the Paint new sprite
icon, as shown in the following screenshot:
4. Clicking on the Paint new sprite icon creates a new sprite named Sprite1 and
opens the paint editor to an empty canvas, as shown in the following screenshot.
To start, click on the Text tool, as shown in the following screenshot, so that we are
able to type:
Chapter 3
[ 51 ]
5. Click on the canvas with your mouse where you want to type, and you'll see a
vercal bar appear, which indicates that you are able to type. Go ahead and type
Happy Birthday. If the text scrolls o the screen, use the horizontal and vercal
scroll bars on the editor window to posion the text in the editor window.
6. Don't like the default font? We can change it. Highlight the text you just typed and
look at the boom of the paint editor to nd the Font menu. You can select from a
limited number of fonts. In the following screenshot, I have selected the Scratch font:
7. As you can see, there is also a color palee available, so let's change the text
color. Highlight the text and click on the color you want from the color palee.
Happy Birthday is now displayed in the color you select.
8. If you're happy with the words, font, and color, you can save your sprite by clicking
anywhere on the stage or the paint editor. The sprite is now visible on the stage.
But be careful; aer you click out of the Text tool, you will not be able to change
your text.
Creang an Animated Birthday Card
[ 52 ]
Erasing mistakes
The toolbar contains an erase tool with an adjustable eraser width that
allows you to remove parts of your image. If you want to change the words,
font, or color of the text we just created, you'll need to erase the sprite and
start over.
What just happened?
We used the default bitmap editor to create a simple Happy Birthday sprite in the font and
color of our choice. Note that aer we saved our text by clicking anywhere in the image
editor or the stage, we created a sprite. Even though our sprite inially comprised of 13
leers, it's now treated as a single bitmap image instead of individual leers. If we need to
change the details of the Happy Birthday sprite, we'll need to erase what we have created
and start over again.
Changing the size of a bitmap image
Aer we save the size of our sprite, Scratch 2.0 does not provide a size seng in the bitmap
version of the editor where we just created this image. Bitmap is the type of image we
created in the previous exercise, and we'll talk a bit more about it in the following secon.
To change the size of the sprite we just created, we can manually resize the image using
the Grow and Shrink buons, which are located directly above the ag and stop sign in the
project editor. To manually make a sprite bigger, click on the Grow buon and then on the
sprite. The following screenshot shows the locaon of the Grow and Shrink buons. Scratch
will remember these sizes unless we change the size of the sprite with a block.
We can also change the size of the sprite by adding the set size to () block from the Looks
palee. The next exercise will use the set size to () block.
Our exercise is focused on drawing a sprite using words; however, you can draw shapes or
characters if you're so inclined.
Chapter 3
[ 53 ]
Choosing bitmap or vector images
Not only does Scratch have a built-in image editor, but it also allows you to choose from
bitmap or vector graphics. Bitmap images tend to be easier to work with, but as you make
the image bigger in size, it becomes less clear and more blurry, and the quality deteriorates.
The image appears to have rough edges. That's because a bitmap image is represented on a
computer by pixels or single dots of color that are arranged in a paern to create the image
we see.
If we were to zoom in on a bitmap image, we would eventually see the individual dots.
When we resize an image to the point where we start to see the individual pixels, this
eect is commonly referred to as pixilaon. The image is no longer smooth and crisp.
Vector graphics, on the other hand, will appear to be smooth no maer how big you make
the images. However, they tend to be a bit harder to work with. When a vector graphic is
displayed on a computer screen, a program (Scratch in this case) renders the image based
on a mathemacal calculaon to draw the curves and lines instead of individual pixels of
color. This makes the image scalable to any size while avoiding pixilaon.
Let's try a side-by-side comparison using the Happy Birthday sprite.
Time for action – drawing a vector image
Let's draw the Happy Birthday sprite in the vector mode. Then, we'll increase the size of both
our images to compare the appearance:
1. Create a new sprite by clicking on the Paint new sprite icon.
2. Convert the image to vector graphics by clicking on the convert to vector buon at
the boom-right of the editor. When the mode changes, the toolbar moves to the
right side of the editor.
3. From the toolbar, use the text tool to create a second Happy Birthday sprite.
4. Now, let's make the sprites bigger. From the Looks palee, drag the set size to ()
block into the Scripts area. Change the size aribute to 300 and then click on the
block to apply the size.
5. Repeat step 4 for the other Happy Birthday sprite we created.
6. View the project in fullscreen mode by clicking on the blue square located at the
top of the stage, to the le of the project name. The output looks similar to the
following screenshot:
Creang an Animated Birthday Card
[ 54 ]
When the project opens in fullscreen mode, the output on your screen should resemble the
following screenshot:
As you can see in the previous screenshot, the image at the top is starng to pixelate and is
not as crisp as the boom sprite. This top image is the bitmap image.
What just happened?
In the preceding screenshot, the rst Happy Birthday sprite is the bitmap image. As we
made the sprites bigger by viewing the project in fullscreen mode, the bitmap starts to show
ragged edges that didn't show up when we viewed the sprite in the editor at its original size.
If you compare this bitmap image with the vector graphic, by comparison, the vector graphic
looks smooth. Visually, that's the key dierence between vector and bitmap graphics.
In addion to creang your own vector images, the Scratch sprite
library contains many vector-based images. The editor cannot
convert bitmaps to vector images, and all imported images are
imported as bitmaps.
You can choose to use vector or bitmap images depending on your ability and needs.
The best way to nd some Scratch drawing inspiraon is to explore the community.
Changing the size of the vector image
When we create a vector image, Scratch allows us to resize the image by clicking on one of the
control points on the boundary of the image. The following screenshot shows eight square
control points around the Happy Birthday sprite that allow us to resize or reshape the image:
Of course, we can also change the size of the vector-based sprite by using the Grow or Shrink
buons and the set size to () block, as discussed with the bitmap images.
Chapter 3
[ 55 ]
Reviewing the image editing tools
Each image mode contains a toolbar. The following table denes the tools for both bitmap
and vector modes. The tool name column corresponds to the toolp you get when you hover
your mouse over the tool.
The bitmap eding tools along with their descripons are listed as follows:
Bitmap editing tools Description
Brush This tool is used to draw freehand. You can select a color and a
line width.
Line This tool is used to draw straight lines only by clicking-and-dragging
the mouse on the canvas. You can select a color and line width.
Rectangle This tool is used to draw a rectangle. In addition to selecting a line
width and color, you can draw a solid rectangle or transparent
rectangle.
Ellipse This tool is used to draw an oval. In addition, you can hold down
the Shift key to draw a circle with your mouse. You can draw an
image with a solid or transparent center. You can also select a
color and line width.
Text This tool creates a text box with a cursor when you click on the
canvas. You can select the font and color. However, the text can't
be changed after you save it.
Fill with color This tool fills a region with a solid color or gradient.
Erase This tool enables an eraser with a selectable size.
As you move the eraser over the canvas, it removes the image.
Select This tool, as the name suggests, selects an area of the image that
you can move, stretch, or shrink.
Select and duplicate This tool selects an area of an image and then copies the selected
area so that it can be dragged to a new place on the canvas.
The vector eding tools along with their descripons are as follows:
Vector editing tools Description
Select This tool selects a sprite by clicking on it so that you can
reposition or rotate it. It allows you to resize, shrink, or stretch
the image.
Reshape This tool changes the shape by clicking on and dragging one of
the control points.
Pencil This tool is used to draw a freehand design using a selectable
line width and color.
www.allitebooks.com
Creang an Animated Birthday Card
[ 56 ]
Vector editing tools Description
Line This tool is used to draw a straight line on the canvas by
clicking-and-dragging from one point to another. You can
select the line width and color. To make a curvy line, you will
first start with a straight line and then use the reshape tool to
create the shape you need.
Rectangle This tool is used to draw a rectangle. In addition to selecting
a line width and color, you can draw a solid rectangle or
transparent rectangle.
Ellipse This tool is used to draw an oval, or hold down the Shift
key to draw a circle with your mouse. You can draw an
image with a solid or transparent center. Select a color
and line width.
Color a shape This tool is used to fill a vector object. Unlike the fill tool in the
bitmap editor, it cannot fill a blank background or object.
Duplicate This tool is used to select and copy an object with the mouse
pointer. The copied object can then be moved and changed as
needed.
Erasing in the vector mode
You may noce that there is no erase tool in the vector mode. In the vector mode, you can
remove the secons of a line or curve by pressing the Shi key and clicking on a circle control
point, or you can do this by dragging a control point to reshape the line. This funconality
is available under the reshape tool. The following screenshot shows Gobo, one of Scratch's
default sprites in the paint editor, with the reshape tool selected. Note the circular control
points around the perimeter of the selected shape.
If you click around the Happy Birthday vector sprite we created, you'll also noce that it's
possible to change the individual leers of the text we created as well as the color.
Chapter 3
[ 57 ]
Filling the stage with color
A white background seems boring, and we're not about to tolerate boring, are we? Let's see
how easy it is to design our stage with colors and gradients.
Time for action – using the ll with color tool to paint the stage
In this exercise, we're going to create a solid background for our card and add a border to the
design using a second color. Before you paint the background, let's delete the bitmap version
of the Happy Birthday sprite. Let's paint by performing the following steps:
1. Select Stage in the sprite list.
2. Select the Backdrops tab. Our project is new, so we see the default white
background in the paint editor.
3. Apply a color by selecng the Color the shape tool and then choosing a color from
the color palee. Click on the stage to ll it with the selected color.
Creang an Animated Birthday Card
[ 58 ]
Undo
If you don't like the color you put in place, you can remove it by
pressing the Clear button located above the editor. Likewise, you
can use the Undo button, which is the counter-clockwise arrow.
4. Let's create a frame around the edge of the stage so that we can add a second color.
Convert the stage backdrop to the vector mode so we can use the Rectangle tool.
5. Select the Rectangle tool and pick a contrasng color. Click on the image editor to
draw a rectangle. The following screenshot shows a sample backdrop border on
the stage:
Changing the width of the line
At the bottom-left of the paint editor, there is a slider to control the
width of the rectangle line. Several other tools also include a way to set
the width of the line, including the pencil, line, ellipsis, rectangle, and
reshape tools.
We've now given our stage some color and a touch of personality. Feel free to
experiment here.
Chapter 3
[ 59 ]
What just happened?
A basic tool of any image eding soware is the ll tool, which allows you to ll an area
with color. When we were working in the vector mode, our ll tool was called Color a shape.
In the bitmap mode, it's called Fill with color. When we add the simple rectangle shape, we
are able to create a border or a frame.
This exercise, beyond adding some color, should get you thinking about design. Even the
simplest of projects will be designed. Our design is relavely simple right now. We have
mulple colors and shapes in addion to the text.
One of the beauful things about design (much like any other creave process) is that it's an
iterave process, which means you expect to change it as the project evolves.
Adding gradients
Gradients gradually blend two colors together and are available in both the color a shape
and Fill with color tools. Let's take a quick look at using the gradient tool.
Time for action – applying a gradient
In our previous exercise, we used the Color a shape tool to apply a solid color to the stage.
Let's see what happens when we choose a gradient instead:
1. Open the stage in the paint editor if it's not already open. Then, select the color a
shape tool.
2. Next to the color palee at the boom of the editor are two color squares, one
overlaid on top of the other. You can bring the boom square to the front by clicking
on it. Clicking on a color square from the palee will assign that color to the top
square. Select two colors; we'll use them to draw a gradient.
3. Now select a gradient, which are the four squares available at the boom-le of the
editor. The rst opon is the solid ll and working clockwise, we have horizontal,
circular, and vercal. Choose one of the other gradient opons and click on the
image editor. Now, try reversing your two colors and see how the gradient changes.
Creang an Animated Birthday Card
[ 60 ]
4. The following screenshot shows a gradient along with the color opons at the
boom of the editor:
5. Now that you have a gradient opon, you may choose to connue designing your
card with it. For my card, I'm scking to a solid background.
What just happened?
If you click around the stage and apply dierent gradients, one of the things you will noce
is that color one is darkest at the point where you click onto the stage and then it gradually
fades into the second color.
There are three gradient opons. A vercal gradient will start with color one at the top of the
stage and gradually fade into the second color. A horizontal gradient starts with the rst color
to the le of the stage and transions to the second color as it lls to the right of the stage.
Use the ip le-right and ip up-down opons in the paint editor to change that orientaon.
The circular gradient starts wherever you click on the stage with color one and transions to
the second color as the circle reaches the edge of the stage.
Chapter 3
[ 61 ]
While working with gradients, the gradient will ll to a boundary created by another line or
shape. If the stage is empty, then the gradient will ll the enre space. If you draw a square
in the middle of the stage and ll the square with a gradient, the gradient connes itself to
the boundary of the square.
Time for action – adding more sprites to address the card
So far, we have not placed one block of code in our birthday card. This will change soon
enough, but we have some addional sprites to add.
For this exercise, use the paint editor to spell out the name of the person receiving the card,
but do it such that each leer is an individual sprite. This will give us more control over the
animaon of the name:
1. Use the Paint new sprite opon one by one to create a sprite for each leer of the
person who you are sending the card to. I'm sending my card to my mom, so I'm
going to spell Mom. You may choose anyone you want, but I'd recommend you keep
the name short for this exercise.
2. Aer you add the sprites, reposion the name on the stage by clicking and dragging
each leer around the stage so that they form a word. If the leers are too small,
you can resize them as needed.
3. The following screenshot shows my updated project. Note that I have three new
sprites: M, o, and m.
Creang an Animated Birthday Card
[ 62 ]
What just happened?
Happy Birthday, Mom. Now it's starng to look like a card. For the grammarians among us,
feel free to insert a comma aer Birthday.
Did you make an observaon as you dragged each leer around the stage to correctly spell
mom? You dragged the M, the o, and the m independently of one another. We can't drag
each leer in the Happy Birthday sprite around the stage. Go ahead, give it a try. You can
move the enre phrase, but you cannot separate Happy from Birthday.
This subtle but important dierence is what allows us to control the animaon of each leer in
the word mom, whereas in the Happy Birthday sprite, we can only control the enre phrase.
Initializing a sprite's starting values
As we animate the card, we need to start thinking about how the card looks when we give
it to somebody. In other words, we need to know what happens when that person clicks on
the green ag to view the card.
Time for action – hiding all sprites when the ag is clicked
We're going to animate our card, which means we're going to be changing the default
appearances of the sprites in our card. Therefore, we need to think about the starng values
of our sprites. As the rst step in our animaon, we'll hide all sprites so that we start with
a blank screen. Then, we can introduce and animate each sprite in turn as shown in the
following steps:
1. Select the Happy Birthday sprite to display its script area.
2. We'll use the click on the green ag as an event to trigger our script. From the
Events palee, drag the when ag clicked block to the scripts area.
3. From the Looks palee, snap the hide block to when ag clicked.
4. Hide each of the leers that spell mom using the same script. Try the
following shortcut:
Chapter 3
[ 63 ]
1. Right-click on the Happy Birthday script and select duplicate. The script
attaches to your mouse cursor.
2. Drag the script to one of the other sprites in the sprite list and click on it.
The script copies to the sprite.
3. Duplicate the script for the remaining sprites, with the exception of
the stage.
5. Check your work. Click on each sprite and verify whether it has the script that hides
the sprite when the green ag is clicked.
6. Click on the green ag and watch our greeng, Happy Birthday, Mom, disappear
from the screen.
7. In the current state, you can make the sprites reappear by right-clicking on each
sprite in the sprite list and choosing show.
What just happened?
As creave directors, we want control over when and how our sprites enter the stage.
For this project, we don't want Happy Birthday, Mom passively sing there, so we send
them backstage.
Creang an Animated Birthday Card
[ 64 ]
The when ag clicked block, when added to the script area for each sprite, tells each sprite
to do something when the green ag is clicked. In our example, we tell them to hide, which
clears each sprite from the stage. In the programming context, we're inializing our project.
In other words, we're explicitly seng the starng view of our card. This will be common in
most of the projects we create. In other examples of inializaon, we will somemes want
to hide or show a sprite, posion a sprite, or give a variable a specic value when the user
starts the project. Clicking on the green ag is one such event that we can use, but any of
the other Event blocks can be also used to inialize a sprite's starng values.
Time for action – displaying happy birthday
Can you imagine mom's confusion? She clicks on the green ag, and the screen goes blank.
That's like going to a play where all the actors are sing on the stage in front of the curtain
unl show me. Then, when the curtain goes up, all the actors disappear. However, we
don't go to the theater to watch an empty stage. We want actors. Without further fuss,
let's introduce our sprites:
1. Let's bring out the Happy Birthday sprite rst. Select the Happy Birthday sprite from
the sprite list.
2. From the Control palee, add the wait (1) secs block to the exisng script to create
a bit of delay and to allow the Happy Birthday sprite to display.
3. Before we show the sprite, let's set the default size, adding the set size to () block.
I set the size to 300, but your design may require a dierent value. The value inside
the set to () block is a percentage.
4. Show the sprite by adding the show block from the Looks palee.
5. Run the script by clicking on the green ag. Happy Birthday disappears and
reappears one second later. Now, let's make it pulse.
6. From the Control palee, snap the forever block in place below the show block.
7. From the Looks palee, drag the change size by () block into the forever block.
Change the value on the change size by () block to -20.
8. Add a second change size by () block to the forever loop and change the size to 20.
9. From the Looks palee, add the wait () secs block between the two change by size
() blocks and enter a value of .5 seconds.
10. From the Events palee, add a broadcast block between the show and forever blocks.
11. On the broadcast block, add a new message: hi mom.
12. Click on the green ag to make Happy Birthday pulsate on the screen.
Chapter 3
[ 65 ]
If you haven't already done so, you can stop your pulsang sprite by clicking on the
stop buon.
What just happened?
Like a beang heart, the "Happy Birthday" text contracts and expands on the stage as long as
the script runs. We get the pulsang eect from the blocks of code in the forever loop. We
increase the size by 20 pixels, and then half a second later, we decrease the size by 20 pixels.
The set size to (300) block does something very important. It resets the size of the sprite
each me it runs. Otherwise, the size of the sprite will get increasingly smaller as you run
and stop the script mulple mes because you will stop and start the script while it's in the
process of geng bigger or smaller. Let's say you stop the script during the wait () block and
aer the size was changed by -20 units. Then, when you start the script again, everything
starts from the beginning. Now, the change size by -20 block just ran a second me, but was
only negated one me. Scratch remembers state, which makes it necessary to set the size
when the green ag is clicked on. That's why we explicitly inialize the sprite's size at 300
percent each me the user runs the project by clicking on the ag. This ensures the sprite
always has a correct starng value and helps ensure the user has the correct experience.
Before our sprite enters into its innite loop, it broadcasts the message hi mom. Nothing
happened in our script as a result of the broadcast because we have not yet programmed
any other sprites to act on the hi mom message.
Creang an Animated Birthday Card
[ 66 ]
Specifying memorable names and comments
We haven't focused on naming convenons yet, but we just created a new broadcast
message with a unique name. So, I'm going to use this opportunity to introduce the
importance of naming things in our projects.
If we look closely at our list of sprites, we see the following names: Sprite1, Sprite2, Sprite3,
and Sprite4. The broadcast messages would follow an equally bland naming convenon.
If we allow this default naming convenon to connue, we'll easily lose track of our
objects in Scratch.
Time for action – renaming sprites
Let's rename our sprites by performing the following steps:
1. Select Sprite1 from the sprite list and click on the blue i icon to display the sprite
properes. Change Sprite1 to Happy Birthday.
2. Rename the remaining sprites with a memorable name, such as First M, Second M,
and O.
Each sprite in the list can now be idened by a unique name.
What just happened?
To the computer, Sprite3 is just as good as First M, but humans benet from associang
sprites, costumes, backdrops, lists, variables, and messages to a descripve name. In our
example project, we spell mom from individual sprites. How do we know if Sprite2 is the
First M or the last M? But if we rename Sprite2 to First M, we have no doubt.
In addion to providing context, names provide a way for us to easily idenfy our objects
later. For example, if we broadcast one message as message 1 and another as message 2,
we may not know which message does what when it's me to make a sprite perform an
acon based on that message. If the message becomes hi mom, then we know that the
message signals the beginning of the mom animaon.
Chapter 3
[ 67 ]
As meaningful names give us a context and understanding about the object, it helps us and
other programmers understand our code later. As you create your projects, don't rely on
Scratch's default naming. Change it as necessary.
Inserting comments into our code
A topic closely related to naming our objects is adding comments to our scripts. Adding
comments to scripts provides a way for us to explain complicated scripts. Commenng
allows us and other programmers to easily understand our code.
Time for action – adding comments to a script
Let's add a quick comment that annotates the broadcast block in the Happy Birthday
sprite's script:
1. Select the Happy Birthday script. Right-click somewhere in the scripts area and
select add comment.
2. In the yellow box that appears, type the following: the "hi mom" broadcast
signals the second m sprite to start its animation.
3. Now click on the yellow comment box and drag it to the broadcast (hi mom) block.
Then, release the block. This can be tricky, but the goal is to aach the comment to
the block. See the following screenshot:
Creang an Animated Birthday Card
[ 68 ]
What just happened?
Commenng our code is one of those things that we should always do more oen because it
helps other people understand our code. And in reality, this can help us understand what we
did when we open a project we haven't worked on in months.
Transforming sprites with graphical effects
Scratch provides two blocks in the Looks palee to allow us to apply a variety of graphical
transformaons to our sprites. The eects are color, sheye, pixelate, mosaic, brightness,
ghost, and whirl.
Time for action – transforming sprites
Next, we want to introduce the sprites that spell mom, and as we show the leers, we'll use
the graphical eects to transform the leers:
1. We're going to start by adding the when I receive () block to the scripts area for
Second M.
2. To unhide the leer M, we need to add the show () block.
3. Click on the green ag to see the script run so far. As Happy Birthday ashes on the
screen, the second leer M appears on the screen. Click on the stop buon when
you're ready to connue.
4. We're going to transform the m by using the mosaic eect and a repeat loop. From
the Control palee, snap the repeat () block to the boom of the show block and
change the value to 25.
5. From the Looks palee, add the change () eect by () block to the repeat loop.
Change the eect from color to mosaic by selecng mosaic from the drop-down
list as seen in the following screenshot:
Chapter 3
[ 69 ]
6. Click on the green ag and watch the eect of our acon. Our m is a mosaic, but it's
no longer readable. Click on stop when you're ready to connue.
7. From the Looks palee, double-click on the clear graphic eects block to redisplay
the leer m. A shortcut to run the block is to click on the block name, which in this
case clears any eects.
8. Snap another repeat () block to the boom of the rst repeat () block and set the
value to 25.
9. Insert a second change () eect by () block into the new repeat 10 block. Change the
eect to mosaic and set the value to -25.
10. If you run this script now, the mosaic happens quickly. You can slow down the eect
so that it's visible by adding a wait () secs block aer each of the change () eect by ()
blocks. Try a small value, such as .1.
11. Next, we need the script to announce when it's nished so we can signal the next
leer in the animaon. Add a broadcast () block and create a new message named
next m.
The following screenshot shows the script we've just created:
Creang an Animated Birthday Card
[ 70 ]
To see what that script does, click on the green ag. The following screenshot shows the
change in the leer m as we apply the change (mosaic) eect by (25) command:
The following screenshot shows the nished product aer we apply the change (mosaic)
eect by (-25) command:
What just happened?
Finally, we acknowledged the Happy Birthday sprite's hi mom broadcast message. Hi mom
was the cue that told Second M to enter the stage with dramac eect.
Once the leer "m" displayed, it split apart to form a paern of its own before it reconstuted
itself into a whole leer. The code that created our paern was straight forward. First, we split
the "m" into a mosaic 25 mes via the repeat () block, which turned the single leer into 25
smaller copies of itself.
The second repeat () block also ran 25 mes, but it changed the mosaic eect by -5 units
each me. The second repeat block undid the eects of the rst repeat () block through
negaon. This has the praccal eect of running the clear graphical eects block with a big
dierence. The clear graphical eects block will abruptly turn the sprite back to its original
state. By using a second repeat () block to undo each step of the rst repeat () block, the
animaon connues unl the sprite returns to normal.
Chapter 3
[ 71 ]
Graphical transformations
We can change the appearance of a sprite very easily, as we have seen with the Happy
Birthday card, and Scratch includes several special eects that we can apply directly to the
sprite or its costume.
The eects in the following table can be found in the change () eect by () and set () eect
to () blocks in the Looks palee.
Effect What it does Sample usage
color This effect changes the color of the
sprite. A sprite or costume can have
up to 200 color effects.
While creang art
To visually signify a different state
fisheye This effect distorts the sprite by
rounding the edge as if you're
looking at it through a glass or peep
hole.
To distort the sprite
For use as a transition effect
whirl This effect twists the sprite around
a center point and produces an
effect similar to throwing a pebble
in the water. The greater the whirl
effect, the more difficult it is to see.
To distort the sprite
For use as a transion eect
To give a spin
pixelate This effect increases the size of the
pixels in the image so that you can
see them. However, it creates a
blurry image.
To blur an image
For use as a transion eect
To cover up another sprite
mosaic This effect splits the sprite into a
pattern of smaller images of itself.
For use as a transion eect
To split a single sprite into
multiple
Creang an Animated Birthday Card
[ 72 ]
Effect What it does Sample usage
brightness This effect increases the luminance
of the sprite to make it appear
brighter.
To make a sprite glow
To make a sprite dimmer
ghost This effect makes the sprite
transparent so that you can see
other sprites and backgrounds
through the sprite. A value of
100 hides the sprite by making it
completely transparent; -100 shows
the sprite.
To hide a sprite
To create a fade in/out eect
To create transparency
(like a ghost)
The following screenshot shows all the graphical eects as applied to Gobo:
In the preceding screenshot, the eects on the rst row are normal, color, sheye, and whirl.
The eects on the second row are pixelate, mosaic, brightness, and ghost. All the graphical
eects can be undone by clicking on the clear graphic eect block. You can also undo the
eect by negang the original eect. For example, if you set a sheye eect of 100, you can
return to normal by applying a sheye eect of -100.
Comparing the repeat and forever blocks
Like the forever block, the repeat () block creates a loop that runs the blocks inside the loop.
The repeat () block diers from the forever block in that we specify the count for which the
loop will run.
In addion to typing a number in the repeat block, we can insert variables values via reporter
blocks. We will introduce variables in Chapter 6, Making an Arcade Game – Breakout (Part I).
Chapter 3
[ 73 ]
Time for action – turning m in a circle
When we last le our animaon, we had the second M displayed on the screen. Now, let's
create the script that receives and acts on the next m broadcast message by spinning the
First M sprite around in a circle:
1. Add the blocks to show the First M sprite when it receives the next m broadcast
message. If you get stuck, you can take a peek at the screenshot in this exercise.
2. Instead of a graphical eect, we can animate this script with moon by rotang
the First M sprite. From the Moon palee, add the turn () degrees block to the
show block.
3. Wrap the turn () degrees block in a repeat () block. Change the value on the repeat
block to 36 and set the value on the turn () block to 10.
4. Check your animaon by clicking on the green ag. Note the moon on the First M
sprite as it spins 360 degrees in a circle.
5. Now that the First M sprite is nished with its animaon, we need to add a broadcast
() block and create a new message named gimme an O to signal the leer O.
Creang an Animated Birthday Card
[ 74 ]
What just happened?
When signaled by the Second M's broadcast message, First M tumbled onto the stage.
The repeat () block instructed the M to turn 10 degrees clockwise for a total of 36 mes.
If we mulply 10 degrees by 36, we get 360 degrees, which is otherwise known as a circle.
Have a go hero – cleaning up the animations
Earlier in the chapter, we spoke about inializing our sprites so they always display properly
at the start of the project. Go through the sprites we've transformed and ensure they have
scripts that reset the sprite to a default starng point. The First M sprite is using moon. Can
you add a block to ensure it's always poinng in a posion that looks like an M?
Test your work by stopping the project mid-animaon and then clicking on the green ag to
start it again.
Finally, complete the "mom" animaon by showing and animang the leer "o" sprite.
Time for action – making a sprite fade in with the ghost effect
Let's put some nishing touches on our card by adding a buery and a personal message
to mom:
1. To add a new sprite, click on the Choose sprite from library buon to open the list
of sprites. Browse to Animals. Find and select Buery1. Click on OK to add it to
the stage.
2. Scratch places the buery at the middle of the stage, so we need to drag the
buery to a place on the stage where it ts into the design.
3. We should add a personal note for mom on her birthday. Use the paint editor and
create a new sprite that contains your message. I like to joke with my mom, so for
my message, I have typed Congratulaons on your ability to freeze me. I hear
you are only 29 again this year.
4. Resize and reposion the sprites on the stage so that they t nicely. Take a look at
the following screenshot for an example.
Chapter 3
[ 75 ]
5. Right now, the note and the buery are not animated, and they remain on the
screen for the enre me. We'll change that now by experimenng with a new
graphic eect called ghost.
6. Add the when ag clicked block to the scripts area for the note and add the change
() eect by () block. Change the eect to ghost. Set the value to 100. This eecvely
hides the sprite.
7. We don't want the note to show up right away, so add a wait () secs block with a
value of 9 seconds, and make sure you place it aer the change (ghost) eect by
(100) block.
8. Add a repeat () block and change the value to 20.
9. Inside the repeat () block, add a change () eect by () block. Change the eect to
mosaic and set the value to -5.
10. As the script is wrien, the note will fade in very fast. Go ahead and try it by clicking
on the green ag.
11. To slow the fade, we can add a wait () secs block to the repeat (20) block and set a
value of 0.2.
12. Click on the green ag to run the script. Now, our note fades in three seconds aer
we click on the green ag and aer the word mom displays.
Creang an Animated Birthday Card
[ 76 ]
13. The script for the note should look like the following screenshot:
What just happened?
There is oen more than one way to accomplish a task, as this exercise illustrates. Seng
the ghost eect to 100 is the same as making the sprite invisible or hiding it. So, if you were
creang a game where you wanted a sprite to disappear when shot, you could hide it or use
the ghost eect to slowly fade out.
In our birthday card example, we repeat the ghost eect by -5 for 20 mes. Guess what our
ghost value becomes? If we mulply 20 by -5, we get -100, which negates the ghost 100
eect we started with, eecvely showing the sprite.
To control the ming of the animaon, the .2 second wait at the end of the repeat loop
slows down the fade so that we have a gradual transion.
Two ways to control timing
In this chapter, we've used both broadcasts and the wait () block to control the ming of our
animaons. Let's take a moment to discuss the ramicaons of our decisions.
As we have seen in the examples in this chapter, the broadcast () block gives us a way to
synchronize events across sprites. For example, when we animated the word mom in our
card, we actually brought the second "m" in rst, and at the end of the eect, it signaled
the rst "m" to display. A broadcast can be sent to any sprite within Scratch.
The wait () secs block pauses the script for the amount of me specied. However,
the wait () secs block does not stop other scripts and only interacts with the sprite it's
assigned to. It eecvely creates a mer or a delay for the script.
Chapter 3
[ 77 ]
Trying to use the wait () secs block to synchronize the acons of all our sprites could be a
considerable challenge. Could you imagine the revisions we would have to make if we used
the wait () secs block throughout our animaons in this chapter? Every me we alter the
animaon, we would potenally have to go back through every script to manually set the
ming. That's a tedious prospect.
Have a go hero – animating the buttery
Our birthday card is relavely complete. At the moment, all sprites are animated except the
buery. Take this opportunity to revise your card or add an animaon to the buery. Need
some ideas? The buery has two costumes. Make it y.
Pop quiz – reviewing the chapter
Q1. Which of the following statements is true about vector and bitmap graphics?
1. Vector graphics are represented by pixels on the screen.
2. Bitmaps use calculaons to draw lines.
3. Bitmap images are smooth at any size.
4. Vector graphics are smooth at any size.
Q2. When naming sprites, you should always:
1. Allow Scratch to dene the name.
2. Forget about names because they're not important.
3. Pick memorable, meaningful names.
4. Use names based on Greek gods.
Q3. Which of the following best describes a gradient?
1. Gradients ll an area with a solid color.
2. Gradients are only available to vector graphics and transion one color into
another color.
3. Gradients are an opon in the change () eect by () block that fade two
colors together.
4. Gradients gradually blend two colors together and are available in both the vector
and bitmap image editor.
Creang an Animated Birthday Card
[ 78 ]
Q4. If you want to loop through a set of blocks for an innite number of mes, which block
do you use?
1. forever
2. repeat
3. broadcast ()
4. set () eect by ()
Q5. Which of the following graphical eects splits a sprite into a paern of smaller images
of itself?
1. whirl
2. pixelate
3. mosaic
4. brightness
Q6. How do you copy a script from one sprite to another?
1. Right-click on the script, select duplicate, and drag the script to the second sprite.
2. Highlight the script, press Ctrl + C to copy it, and press Ctrl + V to paste it on the
second sprite.
3. Both 1 and 2.
4. You can't copy scripts from one sprite to another.
Summary
We just completed our rst Scratch project from concept to compleon. In the process,
our animated birthday card introduced us to several Scratch programming concepts.
We started by using the built-in paint editor to create sprites and explore the dierences
between bitmap and vector graphics. We then animated these sprites by using graphical
transformaons. Throughout the chapter we relied on the following blocks to make the
animaons work: forever, repeat (), and broadcast () and wait () secs.
In the next chapter, we will create a storybook with mulple scenes. We'll also build
navigaon that lets the user click through the chapters.
4
Creating a Scratch Story Book
Building on the design and graphic elements we've learned in the previous
chapters, we will create a book of barnyard jokes. The project unfolds in a fairly
non-linear way, and the scripts are built and tested several blocks at a time, but
as we near the end of the chapter, we come to create a seamless transition from
the table of contents to a joke and back again. In this chapter, we'll provide a
framework that empowers the user to pick their flow through the project.
In addion to praccing our storytelling skills, we will:
Design the book's outline
Use the say () block to deliver the chapter jokes
Play sounds and create sound eects
Move sprites based on x and y coordinates
Coordinate scene changes to navigate the book
Designing the outline of a barnyard joke book
Got a good joke or two? Feel free to substute them for my examples in the following
exercise. Our rst step is to create a table of contents that users can use to navigate the
jokes in our book.
Creang a Scratch Story Book
[ 80 ]
Time for action – designing a clickable table of contents
For our storytelling project, we will create buons with labels that the user can click to open
each joke sequence, which we'll make analogous to a chapter in our Scratch book. We'll refer
to these buons as our table of contents. The steps to design a clickable table of contents
are as follows:
1. Open a new project and delete the default Scratch cat sprite.
2. Let's import a buon sprite into Scratch. For this project, I'm choosing the Buon2
sprite from the Things category because it's a vector image and it has two costumes.
Change the sprite name to Dog TOC so that we can idenfy this buon as something
that appears on our table of contents page.
3. Aer you import the buon into the project, click on the Costumes tab to open up
the paint editor. We need to add a label.
4. Use the text tool to type Dog in any font you want.
5. Resize the text and posion the word Dog so that it ts inside the buon. Because
this is a vector image, we can make the buon as big or small as we want.
6. Create a new sprite using the text tool that says Click on a button to open
the chapter. Then, name the sprite Instructions.
7. Duplicate the Dog TOC sprite and edit the text of the duplicated buon to say
Horse and name the new buon Horse TOC. The following screenshot shows
our new sprites:
Posion the sprites anywhere you like on the screen.
Chapter 4
[ 81 ]
What just happened?
Our book now has a table of contents. You will be able to add to this at a later date, but
creang two chapters will be enough to get us started. By using a combinaon of the sprite
library and the image editor, we were able to create a buon with a label. As we connue
to build the book, we'll make the buons clickable.
Time for action – adding pages to the book
Next, we are going to add two background images from the Scratch Backdrop Library to our
project to represent pages in our book.
We'll adapt our backdrops by combining them with a sprite to create something unique for
our project. Our objecve is to create a single image from a backdrop and a sprite. I'll explain
the nuances of this task aer we complete the exercise rather than try to explain the reasons
as we go.
With the stage selected, let's get started:
1. Use the Choose backdrop from library buon on the Backdrops tab to import
bedroom1 from the Indoors category and hay eld from the Outdoors category.
2. From the Backdrops tab, select hay eld to open it in the paint editor. Convert the
image to vector format, or you'll have unsasfactory results when we import the
microphone in the following steps.
3. Next, we're going to import a microphone into the project that we'll use as a visual
aid for our scenes. Choose the Microphone Stand from the Things category in the
Sprite Library. Aer you import the microphone as a sprite, open the Backdrops tab
for the stage and select hay eld.
4. From the list of sprites (beneath the stage), click and drag the Microphone sprite
into the hay eld backdrop in the paint editor. This places the sprite into the
backdrop as seen in the next screenshot.
Creang a Scratch Story Book
[ 82 ]
5. We can posion and resize the microphone object in the paint editor by clicking on
it with the select tool and dragging it around the image. For our purposes, posion
it in the boom-right of the stage. The following screenshot shows the status of our
project so far. Noce that our stage displays two microphone stands. One is a sprite
and the other is part of the backdrop. We'll x this in due me, but let's pause to
review our exercise rst.
What just happened?
The backdrops we added begin to provide some graphical context to our story. For example,
many pet dogs like to spend their days inside on a bed, and while we may not nd horses
roaming the hay elds, they do eat hay. It's up to us to use design eecvely in our stories.
We're also able to suspend our disbelief as we create our story. It does not maer if you put
your horse on the moon or your dog in an aquarium.
The microphone adds a layer to the story. This is a joke book, and the microphone is a
perfect way for our characters to deliver the joke.
In addion to the design, we also discovered a technical feature of Scratch. Scratch 2.0
convolutes the process of combining sprites into a single image, but as the example
demonstrated, it's possible to combine them. Combining sprites with backdrops allows
us to further customize the sprites and backdrops included with Scratch.
If you didn't follow the instrucons closely and le the hay eld backdrop as a bitmap
image, you will have noced a white box around your microphone when you added it to
the backdrop. Undoing the change and converng the backdrop to vector format before
you add the microphone will get a seamless image.
Chapter 4
[ 83 ]
Now our hay eld backdrop consists of two objects: the original backdrop and the microphone
stand. We'll be able to edit those objects independently if we edit the backdrop, but when the
backdrop image displays on the Scratch stage, it will appear as one image.
For this project, I made a design decision to integrate the two images because it will create
one less sprite in my list and will be one less sprite that we have to manipulate as we
transion our chapters. This decision has a tradeo. We will not be able to independently
add scripts to the microphone in our project because we made it part of the backdrop.
Time for action – adding a sprite to the Backpack
Right now, our project sll displays the extra microphone sprite we imported. That was
a necessary step so that we could combine the sprite with the backdrop; however, it's
cluering our project. And because we will want to use this same microphone throughout
our chapters, we don't want to have to re-import the microphone each me. We'll decluer
our project by using Scratch's Backpack. The Backpack is a feature in the online project
editor for users who are signed in. If you're not signed in to the online project editor, the
Backpack will not be available.
Let's work through the steps, and then we'll explain:
1. The Backpack is collapsed (that is, closed) at the boom-right of the Scratch
interface. You can open it by clicking on the up triangle next to the word Backpack.
2. Drag the Microphone Stand sprite into the open Backpack to create a copy.
3. Now, you can delete the Microphone Stand sprite from the sprites list by
right-clicking on the sprite thumbnail in the sprites list and choosing Delete.
4. Now let's see how we can add the microphone to the bedroom backdrop.
Open the bedroom1 backdrop in the Backdrops tab so that it displays in the
paint editor.
5. From the Backpack, drag the microphone onto the bedroom1 backdrop in the
paint editor.
6. Resize and posion the microphone object as needed.
Creang a Scratch Story Book
[ 84 ]
7. The following screenshot shows the microphone in the Backpack and the sprite
added to the backdrop:
What just happened?
Welcome to the Backpack—a new feature in Scratch 2.0. We're making a creave but
modest use of the feature in the context of this project as a way to combine the microphone
with any backdrop that we add in the future.
The benet we get from removing the unused sprite is that our sprite list stays cleaner and
we don't have to worry about inadvertently showing the Microphone Stand sprite when it
shouldn't be shown. In other words, we limit our ability to make future mistakes.
Using the Backpack to store sprites and scripts
As our project example demonstrates, the Backpack can hold things, but it's capable of
holding more than just a sprite.
When you drag a sprite to the Backpack, it will copy the sprite, its costumes, and all of
the scripts associated with the sprite. In addion, you could drag an individual script to
the Backpack.
Chapter 4
[ 85 ]
The Backpack is only available online and to users who sign-in to Scratch.
And like a backpack on a second-grader, the contents of the Scratch Backpack follow the user
from one project to the next. So, the sprites and scripts we add to the Backpack will now
will be available to all of the projects we create, edit, or remix, making the Backpack our
portable collecon of our favorite things.
If we create a script that you think may be useful in the future, feel free to add it to
your Backpack.
Building a joke with say blocks and sounds
Now that we have the basic page designs dened via our backdrops, let's add in a horse as
our character for the hay eld scene and write some lines for its comedy roune.
Time for action – making a horse talk with the say block
Right now, we have the Dog TOC and Horse TOC sprites displayed on the screen. Go ahead and
hide them from the stage by right-clicking on the sprites and selecng hide. Then, make sure
the hay eld displays on the stage by clicking on the hay eld backdrop from your list of stage
backgrounds:
1. Import the horse1 sprite from the Animals category of Scratch's Sprite Library.
2. Posion the horse next to the microphone by dragging the sprite on the stage with
your mouse. If the horse and microphone seem out of proporon, resize the horse
sprite using the shrink or grow tools.
3. Next, we'll try our hand at joke wring. Click on the Scripts tab to get started.
4. From the Looks palee, drag the say () for () block into the script area. Change the
message from Hello! to How do you make it rain?. Change the me value to 4.
5. If the sprite is close to the edge of the stage, the speech bubble that displays from
the say block may appear at the backend of the sprite. If this happens, move the
sprite away from the edge.
6. Add a say () for () block. Change the message to Mow a hay field, and change
the me from 2 seconds to 3. I didn't say we were going to write good jokes; check
with your local farmer to understand the relaonship of hay making to rain. In all
sincerity, you can write any joke you want.
7. Add a wait () secs block. Change the me from 1 to 3 seconds.
Creang a Scratch Story Book
[ 86 ]
8. Add the say () for () block to the script. Change the message to Hello, is this
thing on?.
9. Double-click on the script to watch our horse tell its rst joke.
What just happened?
We wrote a short script to deliver the joke using the say () for () blocks to display speech
bubbles, and aer three seconds of silence, our horse tossed out a comedic cliché, "Is this
thing on?"
We used two variaons of the say block. For the joke and punchline, the horse speaks for a
specied number of seconds. However, at the end of the script, the say block we added did
not specify a me value. And if you look at the stage, you'll see that the speech bubble sll
displays Hello, is this thing on?. We're going to use that say block to our advantage in the
next exercise.
Time for action – synchronizing and animating the horse
The rst part of this exercise will be familiar to you. We want to animate the horse using
its costumes. However, we'll combine that animaon with another say block to create a
uid scene:
1. Connue building the script by adding a next costume block.
2. Add a wait () secs block.
3. Add a next costume block. Note that since we are not actually going to call the
name of the costume for the horse1 sprite, we're not going to take the me to
rename them from their defaults.
4. Add a say () block with an empty input value.
5. Double-click on the script to run the code.
Chapter 4
[ 87 ]
What just happened?
It was a tough crowd, and the joke fell at, causing the horse to nervously rear up on its hind
legs and say Hello, Is this thing on?. Even though our script technically runs the say (Hello,
Is this thing on?) block before switching to the costume of the horse on its hind legs via the
next costume block, any delay between the two acons is going to be dicult to noce,
which is the intenonal eect; we want those two acons to happen in a uid way.
By adding a say () block at the end of the script with an empty value, we clear the speech
bubble. The dierence in the two say blocks warrants some discussion.
When we use a say () for () secs block, the speech bubble displays on the stage for the
amount of me specied, and more importantly, the script stops when the specied me
elapses. If we use the say () block with no me value, the speech bubble displays and the
script connues, meaning we can animate the sprite while the speech bubble displays as
we demonstrated in our script.
Speech bubbles enable us to convey a conversaon; however, the text can only be displayed
on the screen. While it would be cool to have a computer-generated voice read the value
of the say block, that's not yet possible in Scratch. Maybe we can ask the Scratch Team for a
feature enhancement.
For our next exercise, we're going to add some prerecorded sounds from Scratch's library.
Time for action – importing a horse sound
Let's add some further context to our story by incorporang some actual sounds. As we'll
see in the exercise, Scratch includes a horse sound, making it relavely easy to create some
themac stories based on the included media:
1. With the horse sprite selected, click on the Sounds tab.
2. Click on the Choose sound from library buon to display Scratch's sound library.
Creang a Scratch Story Book
[ 88 ]
3. Browse to the Animal category and select Horse.
4. To demo a sound before you import it, click on the play buon next to each sound.
5. Click on OK to add the sound to the list of sounds for the horse sprite. To listen to
the horse whinnying, click on the play buon in the sound editor.
6. Duplicate the horse sound by right-clicking on the sound and selecng Duplicate.
7. Select all of horse2 in the sound editor and apply the soer eect. To select the
sound wave, click on the le-hand side of the sound editor and drag your mouse to
the le. This is the same selecon technique we used to highlight text in a document.
8. Let's give horse2 a beer name. Change the name to horse soer to correspond
to the eect we used. You can change the name of the selected sound above the
sound editor.
9. Now let's add the sound to several places in our script. From the Sound palee, add
the play sound unl done block to the top of the script and select the horse sound.
10. Insert a second play sound () unl done block aer the say (Mow a hay eld) for (1)
secs block. Select horse soer as the sound to play.
11. Insert the play sound () block aer the next costume and before the wait (1) secs
block. Select horse as the sound to play.
12. The following screenshot shows our script so far:
What just happened?
We used Scratch's sound library to add a horse sound to the scene as we connued to build
our story. We introduced the horse with a whinny, and then we reiterated the sound aer
the joke's punchline.
Chapter 4
[ 89 ]
By duplicang the whinny and applying the soer eect, we created a mid horse. Right
about then, the horse is realizing that if he has to explain the joke, it's not a good joke.
At the end of the script, we used the plain play () sound block to play the horse sound
while the script connues to run. This allowed the horse to do several things at one me:
say Hello, Is this thing on?, rear up, and whinny. This combinaon at the end enabled us to
reinforce the nervous horse idea.
Playing supported sound formats
Scratch includes a library of sounds that you can use in any of your projects, and you can
also easily import your own sounds. The Upload sound from le buon on the Sound tab
provides a dialog box that lets you select sounds on your own computer.
In addion to the MP3 format, Scratch can play uncompressed WAV, AU, and AIF sound les.
Positioning a sprite by its coordinates
With our horse scene complete, we'll move on to the dog. Our dog is also a comedian, but
in this scene, we're going to be moving the dog across the stage. Therefore, we'll have to
posion the sprite to be exactly where we need it to be in order for the scene to play out.
Time for action – moving the dog based on x and y coordinates
In this exercise, we're going to use the x and y coordinates to move our dog:
1. Let's prepare the stage by hiding the horse1 sprite by right-clicking on the
thumbnail in the sprites list and choosing Hide. Then, display the bedroom1
backdrop on the stage.
2. Next, add the dog2 sprite from the Animals category of Scratch's sprite library.
3. Posion the dog so that it's talking into the microphone. Resize the sprite as necessary.
4. With the dog in posion, let's nd the x and y coordinates of the sprite so we
can ensure the dog always returns to this posion. Select the dog2 sprite in the
sprite list and then click on the i icon on the sprite thumbnail to display the sprite
properes pane as seen in the following screenshot:
Creang a Scratch Story Book
[ 90 ]
5. Now, we'll create the script that always returns the dog to the spot in front of the
microphone. From the Moon palee, drag the set x to () block to the scripts area.
Change the value to the dog's x value. My example uses 22.
6. Add the set y to () block. Change the value to the dog's y value. My example uses -88.
7. Let's idenfy some coordinates on the le-hand side of the stage by the desk
because we will want our dog to move there aer it's done telling the joke. As
you move your mouse around the stage, Scratch tracks the x and y posion of the
mouse. The informaon displays the x: and y: values in the space between the stage
and the New sprite icons as seen in the following screenshot:
8. From the Moon palee, add the glide () secs to x: () y: () block to the scripts area,
but do not aach it to the set x: (22) and set y: (-88) blocks.
9. The glide () secs to x: () y: () block is populated with the current x and y coordinates
of the selected sprite. Let's change the coordinates to where we want the dog to go.
Change the x value to -138 and the y value to -2. Change the secs value to 2.
The more seconds you add to the glide block, the longer it
takes the dog to reach its coordinates.
10. Run each script by clicking on each stack and observe how the dog changes
posions. The following screenshots show the scripts so far:
11. The following screenshot shows the result of the glide block by posioning the dog
next to the bed and in front of the desk:
Chapter 4
[ 91 ]
What just happened?
We issued a series of commands and our dog responded with precision. The rst script sets
the dog's X and Y coordinates next to the microphone. The second script moves the dog to
the new X and Y coordinates in front of the desk by gliding to the point over the course of
two seconds. If we wanted the dog to amble along, we could set the value to a higher value,
such as 10 seconds.
When we built the horse scene, we didn't need to know the posion of the horse because it
didn't move. Each me we displayed the horse, it was in the same locaon.
However, the dog will change posion as the scene plays out, and since Scratch remembers
the sprite's previous posion, we need to ensure that the dog always starts in front of the
microphone when the scene starts.
Did you noce that the dog walked backwards when you ran the glide block? Of course you
did. We'll x that up in due me.
Locating sprites with x and y coordinates
Scratch uses the Cartesian coordinate system to dene the posions on the stage. If you're
not familiar with the Cartesian coordinate system, it's basically a set of two points (numbers)
that describe a locaon. There are a lot of everyday items that are located by describing them
in terms of two points. For example, a street address is generally described in terms of a street
name and a number, as in 352 Main Street. In another example, spreadsheets are comprised of
cells that are located by a leered column and a numbered row. Here, B2 represents the cell in
the second column, second row of the spreadsheet. Cartesian coordinates are represented in
terms of x and y posions, as our previous example demonstrated.
Creang a Scratch Story Book
[ 92 ]
The x axis divides the stage into equal halves horizontally, and the y axis divides the
stage into equal halves vercally. The two axes intersect in the middle of the screen
or at coordinates 0,0 to form four equal quadrants, or blocks.
If a sprite has a posive x value, it's posioned in the right half of the stage. If a sprite has a
posive y value, it's posioned in the top half of the stage. A negave x value can be found in
the le half of the stage, and a negave y value can be found in the boom half of the stage.
The following screenshot shows the Scratch stage with an x and y grid as a background.
The background displays the four equal quadrants with key points labeled. This grid is
one of Scratch's included backdrops and provides a very nice graphical representaon
of the coordinate system.
When we locate a sprite on the stage by the coordinates, Scratch uses the center point of
the sprite to determine exactly where the sprite is placed. We'll explore the sprite's center in
more detail in Chapter 6, Making an Arcade Game – Breakout (Part I).
The following table denes several key coordinates on the stage. The coordinates are listed
in the format (x, y).
Coordinates (x, y) Location
(0,0) This marks the center point of the stage.
(240, 0) The x=240 identifies the right edge of the stage. The y=0 represents
the vertical midpoint on the right edge of the stage.
(-240, 0) The x=-240 identifies the right edge of the stage. The y=0 represents
the vertical midpoint on the right edge of the stage.
Chapter 4
[ 93 ]
Coordinates (x, y) Location
(0, 180) The y=180 identifies the top edge of the stage. The x=0 represents
the horizontal midpoint on the top edge of the stage.
(0, -180) The y=-180 identifies the bottom edge of the stage. The x=0
represents the horizontal midpoint on the bottom edge of the stage.
Creating a new costume
Most dogs don't walk across the room backwards like ours does. Let's get our dog walking
forward by creang a new costume that points in the direcon we want to go.
Time for action – duplicating, ipping, and switching a sprite's
costume
We've established throughout our exercises in this book that sprites have costumes, and we've
chosen sprites that have more than one costume because it's been convenient to our projects.
We can, however, add costumes to a sprite. In this exercise, we'll add a costume by duplicang
an exisng costume as follows:
1. With the dog sprite selected, click on the Costumes tab.
2. Right-click on the dog2-b costume and select duplicate to create a fourth costume
called dog2-b2.
3. Select the dog2-b2 costume and then click on the ip le-right buon at the top of
the image editor. The costume dog2-b2 now faces to the le.
4. Name the costume face le. Also, change the name of dog2-a to face right. See the
following screenshot:
Creang a Scratch Story Book
[ 94 ]
5. To use the new sprite, add the switch costume to () block to the top of the glide
block. Select the face le costume.
6. Add another switch costume to () block to the top of the script that starts with the
set x to (22) block. Select face right as the costume.
7. Click on each script to run the blocks of code.
What just happened?
Costumes change the appearance of the sprite, and in this case, duplicang a costume
and ipping it horizontally points the dog in the opposite direcon. We used the switch
costume to (face-le) block to display the le-facing costume before we glide. When we
posion the dog in front of the microphone, we use another switch costume to block to
posion the dog correctly.
Comparing costumes to sprites
We'll use the following denion from the Scratch Wiki to describe a sprite. Sprites are the
objects that perform acons in a project. While the stage can also be programmed in a project,
most projects have at least one sprite as well because only sprites can move. We can think of
the "acons" as a reference to the scripts, costumes, and other properes that we assign to
a sprite. I generally will not refer to sprites as objects because sprites is a more specic word;
however, it's worth menoning sprites as objects because other people, parcularly people
from a computer science background may tend to think in terms of objects.
We use a costume to manipulate the appearance of the sprite by switching between the
costumes. Another way to think about costumes would be as frames, as in the frames of an
animaon. By using costumes, we can easily make a sprite run, walk, dance, or explode into
pixels. In our previous exercise, we switched to a costume to point our dog in the direcon
we wanted to make it walk. There could be other ways to script this behavior, but the
switching costume approach accomplishes the goal simply.
Chapter 4
[ 95 ]
In our exercise, we duplicated an exisng sprite's costume, but you can also add a costume
by drawing it or by imporng a costume from Scratch's library (at the top of the Costumes
tab). When working in a Scratch project, it's possible to import a sprite with costumes or just
one costume.
The Scratch Library has the benet of including many sprites that are packaged with mulple
costumes that provide a great way to jump-start our animaons. When you choose a sprite
from the library, you can tell if the sprite has costumes by clicking on its thumbnail. The
number of costumes will display below the sprite costume. The Breakdancer1 sprite, as seen
in the following screenshot, includes three costumes that will be imported with the sprite:
If you're working from the Costumes pane and want to import a single costume into the
sprite you're eding, then you Choose costume from library from the New costume icons.
The dierence between choosing the costume versus choosing the sprite is that choosing a
costume shows all the individual costumes of sprite for selecon. The following screenshot
shows the three costumes that are available to the Breakdancer1 sprite when you use the
Choose costume from library opon in the Costumes tab:
Composing custom sound effects
Earlier in the chapter, we used the play sound () block. Scratch includes several
sound-related blocks, such as the play (drum) block, that allow us to create music
and sound eects for use in our projects.
Creang a Scratch Story Book
[ 96 ]
Time for action – creating drum sound effects
Let's try our hand at creang a drum eect that plays on the punchline of the dog's joke.
We'll create the dog's joke in the next Have a go hero exercise:
1. From the Sound palee, drag the set tempo to () bpm block to the script area,
but do not aach it to an exisng stack of blocks. Change the bpm value to 150.
2. From the Sound palee, add a play drum () for () beats block. Use the block's
default value (a snare drum for .25 beats).
3. Snap the rest for () beats block from the Sound palee to the script and change
the value to .4.
4. Add two more play drum () for () beats blocks, leaving the drum value set to one.
Change the beats value to .1 for both.
5. Add another play drum () for () beats block to the end of the script and change
the drum value to 4 (Crash Cymbals). Set the beats value to .5.
6. Click on the stack of blocks to listen to the eect.
Feel free to tweak the values and experiment with the sound.
What just happened?
By arranging three blocks to aect the drum eects, tempo, and rest, we created a familiar
da dat dat chsh drum roll. If we wanted a faster pace, we could set a higher beats per
minute (bpm) value in the set tempo to () bpm block. We're going to use this sound eect
to punctuate the punchline of the dog's joke, which we haven't wrien yet.
Creating sound effects and music
In the Sounds palee, Scratch provides several blocks that can be used to create sound
eects (as we did) or to create your own musical scores. The following table lists the sound
blocks that will help you create your own music and sound eects:
Chapter 4
[ 97 ]
Block Description
play drum() for () beats Select from a variety of percussion instruments,
including drums, cymbals, triangles, cowbells, and
hand claps. You can also set the number of beats
the drum plays for.
play note () for () beats Specify both the note to play and the beat. Notes
are annotated with numbers in a range of 0 to 127,
and the pitch gets higher as the number increases.
A list of predefined numbers and notes are
available in the note drop-down list, including the
following key notes:
48 – low C
60 – middle C
72 – high C
set instrument to () Use in conjunction with the play note block to set
the instrument for the note. The current instrument
values are between 1 and 21 and include a variety
of options including drums, organs, and flutes.
rest for () beats The block plays silence for the specified number of
beats. The default value is .25.
set tempo to () bpm Specify the beats per minute (bpm) that the note
or drum plays. The higher the bpm, the faster the
tempo.
change tempo by () Increase or decrease the tempo by the specified
amount. Use a negative number to decrease the
tempo.
set volume to () The default volume is 100 percent, but you can limit
the volume with this block. The change volume by
block can also be used to increase or decrease the
volume.
Have a go hero – writing a joke sequence for the dog
You should be able to build the joke sequence for the dog without much help from me. Feel
free to incorporate your own joke, but I'm going to use a top three list, as in "What are the
top three reasons dogs don't use computers?" The responses will be:
It's hard to read the monitor with your head cocked to one side.
They can't stop hunng the mouse.
CarPAW Tunnel Syndrome!
In the next exercise, we'll refer to this block of code as the joke sequence.
Creang a Scratch Story Book
[ 98 ]
Time for action – integrating the dog's joke sequence
With jokes in hand, let's integrate them into our scene:
1. Snap the joke sequence to the script that ends with the set y to () block. In the next
screenshot, my joke sequence is everything between the say (What are the top
three reasons dogs don't use computers?) for (4) secs and say (CarPAW Tunnel
Syndrome!) for (3) secs blocks.
2. Add the stack that ends with the glide (1) secs to x: (-138) y: (2) block to the end of
the joke sequence. Check your work against the following screenshot:
3. Now let's add our drum eect to the script. We have three jokes; therefore, we will
use a broadcast () and wait block to play the drum eect aer each line. Aer each
joke, insert a broadcast and wait block. Create a new broadcast message named
play drums and select the play drums message in each broadcast () and wait block.
4. Add a when I receive () block to the top of the drum eects stack and select the play
drums message.
5. Double-click on the stack that contains the joke sequence to watch the scene unfold.
Chapter 4
[ 99 ]
What just happened?
We took our disparate stacks of code and combined them into two stacks that execute
our scene. The broadcast () and wait block is signicant to the ming of our scene. The
broadcast (play drums) and wait block pauses the script unl all the code in all of the
when I receive (play drums) blocks run. The broadcast () block by comparison will send the
broadcast message and connue running the blocks in the remainder of the stack regardless
of whether or not the code aached to the when I receive () block completes or not.
Aer we complete our work in Chapter 7, Programming a Challenging Gameplay – Breakout
(Part II), you'll recognize that we could also use custom blocks, which is a new Scratch 2.0
feature to create procedures. In our script, one way would be as good as the other.
Have a go hero – adding context to the dog's scene
We have an opportunity to customize the dog's behavior extensively. Here are a couple of
suggesons. Can you make the dog lie on its back on the bed? As another example, one of the
dog's costumes has a raised eyebrow, which might be a good expression to show aer each line
of the joke. I'm sure you can come up with some ways to add meaning to the scene.
Creang a Scratch Story Book
[ 100 ]
Navigating the story and coordinating scenes
With the majority of the project complete, the only steps le are to add some controls to the
project so our readers can click from one scene to the next.
Time for action – hiding the table of contents
For navigaon, we want to give users the ability to click on an item from the table of
contents to play the scene. The user can then click back to the table of contents by clicking
on a home link.
1. Let's get back to the plain white background that represents our table of contents.
Hide the Dog2 sprite. With the stage selected, click on the Backdrops tab. Select the
blank white backdrop.
2. Display the Dog TOC, Horse TOC, and Instrucons sprites by right-clicking on each
one from the sprites list and selecng show.
3. We're going to make the Dog TOC sprite clickable, so select the Dog TOC from the
sprites list.
4. From the Events palee, drag the when this sprite clicked block into the scripts
area. Add a broadcast () block to the script and create a new broadcast message,
hide toc, because clicking on the Dog TOC buon will cause the dog scene to load
and all visible sprites on the table of content page to hide.
5. Next, add a hide block to the script.
6. The script can be seen in the following screenshot:
7. In addion to hiding the clicked buon, we want to use the hide toc broadcast
message as a signal to hide all the visible sprites. Let's start with the Horse TOC
buon. Add the when I receive () block to the Horse TOC sprite's script area.
Select the hide toc message.
8. Add the hide block to the when I receive (hide toc) block. The following screenshot
shows the two block stack:
Chapter 4
[ 101 ]
9. Now we can copy the when I receive (hide toc) script to the Instrucons sprite.
What just happened?
Before we can play our scene, we need to clear the stage in preparaon for the dog scene.
We use the broadcast () and when I receive () blocks to coordinate what happens when we
click on the Dog TOC buon. Now when we click on the Dog buon, all the sprites should hide.
Let's reect on the sprite names in our project so far. There can ulmately be no wrong
answers when it comes to naming convenons and vernaculars, and I'm not intent on enforcing
any one on you. I think it's a good idea to choose names that provide meaning to you.
Let's break down our current Dog TOC example. We can tell by looking at the sprite that it's
a buon and the Dog label gives us a clue as to what scene will load. TOC represents the
table of contents, which is where the buon displays. When we click on the Dog TOC sprite,
we need to hide the table of contents, which we do with the hide toc broadcast. You might
noce that the name of our dog character is sll the Scratch default Dog2. This will drive
some of you nuts, but from a praccal standpoint, Dog2 already adequately describes the
sprite. Changing the name to Dog, for example, will not add clarity to anything, especially
because we're not adding more than one dog sprite to the project.
Time for action – displaying the dog scene
We connue to build around the broadcast message enter dog to display the sprites and
background of the dog chapter:
1. Now that we have cleared the table of contents, we need to load the dog scene.
We'll bring in the backdrop rst and the dog second. Select the Dog TOC sprite.
2. From the Looks palee, add the switch to backdrop to () block to the end of the
when this sprite clicked stack and choose bedroom1. The revised script can be
seen in the following screenshot:
Creang a Scratch Story Book
[ 102 ]
3. Now let's display the dog. Select the Dog2 sprite.
4. From the Events palee, add the when backdrop switches to () block to the
scripts area. Select the bedroom1 backdrop.
5. From the Looks palee, snap the show block to the script.
6. Now aach the when backdrop switches to (bedroom1) stack to the top of the
script that begins with the switch costume to (facing-right) stack that iniates the
dog's joke sequence.
7. Aer the scene changes, we want to delay the start of the acon for a few seconds
so our users have a chance to acclimaze to the switch. Add a wait () secs block in
place aer the set y to () block and change the value to 5. The revised script can be
seen in the following screenshot:
8. Click on the dog buon from the table of contents and watch the dog chapter
load and play.
What just happened?
With one mouse click, we loaded our wise-cracking dog and learned why dogs don't use
computers. Did you noce the sequence? First, we switched the backdrop. Then, we used
the backdrop as the cue to display the dog.
We needed to add some ming to control the scene by delaying the start of the joke by
ve seconds. Without the delay, everything happened at once: the background displayed,
the dog displayed, and the joke started. It would have been too abrupt.
Coordinating scenes by backdrop name
In our chapter exercises, we've seen two ways to coordinate the ow of our program.
The broadcast (play drums) and wait block iniates the drum eects, and the broadcast
(hide toc) block hides everything on the table of contents. But then we added a new wrinkle
by using the when backdrop switches to () block, which is a new Scratch 2.0 block.
Chapter 4
[ 103 ]
The Dog2 sprite is checking to see if the current backdrop is bedroom1, and if the backdrop
is bedroom1, then the dog's joke sequence plays out. Otherwise, the dog stays hidden and is
silent. The when backdrop switches to () block only checks stage backdrops as the name of
the block implies.
Time for action – navigating back to the table of contents
Aer a scene plays out, we need to give our users a way to play the next scene. We'll do that
by adding a home buon on the scene. We're going to return to the table of contents and
allow the user to select the next item. Let's add the controls:
1. The Scratch sprite library includes several buons we can use. For this exercise, I'm
going to import Buon3. You can use or create any buon you like. Just add a text
label that says Home via the paint editor and give the sprite a name, such as home
buon. Posion the Home buon on the top-le of the stage.
2. From the Events palee, drag the when this sprite clicked block into the scripts area.
3. Add a broadcast () block to the script and create a new message: Show TOC.
4. Add the hide block.
5. Aer we send the message to show the table of contents via the show TOC
broadcast and hide the Home buon, we need to switch the backdrop to the rst
stage backdrop. Add the switch backdrop to (backdrop1) block.
6. Now we need to create the script that shows the Home buon. Add the when
I receive (hide toc) block to the home sprite to take advantage of a broadcast
message we created earlier to hide the table of contents.
7. Add a show block. Our two scripts can be seen in the following screenshot:
Creang a Scratch Story Book
[ 104 ]
What just happened?
Now we have a way to navigate back to the table of contents for our joke book, and a key
part of that navigaon are the show TOC and hide toc broadcast messages. Our script
establishes the table of contents page as home; therefore, when we broadcast the show
TOC message, we're displaying the table of contents (or home). When the user is viewing
the home screen, the user doesn't need a way to navigate to home, so we hide the sprite.
Then, when we broadcast the hide toc message, it means we're loading a scene, and
therefore need to show the Home buon.
Whether we guide the user through the project or make it interacve, we need to think
about "what happens when". The answer to the "what happens when" queson becomes
the basis of how we move our users through the project.
Have a go hero – nishing the sequence and initializing the project
Right now, we're able to switch back and forth from the table of contents to the dog's scene.
Take a moment to make the horse scene load when you click on the Horse TOC buon.
Then, take the necessary steps to inialize the start of the project with the when ag clicked
block from the Events palee to ensure that the project always starts with the table of
contents showing.
Pop quiz – checking chapter concepts
Q1. Which of the following best describes the Backpack?
1. It stores revisions of your scripts that can be restored later.
2. It stores scripts and sprites that can be copied among projects.
3. It lists all your created Scratch projects.
4. It contains help les.
Q2. How can we use the when backdrop switches to () block?
1. As an event that runs the script if the selected backdrop displays.
2. To halt all running scripts.
3. To inialize the project's starng values.
4. To coordinate events via a broadcast message.
Chapter 4
[ 105 ]
Q3. If you want to posion a sprite in your script, how can you do that?
1. Measure the distance from the edge of the stage.
2. Drag the sprite around to the point on the stage where you want it.
3. Add the glide block to the script.
4. Determine the X and Y coordinates for use in moon blocks, such as the
glide () secs to x: () y: () block.
Q4. Which of the following best describes the play sound () unl done block?
1. The selected sound plays while the scripts connue to run.
2. The selected sound sends a broadcast message.
3. The selected sound plays, and the script does not run the next block in
the stack unl the sound nishes.
4. The block allows you to select from several drums.
Summary
Somemes, programming in Scratch can seem like the easy part of creang a project,
especially when we have to simultaneously create the storyline and coordinate all the
elements to make the story unfold. Fortunately for us, everything gets easier with pracce.
We started our work at the beginning of the chapter with the idea to create a book of
jokes—and I'll forgive you if you think my jokes are bad—and by the me we nished our
exercises, we had a project that could seamlessly navigate through the stories based on the
users' selected path. In the process of telling a story via our Scratch book, we got our rst
good look at using coordinates to precisely locate sprites, explored sound, and coordinated
acon based on a background.
In the next chapter, we're going to connue our work with backgrounds by creang a
slideshow from some of our personal images. We'll explore some of the advanced features
of some of the concepts we introduced in this chapter, including hiding the slideshow
navigaon based on the mouse locaon and playing back our recorded slide navigaon.
5
Creating a Multimedia Slideshow
If you're like me, you have thousands of photos on your computer hard drive.
It's time to dust off a few of these photos for our next project as we will be
creating a slideshow with images we import from our computers. To help
us personalize our slideshow, we'll incorporate generic sounds and custom
recordings into our project.
In this chapter, we will do the following:
Import personal photos as backdrops
Work with and resize images for use in our projects
Add slideshow controls to display images
Play and record sounds
Locate the x and y coordinates to locate the mouse and hide the navigaon controls
Display a project in presentaon mode
We will start simple with this project and add advanced features as we near the end
of the chapter, but the basic slideshow framework should be well within reach of the
youngest Scratchers.
Importing photos as backdrops
Before we begin, you might want to look through your photo library. As a backyard
beekeeper, I'll be using some of my bee photos. As you look for your own photos, you might
want to consider selecng a group of images from a party, a trip, or some other event to help
create a theme for the slideshow. A minimum of three photos would be a good place to start
as we work through the chapter.
Creang a Mulmedia Slideshow
[ 108 ]
Time for action – importing photos from les
Let's import a batch of photos from our computers so that the slideshow has something
to display:
1. From the Sprites pane, select the stage thumbnail and then click on the Backdrops
tab to show the current white project backdrop. Click on the upload backdrop from
le icon. The following screenshot shows the available New backdrop opons.
The opon upload backdrop from le is the third icon from the le and looks like
a folder with an arrow. You'll also noce these same New backdrop opons under
the stage thumbnail in the Sprites pane.
2. Browse your computer's folders unl you nd your photos and add them to
the project. To select mulple les, hold down the Shi key while selecng your
image les.
Scratch will autosize the images to fit the stage size of 480 x 360 pixels. If you
want to make sure that your image will fit the Scratch stage perfectly, you
can use an external graphics editing tool (GIMP, PhotoShop, and others) to
crop the image to 480 x 360 pixels prior to importing the image in Scratch.
3. Aer all the images are imported into Scratch from your computer, you will see a
list of backdrop thumbnails in the Backdrops pane. To preview each imported image
on the stage, click on the thumbnail. This step will conrm that all the images were
imported and will be displayed properly.
4. Now, let's work with the names of our images. We're going to display the name
of the photo on the stage. On the Looks palee, nd the backdrop name block
and click on it to make the name of the image appear on the stage. The following
screenshot shows the Looks palee and a check mark next to the backdrop name
block. In my example, this adds the words bee hive to the stage.
Chapter 5
[ 109 ]
5. When Scratch imports an image, the backdrop name is derived from the le name of
the photo on your computer. In many cases, those le names will be combinaons
of numbers and dates because that's how your digital camera or phone names
them. Fortunately, we can rename the backdrops in Scratch to be something
meaningful. As you click on the backdrop thumbnail on the Backdrops pane, you will
see that the text area in the top-right corner of the image editor contains a name.
The following screenshot shows an example of an imported image. Note that the
name of the backdrop is 2013-07-08 09.30.3.
6. Go through your list of imported backdrops and give them meaningful, human-
friendly names.
Creang a Mulmedia Slideshow
[ 110 ]
As the following screenshot shows, my project has several photos added, and the default
white stage remains as the rst backdrop. Like a sprite and its costumes, the stage's
backdrops can be edited via the built-in paint editor. The following screenshots show a
backdrop on the stage and in the image editor. Should you choose to, you could use one
of the image eding tools to manipulate the image in some way. We're not going to modify
our imported images, but the opon is there should you need to use it.
The list of backdrops is arranged in the order in which they were added, but backdrops can
be sorted by dragging and dropping the thumbnail around the Backdrops tab. You may want
to manually sort your photos because our slideshow will sequenally move through the
backdrops and the order in which you display them could become part of the story you tell
with your photos.
What just happened?
By imporng photos from our individual computers, we create an extremely personal and
unique project. Scratch also provides a list of backdrops via the Choose backdrop from
library icon, which is the rst icon under the New Backdrop heading.
The backdrop name block is a reporter block in Scratch and is designed to be used as the
value for other blocks. We'll use the backdrop name block in a script later in this chapter.
The previous exercise gives us a quick and easy capon on the stage as long as we give
our backdrops meaningful names. The reporter block can be reposioned on the stage
by dragging it around.
Chapter 5
[ 111 ]
An alternave way to accomplish capons and tles is to edit each backdrop to create the
capons with the text tool. We've chosen the easier route in our project because we're going
to use sound to provide a more detailed explanaon of the images, so a descripon of a
word or two will be sucient.
Adding text directly to the image may appear more polished, but it can be more dicult to
maintain. The changing color of the images, for example, may mean you need to reposion
the text dierently per image or choose a dierent color for the text. And as we've seen in
Chapter 3, Creang an Animated Birthday Card, working with the text tool in our images may
pose problems to actually changing the text aer you save your text.
On the surface, these are not large obstacles and can be overcome. Working in vector mode,
for example, will let us edit the text at any me. Therefore, even though we're relying on the
backdrop's name and the backdrop name block to create a simple capon, it doesn't prevent
you from doing something more elaborate.
Let's briey talk about working with images in Scratch.
Working with images
Working with digital images is a topic worthy of its own book, but Scratch has some built-in
image eding capabilies that we can use, and we've seen some of those limited capabilies
as we created sprites throughout Chapter 3, Creang an Animated Birthday Card. Basically,
we can change colors, draw rectangles and circles, insert lines, type text, duplicate areas, and
resize, reshape, rotate, and ip images. I'll editorialize for a moment and just say that I think
that's an awesome feature set for Scratch to include by default. However, if we want more
advanced eding capabilies, we need a more advanced editor. Examples of third-party
graphics editors include the following:
GIMP: This is an open source, cross-plaorm editor available at
http://www.gimp.org
Adobe Photoshop: This is a sophiscated editor oered by Adobe at
http://www.adobe.com/products/photoshop.html
MS Paint: This comes installed with Microso Windows
Pixelmator: This is a full-featured app for Macs available at
http://www.pixelmator.com
Scratch imports the popular image formats: PNG, BMP, JPG, GIF, and SVG. If you import
an animated GIF, Scratch will import each frame as a backdrop or as a costume if you're
imporng the animaon as a sprite. Animated GIF creates animaons by combining and
cycling through many individual images.
Creang a Mulmedia Slideshow
[ 112 ]
When imporng an SVG (vector) graphic, Scratch imports the le as a vector graphic,
which means its resoluon can be maintained. We introduced vector graphics in
Chapter 3, Creang an Animated Birthday Card.
Resizing images
The stage in Scratch measures 480 pixels wide by 360 pixels high. In graphic design, we list
width rst, so an 800 x 600 image is 800 pixels wide. As we learned in Chapter 3, Creang
an Animated Birthday Card, if we were to look at an image under extreme magnicaon,
we would eventually see individual dots. These dots are pixels and contain all the
informaon the computer needs to display the image on the screen.
Counng pixels becomes important so we can select images that will meet our needs.
If we want an image to take up the enre backdrop, we need an image that is at least
480 x 360 pixels to ensure we have an image of acceptable quality.
The problem with using an image that is less than 480 x 360 pixels is that we need to stretch
or upsize the image in order for it to ll the screen. As we resize an image to a larger size, the
pixels are made bigger, and we will begin to see the individual pixels. This eect creates a
grainy and unclear image, which is oen referred to as a pixelated image.
We don't have to worry about image pixelaon when we resize the image to a smaller size
from a larger size. Whenever possible, start with a larger image and downsize if needed.
I'll state the excepon even at the expense of being obvious. We're working with backdrops
in this case, but we can import images as sprites, too. In either case, we may want the
imported le to be smaller than the stage, and in those cases, you wouldn't necessarily
want to start with a large image.
Using caution while resizing images
The good news is that if we start with an image that is larger than 480 x 360, then we
don't need to resize the image at all. Scratch will resize the image to t within the correct
dimensions automacally. Be aware that anyme you allow a computer program such as
Scratch to resize your images, you run a great risk of being dissased with the results.
Here's an example. One of the backdrops I started with in the previous exercise was 3504
x 2336 pixels. When I inially uploaded the image via Scratch's paint editor, the imported
image was not tall enough, as seen in the following screenshot:
Chapter 5
[ 113 ]
Noce the white space below the image? If you look at the backdrop's thumbnail
(highlighted in the screenshot), you will see that the image dimensions are the
expected 480 x 360. However, my inial image did not have white space at the boom.
Here's what's happening. When Scratch receives a big image, it resizes the width to 480
pixels and scales the height appropriately. If the resized height is less than or equal to 360
pixels, no further processing happens; however, the image editor will create an image that is
360 pixels high by lling in the dierence with white space. If the resized height is too much,
Scratch will crop the boom of the image to make it t.
The technical concept at play here is called aspect rao. We'll cite Wikipedia's denion of
aspect rao as "the proporonal relaonship between its width and its height." The 480 x 360
stage size has a 4:3 aspect rao. We won't go too far down the aspect rao path, but if you
were to scale an image that is 480 x 360 pixels by seng the width to 4 pixels, the height would
proporonally scale to 3. Other common aspect raos are 3:2 and 16:9, but when Scratch
doesn't scale your images as you'd like, the aspect rao of the image may be the reason.
The boom line is that if you want to have absolute control over what your image looks like
when you import it into Scratch, then use a full-featured image eding soware package to
crop the image to the correct size before you import it into Scratch.
Creang a Mulmedia Slideshow
[ 114 ]
Have a go hero – importing an animated GIF or vector graphic
In the Working with images secon of this chapter, I have menoned that animated GIF
and SVG les can be imported into Scratch. These le formats have interesng properes,
as we've discussed. Now it's me to see these properes yourself.
The code les in this book include two publically available images that you can use for this
exercise. One is animated gif example.gif and the other is yellow bird.svg.
Import each of these les as both a backdrop and a costume. I recommend that you open
a new project as this exercise is a bit tangenal to our slideshow project but will prove
informave. Make some observaons about how Scratch is resizing this image based on how
you're trying to use the image in Scratch. The original le size of both sample images is much
smaller than the Scratch stage.
The example animaon in the book is courtesy of the Animated Gifs: Fleischer's Bubbles
(1922) series by The Public Domain Review website at http://publicdomainreview.
org/2013/09/24/animated-gifs-fleischers-bubbles-1922.
The example yellow bird.svg le was obtained courtesy of the openclipart website at
http://www.openclipart.org/detail/190937/yellow-googley-eye-bird-by-
ruthirsty-190937.
Adding slideshow controls to display images
Let's get back to our slideshow. Now that we have our photos imported into Scratch,
we need to add a way to click forward and backward through the photos. We'll accomplish
this by using one of the arrow sprites included in Scratch's sprite library.
Time for action – ipping through the photos
The Scratch sprite library contains a couple of sample arrows that we can use. However, you
may decide to paint your own arrows or import other images. Just keep in mind that we
need a le and right arrow.
1. Let's add the arrow2 sprite from the Things folder in Scratch's sprite library. You can
nd the sprite by clicking on the Choose sprite from library in the Sprites pane. This
sprite points to the right by default, but there's a costume that points to the le,
which we'll use in the next step.
2. Let's get an arrow that points to the le into the project. Repeat step 1 and add
a second copy of arrow2. Click on the Costumes tab and select the costume that
points to the le. This will give us le and right arrows on the Scratch stage.
Chapter 5
[ 115 ]
If the default color of the arrows blends in with your images, you may
want to use the image editor and use the color a shape tool to change
the color of the arrow.
3. Posion the arrows in the boom-right corner of the screen.
4. To help keep the arrows straight, rename the le-facing arrow to Back and the
right-facing arrow to Next. Rename the sprite by clicking on the i icon on the
sprite to display the sprite info pane, as seen in the following screenshot:
5. Let's build the script for the Next arrow rst. From the Events palee, add the
when this sprite clicked block.
6. From the Looks palee, add the switch backdrop to () block and select next
backdrop from the drop-down list of values.
Creang a Mulmedia Slideshow
[ 116 ]
7. Now, create the same script for the Back arrow, but select previous backdrop for
the value of the switch backdrop to () block.
What just happened?
The scripts we just created for the arrows use the switch backdrop to () block, which is a new
Scratch 2.0 block. This simple block has some big ramicaons for working with backdrops.
In our script, we used the next backdrop and previous backdrop values to sequenally move
through the backdrops. All backdrops have a number, so if we're currently viewing backdrop
number 3, then clicking on the Next arrow will display backdrop number 4. And if we're
viewing number 4, clicking back will display backdrop number 3.
The switch backdrop to () block also contains a list of all the backdrops in the project,
allowing us to select a specic backdrop.
Related backdrop blocks
We've used a couple of the backdrop blocks in our script so far. However, there are several
backdrop blocks available to us, as listed in the following table. Some backdrop blocks are
only available to the stage.
Block name Location palette Description Example uses
switch backdrop
to ()
Looks This changes the
backdrop on the stage
to the one specified.
Available attributes are
the next background, the
previous backdrop, and
the name of each stage
backdrop.
Can be used to switch
the backdrop in a variety
of contexts, including
creating levels in a game
or setting a starting
screen.
switch backdrop
to () and wait
Looks (stage only) Selects the specified
backdrop. This block
works in conjunction
with the when backdrop
switches to () block by
waiting for any scripts
that start with the when
backdrop switches to
() block to finish before
continuing. Only available
to the stage.
Can be used in the same
situations as the switch
backdrop to () block.
Chapter 5
[ 117 ]
Block name Location palette Description Example uses
backdrop name Looks Each backdrop has a
name. This block allows
you to use the name as
a value for other blocks
and passes the current
backdrop's name into the
blocks. It's also a reporter
block, which means you
can show the current
backdrop name on the
stage by clicking on the
checkbox next to the
block.
Used when you need
to create a script based
on a specific backdrop,
such as playing a sound
or checking for a game
level.
backdrop
number
Looks A backdrop also has a
number to indicate its
relative position within
the list of backdrops for
the stage. The backdrop
number block can be
used to display the
number of the current
background on the stage
or as the value for other
blocks. It is only available
to the stage.
Similar to the backdrop
name block.
next backdrop Looks Go to the next backdrop
in the list.
Can be used to create
photo slideshows or
animations including
stop animations.
when backdrop
switches to ()
Events Runs the script when
the specified backdrop is
displayed. The attributes
are a list of all backdrops.
Allows a sprite to
run a script based on
switching to the specified
backdrop.
Plays a sound based
on the backdrop. Runs
a script based on a
backdrop.
Creang a Mulmedia Slideshow
[ 118 ]
Playing and recording sounds
Scratch provides both a library of sounds that we can incorporate into our project and
a way to record our own sounds. We'll start o with a quick exercise to play a sound
when we click on the Next arrow. Then, we'll explore Scratch's built-in sound recorder
to narrate our images.
Time for action – adding a sound from Scratch's library
At the moment, we have a script that shows the next background when the user clicks on
the Next arrow. Let's create a sound eect to signal the next slide:
1. Select the Next sprite and add a play sound () block from the Sound palee to the
script that starts with when this sprite clicked.
2. You'll noce that the play sound () block uses a default pop sound. If you click on the
Next arrow, you'll hear the sound play as the next image loads.
3. Let's choose a new sound from Scratch's library. Click on the Sounds tab in the
project editor to display a list of sounds associated with the sprite. Then, click on
the Choose sound from library icon. Look at the following screenshot for reference:
4. The Sound Library window will open and display a list of sound categories on the
le-hand side. Select Eects and then select the ripples sound. Click on OK to add it
to the Sounds tab.
Chapter 5
[ 119 ]
5. Click on the Scripts tab.
6. Select ripples from the play sound (pop) block.
7. Test the script by clicking on the Next arrow. Your revised script should look as
shown in the following script screenshot:
What just happened?
When our user clicks on the Next arrow to change the image, the ripples will signal the
image change. Note that when you click on the Back arrow, there is no sound. Of course,
we can add other sounds to the script, but the crical step is to add them to the sound tab
rst. Just as sprites and backgrounds, Scratch includes a library of sounds that are freely
available for use in our projects.
The sounds are assigned to the sprites. So, if you look under the play sound () block for the
Back arrow, for example, you'll noce the ripples sound is not available.
Next, we'll use the more advanced sound features in Scratch and record our own sound for
use in the project.
Time for action – recording sounds in the sound editor
We're going to complete our slideshow by recording some audio to describe each backdrop.
This gives our users a richer experience and might be comparable to what you'd experience
if you were ever to take a self-guided walking tour.
For the purposes of this exercise, think about a two- or three-sentence descripon for one of
your images. Our basic task will be to add a sprite that will play the correct audio when we
click on it. Let's walk through the steps:
1. Sounds are associated with a sprite or the stage, so let's add a sprite that can be
used to play the audio we will record. Import Microphone from the Things category
in the Sprite Library.
2. Now select the microphone sprite so that we can record our audio. To record
new audio, click on the microphone icon in the Sounds tab. A new sound called
recording1 is added and selected.
Creang a Mulmedia Slideshow
[ 120 ]
3. Click on the circle icon in the sound recorder to start recording. It is the icon to the
le of the Edit menu and is shown in the following screenshot:
4. When you are nished, click on the square buon to stop recording. In the previous
screenshot, that's the icon to the le of the record (circle) buon.
5. To hear the sound, click on the play buon.
6. In order to make our scripng easier and relevant to this project, rename recording1
to be the name of the image. For example, I made a recording for an image named
Inside bee tree, so that will be the name for my recording.
7. Now let's write a script that plays our recording when the microphone is clicked.
With the microphone sprite selected, click on the Scripts tab.
8. From the Events palee, add a when this sprite clicked block. Then, aach a
broadcast block.
9. From the Looks palee, drag the backdrop name reporter block into the value of
the broadcast block.
10. Now we need to act on the broadcast. Sll working with the microphone sprite,
add the when I receive block to the Scripts area. Create a new message that
corresponds to the name of the backdrop name. In my example, that name is Inside
bee tree. Your names will likely be dierent, but recognize the relaonship we're
creang here. The name of the backdrop matches the name of the recording.
Chapter 5
[ 121 ]
11. Finish the script by adding the play sound block from the Sounds palee. Select the
recording you just made from the drop-down list of values.
Give it a try. Click through each image in the slideshow and try clicking on the microphone.
If you've succeeded, the recording should only play for one image because that's all we've
programmed so far.
If you're encountering problems, double check the spelling of the image name, recording
name, and broadcast name. Typos will cause this script to fail.
Want to add a second recording? All you need to is to make a new recording, duplicate the
when I receive script block, and then change the broadcast and sound values accordingly.
What just happened?
We have a lot to cover here, but let's start with the basics. By using Scratch's built-in sound
recorder, we were able to narrate an image name. The key to this script is the use of the
backdrop name reporter block as a value in the broadcast block.
Earlier in the chapter, we introduced the backdrop name block as a reporter block that
always knew the name of the current backdrop. By adding the backdrop name reporter
block as the value of the broadcast () block, we have created an easier way to broadcast
Inside bee tree based on my example in the exercise. This two-block script will work
regardless of the backdrop that is currently displayed.
We do have to create a separate when I receive () script for each backdrop we want to narrate.
The new broadcast message should match the name of the backdrop you want to play a sound
for. Of course, you'll need to record the addional recordings for use in the script.
Creang a Mulmedia Slideshow
[ 122 ]
By using thoughul naming convenons instead of computer generated defaults, we have
a way to keep the backdrop name, recording name, and broadcast name in sync. This will
reduce confusion when it's me to manage and troubleshoot our scripts.
Let's take a moment to reect on a possible variaon. Consider the scripts shown in the
following screenshot:
The two stacks of blocks on the le are the scripts we built in the previous exercise.
The two block script on the right also plays a sound based on the backdrop. We didn't
build that one, but it's listed here for discussion purposes.
The crical dierence in the scripts shown in the screenshot is when the sound plays.
Our script enables the user to play the sound on demand. The simpler script will play
automacally when the backdrop loads. The user has no say in the decision. However,
the script on the right can be used to play an introductory sound when the backdrop loads.
We chose to play a generic sound to transion the image, but this discussion introduces an
alternave approach.
Understanding sound related blocks
Scratch provides the following blocks for playing sounds:
Block Palette location Description Uses
play sound Sounds Plays the specified sound. The
available attributes are the
sounds associated with the sprite
or background.
Sound is a generic
term that may mean
a sound effect, a
recording sound, or an
imported music file.
play sound
until done
Sounds Similar to the play sound
block, except the script doesn't
continue until the sound is
finished.
Similar to the play
sound block.
stop all
sounds
Sounds Stops any sound that is currently
playing.
Stops playing sound
when a level or
background changes.
Chapter 5
[ 123 ]
Editing sounds
The sound editor includes several advanced but easy-to-use opons for working with sounds,
including copy, paste, and delete.
Time for action – editing a recorded sound
We're going to delete a secon of the sound we recorded in the previous exercise. For
example, if you recorded a bunch of dead air at the beginning or end, you can use the
following exercise to delete it:
1. In the Sounds tab, click on your recorded sound to open the sound in the editor.
2. In the sound editor, highlight the area in the sound recorder that you want to delete
by clicking and holding the mouse and then dragging the mouse to select the sound
you want to remove.
3. Before you delete the selecon you can listen to it by clicking on the play buon in
the editor.
4. From the Edit menu, select Delete. The following screenshot illustrates the process
of deleng a secon of a sound:
Creang a Mulmedia Slideshow
[ 124 ]
What just happened?
Deleng a secon of your recording may be useful, say to trim dead space at the beginning
or end of a recording. You can also delete those pesky ums and uhs.
As you can see in the Edit menu, there are several other basic eding opons available to us:
cut, copy, paste, delete, and select all.
Time for action – appending a sound
Aer you listen to a recording, you may realize that you have more to say about it. Let's
connue working with our recorded sound:
1. Click on the recording at the point where you want to insert a new sound.
The vercal line in the following screenshot shows where the new sound will
be added. Note that the screenshot shows that it's possible to add a new
recording in the middle of an exisng sound.
2. Then, click on the record buon and speak.
3. When you're nished, click on the stop buon. The newly recorded secon will be
highlighted when you click on the stop buon, as seen in the following screenshot:
4. To preview the new recording, click on the play buon. You can keep deleng and
recording unl you're sased with the results.
Chapter 5
[ 125 ]
What just happened?
I nd that the hardest thing about recording is actually geng all the words out in a way that
makes sense. We've seen how easy it is to record, delete, and edit a sound. As the examples
demonstrate, we can edit at the beginning or end or at any point in between.
In our slideshow project, we've been narrang a descripon of each slide, but we could just
as easily record our own sound eects or music.
Time for action – adding sound effects to recordings
Aer we record our sound, and it's just the way we want it, we can use the sound editor to
add eects.
1. Highlight the secon of the recording to which you want to apply an eect.
2. Then select an eect from the Eects menu to apply it. For example, we could select
the fade in eect to make the sound start out quietly and gradually get louder.
3. You can expand or reduce the selecon by clicking and dragging the edge of the
selected sound.
The following screenshot shows the list of eects:
Creang a Mulmedia Slideshow
[ 126 ]
What just happened?
The sound editor includes a list of eects that can be applied to any sound, such as fade in,
fade out, louder, soer, silence, and reverse.
Reviewing available sound effects
The following table provides an example usage for each eect:
Effect Use
fade in This effect starts the audio quietly and gradually
increases the volume.
fade out This effect starts the audio at a normal volume
and gradually decreases the volume until it's
quiet.
louder This effect increases the volume.
softer This effect decreases the volume of the selection.
silence This effect silences the audio selection.
reverse This effect takes the selection and reverses the
order with which it is played, which is a good way
to create gibberish.
Have a go hero – narrating additional images
Take a moment to record a narraon for at least one of the other images in your slideshow
and update your scripts to play the narraon at the appropriate me. You can also
experiment by adding addional sounds based on the backdrop.
Using x and y coordinates to nd the position of the
mouse's pointer
At this point, our slideshow is full of engaging images and has a rich user experience.
We could stop here, but we're going to add one more wrinkle to our show by making the
arrows hide and show based on the posion of the mouse cursor. We'll build these scripts
block by block, so even if the x and y coordinate system is a new concept for you, you'll sll
have a ready-made example to explore the concept some more.
Chapter 5
[ 127 ]
Time for action – using mouse location to hide arrows
This exercise will add a lile bit of glitz to our project, but there's also a funconal reason
behind our wanng to build this interface. The arrows obstruct a part of our backdrop.
Hiding the arrows shows more of the backdrop.
1. To determine when we show or hide the arrows, we need to connually check the
posion of the mouse. Let's start building the script to do this on the Next arrow
sprite. Start the script with the when ag clicked block. Aach a forever block.
2. Inside the forever block, add the if () then, else block from the Control palee.
3. The if () then, else block checks to see if a condion is true. To determine when to
show the arrows, we're going to check the x and y posion of the mouse. We'll start
by adding the () and () block from the Operators palee to the value of if () then,
else to accommodate a check for both x and y posions.
4. In the le value of the () and () block, add the is greater than (>) block, and then add
the is less than (<) block to the value on the right hand side of the () and () block.
5. From the Sensing palee, drag the mouse x block to the is greater than (>) block
and the mouse y block the is less than (<) block. The following screenshot shows
our script so far:
6. Next, we need to replace the empty values of the is greater than (>) and is less
than (<) blocks. To do that, we need to determine the x and y coordinates that will
appropriately show the sprites. Consider the following screenshot that shows my
Next and Back arrows with a rectangle around them. If the mouse moves into the
rectangle area (the hot zone), as shown in the following screenshot, we will want
to display the arrows:
Creang a Mulmedia Slideshow
[ 128 ]
7. As you move your mouse cursor to the right, the x value gets bigger. As you move
the mouse towards the boom of the stage, the y value gets smaller. The x and y
coordinates of the mouse can be seen in the following screenshot. These values
represent the mouse locaon, which is approximately where the x and y annotaon
occurs in the previous screenshot. I'm going to round my values o a bit, and enter
70 in the mouse x > () block script and -105 in the mouse y < () block script. The
following screenshot shows the evaluaon:
8. Let's nish our script by adding the show block to the if part of our block and the
hide block to the else part. Our enre script is shown in the following screenshot:
9. Give the script a try by clicking on the green ag and moving your mouse cursor
around the screen. If the script behaves as you expect, you can duplicate it and
move it to the Back arrow sprite.
What just happened?
We created a script to show the Next and Back arrows depending on the mouse locaon.
We oen see this eect on the web, such as while playing or pausing YouTube videos where
the video controls are hidden unl you mouse over the boom of the video. The controls are
visible when you posion your mouse cursor along the boom of the video. You may wonder
how other users will know they need to move their mouse into the corner to display the
arrow. We'll address that problem in our next exercise. By using the () and () block, our script
was able to check both the x and y posions of the mouse cursor. Only when both condions
were true did we show the arrows. While we purposely chose to use the coordinates, our
values were somewhat subjecve in that we can make a larger or smaller hot zone on the
stage by altering the coordinates.
Chapter 5
[ 129 ]
If x and y coordinates are a new math concept for you, you just need to know that each
locaon on the Scratch stage is represented by two numbers. The x coordinate idenes
the horizontal (le/right) posion on the stage while the y coordinate idenes the vercal
(up/down) posion on the stage.
If you're following my example closely, you'll realize that if you move your mouse below and
to the right of the stage, the arrows are sll visible. That's because the script we created only
dened the top and le edges of the hot zone, leaving it an open-ended hot zone.
The stage, however, does have denite boundaries and coordinates. If you move the
mouse cursor beyond the boundary of the stage to the boom-right corner of the project
editor, the reported values never show higher than 240 (value of x) and -180 (value of y).
When a user views the project page, this might happen if the user lets the mouse wander
below the stage.
Have a go hero – redening the hot zone
As we've discussed, if the user moves the mouse outside our hot zone, the arrows hide as
long as the mouse cursor stays above and to the le of the Next and Back arrows. If the user
moves the mouse below the arrows or to the right of the arrows and outside the stage, then
the arrows will sll be displayed.
Can you constrain the arrows' hot zone to ensure the arrows are only displayed if the mouse
is within the boundary of the stage? You can, and to do this, you'll need to update the arrow
scripts to evaluate a second set of x and y values by modifying this block: if ((mouse x) > (70)
and (mouse y) < (-105)).
Hints
Add more () and () blocks to the value in the if () then else block to
check whether the mouse is within the stage boundary. The following
expressions check whether the mouse is within the stage boundary:
mouse x posion < 240
mouse y posion is > -180
The project les included with the book include a working example of this soluon for the
Next sprite.
Creang a Mulmedia Slideshow
[ 130 ]
Time for action – providing user instructions
Based on our current scripts, it's possible for our slideshow to start with no Back or Next
arrows on the screen because their display is determined by the locaon of the mouse
cursor. That could be confusing to a user. Let's revise our script to provide some user
instrucon at the start of the project. Select one of the arrows and add a show block
to the when ag clicked block.
1. From the Looks palee, add a say for () secs block aer the show block.
2. For the text value of the say block, type an instrucon to the user
(for example, To advance the slideshow hover over this area.).
3. Increase the me value in the say for (2) secs to 5.
4. Now select the other arrow sprite and add a show block aer the when ag
clicked block.
5. This me, add a wait (2) secs block aer the show block. Change the value to 5.
6. Give the script a go by clicking on the green ag.
The following screenshots shows our revised arrow script:
What just happened?
We updated the script for each arrow so that the next and back controls are always visible
for at least ve seconds when a user starts the project. Both the arrow sprites used the show
block to always display the arrows. Then we created some user instrucons using the say ()
for () secs block.
Chapter 5
[ 131 ]
Aer the say () for () secs block, we go straight to the part of the script that shows/hides
the arrows based on where the mouse cursor is posioned. We want the instrucon to be
displayed for a reasonable amount of me so that our user can read it. The say () for () secs
block gave us a way to control the ming of our script. Because the block has a seconds
value, the message will stay on the screen for the specied me. No other blocks in the
script will run as long as the message is displayed on the screen. We solved two problems
with one block—user instrucon and ming.
When we updated the other arrow sprite, we used the wait () secs block in place of the
say () for () secs block. That's because we don't need both arrows to give instrucons,
but we do want both arrows to stay on the screen for ve seconds.
Displaying a project in presentation mode
Up to this point, we've been viewing our projects in the project editor with the block palee
and script areas visible. When our users view the slideshow, they sll have a small viewing
area, as seen in the following screenshot:
However, Scratch has a way for us to view projects in fullscreen mode.
Creang a Mulmedia Slideshow
[ 132 ]
Time for action – presenting a fullscreen slideshow
Let's check out Scratch's fullscreen presentaon mode:
1. The buon to enter presentaon mode is located in the top-le corner of the
project editor. It's the blue square to the le of the project name and below the
menus and is shown in the following screenshot:
2. Check out your slideshow by clicking on the blue square.
3. When you've nished viewing the project in fullscreen mode, press the Esc
key on your keyboard to return to the Scratch interface. You can also click on
the blue square to exit fullscreen mode.
What just happened?
Presentaon mode allows us to run our projects using a larger viewing area with less screen
cluer. And some projects, such as the slideshow we're creang, would look really good
displayed in fullscreen mode on our television or large monitor.
Have a go hero – personalizing the slideshow with graphic effects
Right now, we have a funconing slideshow complete with narraon. Before you set the
family down for a private screening, consider enhancing the transions between slides with
some graphical eects. We covered graphical eects in Chapter 3, Creang an Animated
Birthday Card.
Chapter 5
[ 133 ]
Pop quiz – reviewing the chapter's concepts
Q1. How big is Scratch's stage?
1. 360 x 480.
2. 480 x 360.
3. 420 x 320.
Q2. Aer a sound is added to the project, it is available to all sprites via blocks,
such as play sound ().
1. True.
2. False.
Q3. What block gives us the name of the current backdrop?
1. next backdrop.
2. backdrop name.
3. previous backdrop.
4. backdrop #.
Q4. How would you know where the mouse is located on the screen?
1. The mouse has an x coordinate accessible via the mouse y block.
2. The mouse has an y coordinate accessible via the mouse x block.
3. The mouse has x and y coordinates accessible via the mouse x and mouse y blocks.
4. You can see the mouse pointer on the screen.
Q5. Which of the following image formats does Scratch support?
1. PNG.
2. GIF.
3. JPG.
4. All of the above.
Creang a Mulmedia Slideshow
[ 134 ]
Summary
How great is Scratch! Not only does it give us an engaging programming environment, it also
gives us a whole suite of tools to personalize our projects. In this chapter, the slideshow we
created used our personal images. With the click of a buon, we brought the images to life
with our own recorded voices and with sounds from Scratch's included sound library. And
with a lile creave programming using the broadcast block, we were able to synchronize
the backdrops with a specic sound. We ended the chapter with the slightly more advanced
concept of using the x and y coordinate system to locate the mouse and used this as a way to
show or hide navigaon controls.
Our project used personal photos. However, what we really created was a project that can be
remixed into a presentaon on any topic: science, favorite Scratch authors, birds found in the
backyard, and the list goes on.
In the next chapter, we're going to remix the classic Pong game with the game of Breakout
so we can smash some bricks. We'll introduce variables, condional statements, and cloning.
Cloning is a new Scratch 2.0 feature that allows us to duplicate a sprite and all its associated
scripts, costumes, and properes.
6
Making an Arcade Game – Breakout
(Part I)
If you spend any time with Scratch, you will encounter a Pong project. In
this chapter, we're going to remix that classic arcade game to create our
own version of the game Breakout. In Breakout, the player breaks through
multiple layers of bricks by hitting a bouncing ball. In this chapter, we'll lay the
foundation of the game while in the next chapter we'll make the game more
challenging.
In this chapter, we will:
Upload a Pong starter project that we will customize
Use cloning to create exact duplicates of the sprites that can be individually
controlled
Find and calculate the sprite direcon to program the ball's direcon
Create and use custom variables to keep score
To help you understand the idea of the game, let's get a brief introducon to Breakout.
Learning about the Breakout game
Breakout is a 1976 Atari game that expanded the arcade game Pong. In the gameplay, the
player hits a ball with a paddle in order to break the rows of bricks. There are eight layers of
bricks; every two rows use a dierent color. From top to boom, the colors are red, orange,
green, and yellow. The player bounces the ball o the paddle or the wall to break the bricks
and score points.
Making an Arcade Game – Breakout (Part I)
[ 136 ]
Breaking bricks earns points, and the player will have three chances to break all the bricks.
The ball speed will increase at dened intervals.
You can read about the history of Breakout on its Wikipedia page. We'll mimic the evoluon
of Pong into our own variaon of a Breakout-style game. By the me we nish this chapter
and the next one, we'll have a clear understanding of just how powerful remixing can be.
Let's get started so that we can create our own version of this game.
Discovering Pong
The 1.4 Version of Scratch included a Pong starter project. Now that Scratch 2.0 has moved
online, nding those starter projects is more challenging. Therefore, I've included the
game in the code bundle of the book. If you haven't already done so, download the book's
accompanying code.
Time for action – importing and playing the Pong starter project
Any me we open another person's Scratch project with the intenon of remixing it, we
need to spend some me understanding the project. This exercise will walk us through the
process of uploading a legacy game from our computer and help us discover some of the
details. Our rst step will be to import, play, and learn about how the exisng Pong game
works. Let's follow these steps to import and play the game:
1. The starter project has the le name Pong.sb. To import it into Scratch, create a
new project from the Scratch project editor. Then click on the File menu and select
upload from your computer. Browse and select the Pong.sb starter project to
create a new project using the uploaded project.
2. Play the game by clicking on the green ag. Move the mouse le or right to control
the paddle and hit the ball. Move the mouse up and down the stage, and note that
the paddle doesn't move.
3. When you've had enough, stop the game.
4. Let's get some more informaon about what the ball is doing. With the ball sprite
selected, enable the direcon reporter block by clicking on the checkbox next to
the block's name in the Moon palee. The value of the direcon variable displays
on the stage.
5. Play the game again, and note how the value of the ball's direcon changes as the
ball travels across the stage. When you're done, let the ball hit the red stripe to end
the game.
6. Next, we'll examine the paddle's script by clicking on the paddle sprite.
Chapter 6
[ 137 ]
7. Enable the x posion block from the Sensing palee by clicking on the checkbox
next to the block's name. The x posion block is also a block and you should now
have two stage monitors displayed (one for the ball's direcon and one for the
paddle's x posion).
8. Play another game. Watch as the monitor blocks report the direcon of the ball and
the locaon of the paddle in real me.
What just happened?
The mission is simple—keep the ball from landing on the red stripe to keep the game alive.
The paddle moves based on the movement of the mouse. When you hit the ball, it ricochets
o the top and sides of the stage. As we move the mouse to the le, so does the paddle;
however, the paddle doesn't respond to up and down mouse movements because the
scripts in the game do not specify any acon based on the vercal posion of the mouse.
We tracked the ball's direcon and the paddle's x coordinate by enabling the direcon and
x posion reporter blocks, respecvely. These two values highlight the primary variables in
Pong. These blocks represent the built-in variables (reporter blocks) in Scratch.
The direcon change of the ball is accomplished with the point in direcon block that
executed when the ball touched the paddle. The script calculated the new direcon by
subtracng the ball's direcon from the constant value of 180.
As the ball bounced o the paddle, the script put a twist on the direcon change by turning
the ball a random number of degrees between -20 and 20. We'll cover the sprite direcon in
detail later in this chapter.
Making an Arcade Game – Breakout (Part I)
[ 138 ]
Remixing a legacy Scratch project
In the previous exercise, we uploaded a Scratch 1.4 project, which can be idened by the
.sb le extension. Scratch 2.0 will read this le just ne and actually save it as a Scratch
2.0 le, which uses the .sb2 le extension. In case you're wondering, the choice to start
with the legacy version of Pong is a choice made for a few reasons. It's the version I used in
the rst edion of this book, and it ensures that readers of the book always have the same
starng point available to them.
There are Pong starter projects available at scratch.mit.edu, but nding appropriate les
to use in one, two, or more years is not guaranteed. Also, the exercise gives a nice lesson
using old Scratch le formats—namely, it's possible.
Moving a sprite with the mouse or arrows
The script for the paddle moves the sprite le or right based on the x coordinate of the
mouse by using the set x to () block. The script reads the x coordinate of the mouse via
the mouse x block and uses that value to set the x posion of the paddle. The following
screenshot shows the script:
Using reporter blocks to set values
The mouse x block enables us to use the current x coordinate of the mouse as a value for
any block that accepts a numeric value, such as the set x to () block. The mouse x block is a
reporter block in Scratch. Reporter blocks are the built-in variables that capture the current
value of something in Scratch. Other examples include the direcon, mouse y, loudness,
x posion, and y posion blocks. These blocks watch a single value for the sprite they are
enabled for. For example, in Pong, the direcon block always knows what direcon the ball
is traveling in, and that's the value it reports.
Reporter blocks are the oval-shaped blocks found throughout the palee of blocks in
Scratch. And as we'll nd out later in this chapter, when we create our own custom
variables, Scratch will create a corresponding reporter block.
Variables, whether built-in or custom, provide a way for us to use the value in the reporter
block as a value in any of the other Scratch blocks that has an oval shape for a value,
as illustrated in the previous screenshot showing the set x to (mouse x) block.
Chapter 6
[ 139 ]
Customizing the gameplay of the Pong project
There are a few inial customizaons that we will do to make the game easier to use and to
avoid potenal conicts with our Breakout game. You might like using the mouse to control
the paddle, and that's ne. We're going to walk through the process of changing the paddle
control to the le and right arrow keys.
Time for action – adding the left and right arrow controls
Moving the paddle with the mouse works, but users on a laptop may nd their built-in
mouse dicult to use. Let's revise the paddle script to use the le and right arrows to control
movement by following the given steps:
1. Select the paddle sprite from the sprite list.
2. From the Control palee, add the when key pressed block to the scripts area.
3. Change the value to le arrow.
4. From the Moon palee, aach the move () steps block to the when le arrow key
pressed block.
5. Change the value to -10 (negave 10).
6. Repeat steps 4 and 5, but use the right arrow key to move 10 steps.
7. Play the game, and use the arrow keys to move the paddle. The paddle appears to
move slowly across the screen.
8. Let's try to take bigger steps. Change the number of steps to a larger number,
such as 50.
9. Clean up the script by removing the original when ag clicked block that used the
mouse x value to control the movement. From the Moon palee, uncheck the x
posion block.
Making an Arcade Game – Breakout (Part I)
[ 140 ]
What just happened?
Now we have an alternate way to control the paddle that actually runs the move () steps
block based on an arrow key event. The when () key pressed block connually monitors for
a key to be pressed. In our example, we chose to use the le and right arrow keys, but you
could have chosen to use any key you wanted.
When the le arrow key is pressed, the paddle moves a value of -50 steps, which moves the
sprite to the le. The right arrow key gets a value of 50, which moves the paddle right.
The values in the move () steps block, as you might have surmised, match what we expect
when we use the coordinate system to locate a sprite. Negave values move le along the
x-axis; posive values move right.
Evaluating the y position of the ball to end the game
If we look closely at the ball scripts, we see that all scripts will stop when the sprite touches
the color red. This signals that the game is over and that the player lost. Red conicts with
one of the primary colors of the bricks we could use later.
Instead, let's evaluate the y posion of the ball and the paddle to determine if we should
end the game.
Time for action – determining if the ball is below the paddle
In the starter project, the game is over when the ball touches the color red, which matches
the color of the strip at the boom of the stage. Red is going to be one of our brick colors,
so we'll want to adjust our game over condion to be a neutral color.
Basically, we need to determine if the ball falls below the paddle, but in doing so, we're going
to encounter some problems that we'll need to solve. Let's follow the given steps:
1. The game over condion is set by the ball sprite. So select the ball, and remove the
touching color ()? block from the value of the wait unl () block.
2. Replace touching color ()? with the less than block (<) from the Operators palee.
3. From the Moon palee, nd the y posion block, and add it to the le-hand side
of the less than (<) block.
Chapter 6
[ 141 ]
4. From the Sensing palee, add the block that reads (x posion) of paddle to
the right-hand side of the less than (<) block. Change x posion to y posion.
The revised script can be seen in the following screenshot:
5. Now play the game. Does it behave as you expect? In my game, the game ends
when the ball is in the middle part of the stage.
6. To help us debug, turn on the y posion block for the ball and the paddle so
that we can verify that Scratch is correctly following our instrucons. See the
following screenshot, which is showing a game over condion based on our
latest programming changes.
Let's pause and reect on what we're trying to do compared to what we've done.
Making an Arcade Game – Breakout (Part I)
[ 142 ]
What just happened?
We took a working script, made changes, and as a result, no longer have a working game.
But our mistakes are not to be punished; they are to be learned from.
We expect the paddle, which is posioned near the boom of the stage, to have a y posion
of approximately -175. In reality, the y posion of the paddle is closer to 24. Your posion
may vary a bit, but it's clearly nowhere close to what we expect.
So, what's wrong with the paddle?
To answer that queson, we need to know that Scratch determines the x or y posion of the
sprite based on the center of the sprite.
Time for action – adjusting the center of a sprite costume
Let's edit the paddle in the image editor to see where the center of the paddle is by
following the given steps:
1. Look closely at the costume in the paint editor. You likely see a vercal scroll bar in
the editor, and the paddle is not visible unless you scroll down. In the middle of the
screen is a cross mark.
2. The problem is looking straight at us. The center for this costume is not actually on
the black paddle. It's above the actual paddle. Let's redene the center by clicking
on the set costume center icon, located at the top-right of the paint editor.
3. When you click the set costume center icon, two intersecng lines appear on the
image canvas. The current center is at the intersecon of those two lines.
4. To reset the center, click on the intersecon of the lines with your mouse, and drag
the point down to your paddle, as illustrated in the following screenshot:
Chapter 6
[ 143 ]
5. To save the change, just click anywhere on the paint editor canvas.
6. On the stage, the paddle will reposion itself to the middle of the stage.
Drag the paddle back to the boom of the stage to put it in its place.
7. Now, play the game again. This me the game over check works as expected.
What just happened?
For some reason, the center of the paddle costume was disconnected from the visible part
of the sprite. Because neither you nor I created the original project, we can only speculate
why the original game's author made that choice, and speculaon is not going to help us.
By adjusng the center of the sprite to be on the sprite, our new game over evaluaon
works as expected. When the y posion of the ball is less than the y posion of the paddle,
all scripts stop—our current game over condion.
Have a go hero – using the costume center in projects
As Pong demonstrates, the center of the costume determines the locaon of the sprite
in terms of the x and y coordinates. Sprites also rotate around the costume's center.
And in another use, when you tell a sprite to go to the posion of another sprite,
the rst sprite goes to the center of the second sprite.
In Scratch 2.0, you must set the centers of your costumes manually
when you create a sprite or costume.
In theory, seng the center of a costume is a straighorward idea. However, in pracce,
adjusng the center of your sprite's costume could have dramac, interesng, or
confounding consequences. Here's a quick script courtesy of the Scratch Wiki to
clearly demonstrate costume centers:
Draw a square, and ll it with a color. Set the center to the middle of the square.
Animate the sprite using the following script. Then adjust the center of the sprite
to be on a corner of the sprite. Compare the rotaon dierences.
Making an Arcade Game – Breakout (Part I)
[ 144 ]
Cloning to create identical sprites
We're going to use a Scratch 2.0 feature called cloning to easily create rows of bricks that the
player breaks during gameplay.
Time for action – drawing bricks
To clone a brick, we need to rst make a brick. We'll use the paint editor to do that. We'll use
this single brick to build a connuous row of bricks across the width of the stage in a later
exercise. Let's follow the given steps to create a brick:
1. Create a new sprite with the paint new sprite icon, and then convert the sprite to
the vector mode.
2. Use the rectangle tool to create a solid yellow shape.
3. Draw the rectangle to be 48 pixels wide and 25 pixels tall. To see the current size
of the rectangle, look at the thumbnail of the costume to see the current size. The
width of 48 pixels will allow us to create 10 blocks to span the width of the stage.
We have more exibility in the actual height.
4. The following screenshot shows the costume thumbnail with the image dimensions:
5. You can resize the height and width of the shape by dragging the borders of the
rectangle. This step takes some nesse to get the right size.
6. Don't forget to set the costume center.
Chapter 6
[ 145 ]
What just happened?
This step actually takes some planning as the exercise suggests. We want the row of bricks to
span the enre width of the stage, which is 480 pixels. So a 48 pixel wide block will take 10
blocks to span the stage.
We drew the brick using Scratch's built-in image editor, and even though it's a bit awkward,
it is possible to resize the sprite to a target size if the image is in vector format. An alternave
way to create a block to a specic size would be to use a third-party image editor to create
the image and then import that image into Scratch.
Time for action – cloning bricks
Our task is to take the single brick and connuously duplicate it unl we create two solid
rows of yellow bricks that span the width of the stage. As we work through the exercise,
we'll make a couple of calculaons to accomplish the task, and we'll e it all together aer
we create the script. Let's follow the given steps for cloning bricks:
1. Start the script with a when ag clicked block, and add the show block.
2. We need to specify the starng point of the blocks, so add the go to x: y: () block
from the Moon palee. We're going to assume a starng point on the le-hand
side of the stage. Set the x: value to -216 and the y: value to 25.
3. Add a repeat () block, and change the value to 10.
4. From the Control palee, add the create clone of () block, and choose myself from
the drop-down list.
5. Add a go to x: () y: () block to the create clone of () block.
6. From the Operators palee, drag the addion block (+) block into the x: value.
From the Moon palee, add the x posion block to the rst value of the addion
block. Then change the second value of the addion block to 48. Our calculaon
reads x posion + 48, where 48 is the brick size.
7. To the y: value, add the y posion block from the Moon palee.
8. Copy the go to x: () y: () block in step 2 and place it aer the repeat () block.
Change the y: value to be the sum of the y posion + 25. Duplicate the repeat ()
block, and add it to the boom of our stack.
Making an Arcade Game – Breakout (Part I)
[ 146 ]
9. Add a hide block to the end of the stack. The following screenshot shows the script
we just built:
What just happened?
We have a lot to sort out in this stack of blocks. Let's start with the posioning of the rst
brick. We know that the le edge of the stage is represented by an x coordinate of -240.
When Scratch displays the coordinates of a sprite, it uses the center of the sprite, which
means we can divide the length of our sprite in half to get its center point (24 pixels).
The calculaon to nd the starng x posion becomes -240 + 24 = -216.
The starng y coordinate is somewhat arbitrary in the current script. Depending on how
many rows of bricks you add to the level and how tall you make each brick, you may need
to revise the starng height.
Inside the repeat (10) block, the create clone of (myself) block duplicates the brick ten
mes. The go to x: ((x posion) +(48)) y: (y posion) block advances across the stage by a
value of 48. The number 48 represents the width of the block we created.
With each loop through the repeat (10) block, the script creates a new clone that is 48
pixels to the right of the previous clone. We use the x posion + 48 calculaon because the
x posion block always knows the current posion of the sprite, and we place block two
relave to the posion of block one, and block three relave to block two, and so on unl
the stage width is lled.
Chapter 6
[ 147 ]
The script uses another go to x: () y: () block to posion the second row of bricks. This me, we
change the y value by 25, or the height of one brick, but we use the sprite's current y posion
+ 25 to get the starng height. This way if we do change the starng height of the yellow brick,
we only have to change the y: value in the rst go to x: () y: () block. That's the reason we built
the script using the y posion block in all of the go to x: () y: () blocks even though the height
only changes once. It will make future maintenance and improvements a bit easier.
The second repeat (10) block builds the second row of bricks across the stage and works in
the same way as the rst repeat () block we built.
The end result of our programming is two yellow horizontal rows of bricks. Because
our bricks rely on the most rudimentary designs, the row appears as a connuous strip
of yellow, but rest assured, they are individual bricks. The more eort and design you apply
to the brick, the more realisc it can look. We're not going to get bogged down in design.
You can handle those revisions later.
Dealing with the cloned sprite
In our script, each repeat () block clones itself 10 mes to ll the width of the stage, and
at the very end of the stage, we hide the original yellow brick sprite. If we did not hide this
sprite, we would have an eleventh brick on the second row. Because the clones inherit all
the properes of the original and become separate instances, we no longer have a use of
the original sprite we cloned.
You may be asking, "Why don't we repeat the cloning steps nine mes and leave the original
block showing?"
We could have done that and my early version of the game did that. However, that approach
will convolute our future scripts because we'd have to write one script to break the clones
and one script to break the sprite.
Time for action – breaking bricks when I start as a clone
Cloning works in Scratch in two major steps. First, we need to duplicate the sprite. Second,
we write the scripts that tell the clone what to do.
We created the clones in the previous exercise. Now, let's break the bricks by following the
given steps:
1. From the Control palee, add the when I start as a clone block from the Events
palee to the scripts area of the yellow brick sprite to handle the cloned sprites.
Making an Arcade Game – Breakout (Part I)
[ 148 ]
2. We'll need to connuously check if the ball and the clone touch so that we know
when the brick is supposed to break.
3. Start with a forever block, and then add the if () then block from the Control palee.
4. Inside the if () then block, add the delete clone block from the Control palee,
which will represent the breaking brick.
5. From the Sensing palee, add the touching ()? block to the value of the if () then
block, and select ball as the touching value.
The following screenshot shows the new script (on the right-hand side) and the script we
built in the previous exercise because the script on the le-hand side creates the clone,
while the other script denes what happens to the clone aer it is created.
What just happened?
If you haven't already done so, play this game so that you can see what happened.
Don't worry about what the ball is doing yet.
The script we created for when I start as a clone connually checks each clone to see if it
is touching the ball sprite. If the ball and the clone touch, we delete the clone. And in the
context of our game, deleng the clone is the same as breaking the brick.
Chapter 6
[ 149 ]
What happens when the ball breaks the bricks, in terms of our game, is going to be the
subject of many exercises and also provides endless customizaons.
Cloning explained
As our two previous exercises demonstrated, a clone in Scratch 2.0 is a duplicate of the
sprite being cloned. A clone inherits the costumes, variables, and scripts of the parent sprite;
however, the clone can be modied aer it's created. This makes cloning a very powerful
resource for Scratch programming.
Here's a simple example that shows a clone being modied aer it was created. I used this in
my early versions of the cloning bricks exercise to ensure that I was really geng 10 bricks.
In the previous screenshot, the change (color) eect by (33) block changes the color of the
sprite, and we end up with a paern of dierently colored bricks.
Rapid re shooting with cloning
We're using clones to replicate rows of bricks, and each clone can be acted upon
independently, but consider the challenge of an Asteroid-like game where you shoot falling
objects. Prior to Scratch 2.0, we could only re one shot at a me. The shot would have to
miss or hit the target before reloading.
Cloning allows you to shoot a connuous stream of bullets at the target. We can illustrate
the concept using our exisng game of Breakout. The following two scripts show how we
could make our paddle rapid-re balls at the bricks.
Making an Arcade Game – Breakout (Part I)
[ 150 ]
To make the paddle clone the ball (that is, a bullet), use the script in the following
screenshot. The create clone of () block is using a sprite named ball2 because I duplicated
the ball sprite, so I didn't modify the sprite in my game and make inadvertent mistakes.
The following screenshot shows the when I start as a clone block that would be aached to
the ball. The crical control point of the script is the repeat unl () block that will move the
clone (the ball in this example) ten steps unl it touches the stage edge or a yellow brick.
These two scripts could be duplicated and modied for any shoong game you might create.
Cloning related blocks
The following table shows the available cloning blocks in Scratch:
Block Description Example usage
when I start as a clone This block allows the clone
to act independently of the
parent sprite. It waits until
the clone is created to run.
Detects when a clone collides
with sprite
Moves the clone
Changes the clone's
appearance
Chapter 6
[ 151 ]
Block Description Example usage
create clone of () This block clones the
sprite running the block or
another sprite. It specifies
the sprite to be cloned in the
drop-down list.
Rapid-re a never-ending
supply of bullets
Create reworks
Create multiple copies of a
sprite
delete this clone This block gives you a way to
programmatically delete the
clones.
Aer the clone and sprite
collide
After the game is over
Ricocheting with the point in direction block
In a game of Pong or Breakout, controlling the ball's movement is crical, and as a game
designer, you can make the ball move in a predictable way or choose not to. Let's run several
exercises that explore the current ball movement and then revise the script.
Time for action – changing a sprite's direction
Why does the point in direcon () block use the calculaon 180 - direcon? Let's answer
that queson by experimenng with some new direcons as given in the following steps:
1. Select the ball sprite from the sprites list, and nd the script that contains the
point in direcon () block. See the following screenshot:
Making an Arcade Game – Breakout (Part I)
[ 152 ]
Find the calculaon used to redirect the ball and change 180 to 90:
1. Play the game and observe the results.
2. Let's simplify the direcon change. Drag the green number block that currently
contains the calculaon 90 - direcon out of the value of the point in direcon()
block. You can drag it down to a blank spot in the scripts area.
3. Change the value of the point in direcon block to 180. Click the green ag to
play. Observe the results. The ball should always fall through the paddle and to
the boom of the screen.
4. Change the value of the point in direcon () block to 0. Click the green ag to play.
This me the ball bounces back up when it hits the paddle.
5. Drag the turn clockwise block to a blank spot in the scripts area so that it doesn't
run when we play the game.
6. Click the green ag. Each me the ball hits the paddle, it bounces straight up.
7. Restore the 180 - direcon block to the point in direcon () block. The script should
look like the following screenshot:
What just happened?
In the original point in direcon ((180) – (direcon)) block calculaon, the script calculated
a new direcon by subtracng the ball's current posion from 180. For example, if the ball's
direcon is 121, the calculaon subtracts 121 from 180 to get 59. Therefore, the value of the
point in direcon () block becomes 59, and that's the new direcon of the ball. The script
also added a random turn.
The original calculaon always seems to bounce the ball o the paddle and put it in play.
When we changed our calculaon to use 90 - direcon, the ball behavior became much
more errac and may have failed to bounce o the paddle.
Chapter 6
[ 153 ]
When we simplied our direcon with a value of 180, the ball never appeared to bounce o
the paddle. In reality, however, the ball did bounce o the paddle; it just bounced down.
When we set the direcon to 0, the ball bounced o the paddle as expected; however,
it bounced straight up with a bit of an angle. The turn () degrees block ensures the ball
doesn't bounce straight up because it's turning a random number of degrees.
You may note that I didn't put the turn () degrees block back into the script. I'm choosing to
leave it out for now, so that I can have a more predictable bounce as we connue to build
scripts. Aer we get things working, this would be a good eect to add back.
Figuring out the direction
The point in direcon () block has several prepopulated values available. Understanding
what those values mean to Scratch will help us move the ball in the right direcon. The
block does not use a 360 degree circle. Instead, the values are 180 to -180, and that can be
confusing. As a reference point, -90 as a block value would be equivalent to 270 if we were
talking about a 360 degree circle.
The following table outlines how the predened values move the sprite:
Direction value Movement
0 Up
90 Right
-90 Left
180 Down
The point in direcon () block accepts custom values as well. Use the four default values
as a guide to determine which way the sprite will move.
Time for action – setting the starting position and the direction
Let's take what we learned about the point in direcon () block and apply it to the starng
posion of the ball. We'll also set the starng coordinates because the ball currently starts
above the row of bricks. Let's follow the given steps for seng the starng posion and
the direcon:
1. Change the starng x and y coordinates in the go to x: y: block to be -200 and -25.
The value -25 will keep us below the bricks, and -200 posions the sprite on the
le-hand side of the stage.
Making an Arcade Game – Breakout (Part I)
[ 154 ]
2. We want to make sure the ball moves down at the start of the game. Add a point
in direcon () block. Change the value to 135. The revised script can be seen in the
following screenshot:
3. As you play the game, note the direcon being reported in the direcon stage monitor.
What just happened?
The inial starng posion of the ball was above the yellow bricks, so our rst tweak starts
the ball below the bricks on the le-hand side of the stage. By adding the point in direcon
() block, we can control the starng trajectory with a direcon of 135.
Did you noce the ball's direcon? The ball always approaches the paddle at either 135 or
-135 and leaves the paddle at 45 or -45. When the ball bounces on the edge of the stage,
it leaves in the opposite direcon, so it will bounce at -45 or 45.
Without the turn block adding a random rotaon to the block, the movement of the ball is
predictable, and you eliminate the possibility of geng awkward angles as the ball bounces
o the paddle. We can also clearly see our calculaons in acon.
Time for action – ricocheting off bricks
Right now, the ball bounces o the edge and ricochets o the paddle, but it connues
passing through the bricks. We're going to change that behavior by making the ball bounce
o the bricks. Let's follow the given steps:
1. Select the yellow brick sprite. Add a broadcast () block to the script that checks
if the brick touches the ball, and create a new message called bounce. See the
following screenshot:
Chapter 6
[ 155 ]
Troubleshoot with the say block
If you're having problems with a script or you want to be sure a
certain part of the script is working, you can add a say () block,
as seen in the previous screenshot. When the condition is met,
a quick Hello! appears on the screen.
2. Select the ball sprite, and add the when I receive block to the scripts area.
3. Aach a point in direcon () block.
4. We're going to do a calculaon inside the point in direcon () block to redirect the
ball back to the paddle. Add a mulplicaon (*) block from the Operators palee.
Then add a subtracon (-) block to the le-hand side of the mulplicaon block.
5. Add a direcon block to the le-hand side of the subtracon block, and enter 180
to the rst box. Mulply that by -1. See the following screenshot:
What just happened?
This piece of our game creates a realisc response when the ball breaks a brick. Our rst step
was to send a broadcast message when the brick touches the ball. This coordinates the ball's
change in direcon.
Making an Arcade Game – Breakout (Part I)
[ 156 ]
We then told the ball to act on the broadcast with a new trajectory that we calculated
in the point in direcon ((direcon) - (180) * (-1)) block. Now, here is where our exercise
gets interesng. This calculaon is a bit more complicated than changing the direcon when
the ball bounces o the paddle.
Let's run through a simple calculaon. Remember, the ball is traveling at +/- 45 as it leaves
the paddle and +/-135 as it approaches the paddle. This means that the ball approaches the
bricks at +/-45. So, if the ball is traveling in a direcon of 45 and hits a brick, then the new
direcon is calculated as ((45-180)*-1) or 135. If you run the calculaon for a ball direcon
of -45, the new direcon becomes -135.
This creates the same bounce paern as the ball hing the paddle; however, we achieve
it with a variaon of our direcon calculaon for bouncing o the paddle. The end result is
that the ball is reected away from the bricks and towards the paddle.
Conditional statements
If we go back to the when I start as a clone script in use by the brick, we see an if () then
block that checks to see if the brick is touching the ball, and it's wrapped in a forever block.
We rst reviewed forever blocks in Chapter 2, A Quick Start Guide to Scratch. While the
forever block always runs, the code in the if () then block only runs when the condion is
true. Scratch provides several other condional blocks for use in our scripts, as seen in the
following table:
Block Description Example usage
if () This block is deprecated in
Scratch 2.0 and is replaced by
the if () then block. You may
encounter this block if you're
editing a Scratch 1.4 project.
See the if () then block
if () then This block evaluates an
argument, and if the argument
is true, then the code runs.
Compare values
Control a sprite
Check input
if () then else This block evaluates an
argument, and if true, the
code in the if block runs. If
false, the code in the else
block runs.
Run code based on the
checked value such as
checking a player's
"lives" in a game
Evaluating the player's
score
Chapter 6
[ 157 ]
Block Description Example usage
repeat until () This block evaluates an
argument, and if it's false,
the code runs.
Posion a sprite on the
screen
Repeat a script for a
specified time or interval
wait until () When the specified condition is
true, run the blocks following
the wait until block.
Check for game over
Wait for a specific
variable value before
running a script
The condional blocks control when and if something happens, so we nd them in the
Control palee.
Conditional statements in real life
Condional statements are an integrated part of our everyday, non-programming thought
process in that we evaluate our environmental inputs and take acon based on the results.
Here's an example. You want to cross the street. If there are no oncoming cars, you cross the
street. If there are oncoming cars, you wait and check again.
If we reframe our example of crossing the street into a programming statement using one of
Scratch's condional statements, we might say:
If there are no cars coming, then cross the street
If there are cars coming, do not cross the street; else, cross the street
You'll wait unl there are no cars coming before crossing the street
When you receive a walk signal, cross the street
Dening a variable to keep score
How do we know how good we are if our game doesn't keep score? The next step in our
project is to add points each me we break a brick and display the value on the stage.
Before we begin, turn o any remaining monitors from the stage because we no longer
need to see them.
Making an Arcade Game – Breakout (Part I)
[ 158 ]
Time for action – adding a score variable
To keep score, we need to set up a variable and add a condional statement to increment
the score when the ball touches a brick. Let's follow the given steps to add a score variable:
1. From the Data palee, click on the Make a Variable buon to display the New
Variable dialog box.
2. Type the word Score, and select the For all sprites opon.
3. Click on OK to add the variable. The Data palee displays several new blocks,
and the Score reporter block automacally displays a monitor on the stage.
4. Posion the score monitor somewhere on the stage where it won't interfere with
the gameplay, such as in a boom corner.
5. We will increase the score when a brick breaks, so let's work with the yellow brick
sprite. Add the change () by () block from the Data palee aer the broadcast
(bounce) block in the when I start as a clone script. The default block values of
score and 1 are correct.
6. Click on the green ag and play the game. Each me the ball breaks a brick, the score
increments. Play the game several mes and note that we have a running score.
7. We need to reset the score to 0 at the beginning of the game. From the Data
palee, add the set () to () block between the when green ag clicked and show
blocks. The default block values of score and 0 are correct.
8. Play the game a few mes. The score resets to zero each me you click on the
green ag.
Chapter 6
[ 159 ]
9. The following screenshot shows the two revised scripts for the yellow brick sprite:
What just happened?
Each me the ball touches the brick, we increase the score by 1 and display the value on the
stage. At the start of each game, we reset the score to 0, so that the player doesn't add to
the score from the previous game.
When we created the score variable, we set it for all sprites because as we build upon this
game, we will add dierent colored bricks, and this will allow all brick sprites to adjust the
score. Let's review the two dierent variable opons: For this sprite only and For all sprites.
Setting variables For all sprites
When we make a variable for a sprite, we can select the For all sprites opon. This makes a
global variable, which means that all our sprites can access the value stored in the variable.
This has a couple of implicaons.
All sprites can change the value of a global variable; therefore, it can be dicult to track
problems when they occur because we have to invesgate each script in each sprite to nd
all the places that may be aecng our project. The bigger our project gets, the harder it can
be to keep track of global variables.
Making an Arcade Game – Breakout (Part I)
[ 160 ]
We may also end up programming in some unintended consequences, such as adding points
to our score each me we press the right arrow key. Sure, we can track those mistakes down,
but if we can avoid creang those problems, we should.
Working with too many global variables will quickly complicate your scripts because each
sprite has access to the variables, and the Data palee will ll up with variable opons.
Setting variables For this sprite only
In contrast to the global variable, Scratch allows us to create a variable, For this sprite only.
Programmers oen call this a local variable because it can only be accessed by the sprite you
assigned it to.
It's a good programming habit to use a local variable whenever you can because it will keep
your Data palee and variables organized. It also reduces the risk of inadvertently seng
your variable's values by an unrelated sprite.
Have a go hero – creating a graphical effect for the bricks
What happens when the ball breaks the brick? Our game currently hides the brick, but
that's not too excing. Take this opportunity to make the brick do something when it's hit
by the ball. Here are some suggesons to get you started: change color, show a cracked
brick, explode the brick, and so on.
Pop quiz – reviewing the chapter
Q1. When cloning in Scratch, the clone inherits the original sprite's:
1. Costumes.
2. Scripts.
3. Variables.
4. All of the above.
Q2. The center of a costume is always at the center of the visible sprite.
1. True.
2. False.
Chapter 6
[ 161 ]
Q3. What is another way to state Scratch's direcon of -90?
1. 270 degrees.
2. 340 degrees.
3. 135 degrees.
4. 45 degrees.
Q4. Why would you want to use a local (For this sprite only) variable compared to a variable
for all sprites?
1. Local variables are accessible to all sprites.
2. Local variables minimize cluer and future mistakes.
3. There is no reason to use local variables.
4. Local variables are easier to dene.
Q5. Which of the following block commands represents a condional statement?
1. move (10) steps.
2. forever.
3. if () then.
4. repeat 10.
Summary
Right now we have a playable version of our Breakout game with a solid foundaon. The ball
breaks bricks, we keep score, and there's a game over condion. However, there are several
very important concepts introduced in this chapter that will make you Scratch programming
ninjas, including cloning, condional statements, and variables. The game, however, is not
very challenging yet.
In the next chapter, we'll connue building our Breakout game to create a more challenging
gameplay by increasing the ball speed and adding more bricks. We'll learn how to condense
our scripts by turning duplicate blocks of code into a reusable custom block. We'll also take a
look at cloud variables to keep score, which is another one of Scratch 2.0's featured addions.
7
Programming a Challenging
Gameplay – Breakout (Part II)
We ended Chapter 6, Making an Arcade Game – Breakout (Part I) with a
framework for the Breakout game. Basically, we're breaking bricks and keeping
scores in the framework. The game ends if we miss the ball. In this chapter,
we're going to develop the game by adding challenging elements such as
increased ball speed and a shrinking paddle. By the time we finish the chapter,
we'll have a strong foundation that you can continue developing.
Our objecves include:
Making incremental changes to the game, including mulple lives and ball speed
Implemenng custom blocks as a way to consolidate duplicate scripts
Understanding how to use Boolean blocks to control program ow
Creang variables that use cloud data
Debugging and considering alternave soluons
If you've already made a bunch of changes to your game, which will make it dicult for
you to follow this chapter, you can open the project from Chapter 6, Making an Arcade
Game – Breakout (Part I), from the book's source les, and connue working through
this chapter.
Programming a Challenging Gameplay – Breakout (Part II)
[ 164 ]
Implementing lives
Up unl now we have seen that the Breakout game ends when the ball falls below the
paddle, which occurs when the player misses the ball. In the original gameplay, the player
has three turns to clear as many bricks as possible across the two levels.
Time for action – adding a variable to track lives
As we make the game more dicult, it will be appropriate to provide the player with more
than one opportunity to clear the game. We'll do this by tracking the player's lives, as shown
in the following steps:
1. Create a variable named lives. You can create it For all sprites.
2. Let's set the starng value of the new variable at the start of the game. Select the
ball sprite. Then, add a set () to () block to the when ag clicked stack, which sets
the ball's inial posion and direcon.
3. Select the lives variable and enter the value 3.
4. Next, we need to change the logic that ends the game to check for life. To do
this, detach the stop (all) block from the wait unl (y posion) < (y posion)
of (paddle) block.
5. Instead of stopping everything, let's decrease the value of the lives variable. Add a
change () by () block to the boom of the stack. Select the lives variable and enter a
value of -1 in the by value.
6. Add a wait unl () block from the Control palee to the boom of the change (lives)
by (-1) block.
7. Using the () = () block from the Operators palee, make the wait unl () block
evaluate if lives = 0.
8. Then, add the stop (all) block to the end of the stack.
Play this game and miss the ball on purpose. Does your game ever end? How about the lives
value—does it ever reach zero? No. We have a bug.
Chapter 7
[ 165 ]
The following screenshot shows our current script:
Let's pause a bit to examine this script and idenfy the bug.
What just happened?
Adding the lives variable was straighorward. We dened the variable by assigning it a
starng value 3. Each me the player misses the ball, change (lives) by (-1) will run and
reduce the number of lives available to the player. When there are no more lives le, the
game ends. At least, that's how we want our project to work. To understand why it's not
working as expected, we have to gure out how a wait unl () block works.
By this point, we know that the code aer the wait unl () block does not run unl the value
evaluates to true. What's happening in our script is that if we miss the ball once, the lives
variable is properly reduced. The script also evaluates the wait unl (lives = 0) block, which
amounts to false; therefore, our game connues correctly.
When the player misses the ball the second me, we see our bug. The problem is that the
wait unl () block will run only once; therefore, the code to reduce the variable by -1 never
runs more than once, ensuring that the lives variable remains at a value of 2.
We need to rewrite the script to get beer control over the wait unl () blocks.
Time for action – checking for game over
There's going to be more than one way to address our "game over" bug, and that shouldn't
surprise you by now. We're going to approach this problem with the forever block.
Programming a Challenging Gameplay – Breakout (Part II)
[ 166 ]
Let's see what we can do by performing the following steps:
1. First, detach the rst wait unl () block from the script and add the forever
block in its place.
2. Add two if () then blocks to the forever block because we will evaluate two
unique values.
3. The rst if () then block should evaluate the y posion < y posion of
(paddle) statement.
4. Add the change (Lives) by (-1) block to the rst if () then block we just added.
5. Make the second if () then block evaluate lives = 0.
6. Add the stop (all) block to the second if () then block we just added.
7. Play the game and allow the ball to miss the paddle, and then watch your lives
quickly drop to zero. Now, we've found another bug. The following is a screenshot
of our current script:
8. This bug can be overcome by adding a copy of the go to x: () y: () block to the
change (lives) by (-1) block. The following screenshot shows the revision:
Chapter 7
[ 167 ]
What just happened?
Scratch, like any other programming language or computer applicaon, is designed to do
exactly what you tell it to instead of what you think it should do. In addion, we don't know
how far that gap is unl we snap some blocks together and run the code.
We started this exercise knowing that we had to x our wait unl () blocks because they
didn't suciently control the ow of our script. The x was to use a combinaon of a
forever block and two if () then blocks.
The second big problem we encountered was that once the ball fell below the paddle, the
ball remained below the paddle and depleted the player's lives. The ball never went back
into play. The go to x: (-200) y: (-25) block, which we added aer we reduced the player's
life, put the ball back into play like it was at the beginning of the game. Even though we are
going back to the original starng posion, you can choose to randomize the new starng
posion to add some unpredictability.
Evaluating multiple programming solutions
Let's pause for a brief discussion on revising our script. I was provided with an alternave
script to x the bug of reducing the player's life. As the soluons go, the script that was
provided to me is concise and is visible in the following screenshot:
Programming a Challenging Gameplay – Breakout (Part II)
[ 168 ]
It has some benets in which it doesn't duplicate some blocks and uses one of the original
wait unl () blocks. The queson about whether this is a beer soluon or not is a subjecve
debate, as it doesn't inherently work any beer than the original revision that we did in the
exercise. That's the point of our diversion. When you're faced with construcve cricism, you
get to choose how you're going to accept the crique in most cases. Naturally, parents and
teachers get to impose their will on the people they teach, but independent readers always
have a choice about how these scripts come together.
Somemes a funconal script trumps someone else's beauful soluon. Unless I'm xing a
bug or my original soluon was just absolutely hideous, I don't make changes to my script
just because someone else has a "beer" soluon. There are some dierences that make
me consider revising the script in the previous exercise, and it has to do with the starng
locaon and direcon of the ball.
We programmed our ball to start at point (-200,-25) and aer the player misses, we send the
ball back to the same place. The ball, however, will restart in its previous direcon, which
may actually be -135. If it's -135, it will bounce o the side of the stage aer being put back
into play (that is, aer the player misses the ball). Now, the queson is—does that maer?
If it does, then you need to consider revising the script. However, what if we wanted the ball
to start at a specic locaon, but go to a random starng posion aer the player misses the
ball? In that case, the proposed soluon in the previous screenshot will make our change
a bit harder, though not impossible.
Hopefully, you will see that the decision to revise a script is not always a simple right or a
wrong opon. Rather, these changes have complicaons and ramicaons. The decision
about which soluon to implement is yours.
Have a go hero – programming a character's health
Our Breakout game uses lives to track the number of chances a player gets to win the game.
When the player misses the ball, the game takes away a chance. A closely related idea to
lives is health. With health, a character may take several hits unl it is beaten or weakened.
Imagine that you want to insert a super strong brick into the game. You wouldn't want
the player to break the super strong brick with one hit of the ball, right? That wouldn't
be super strong.
With a bit of programming, you can track the number of hits a parcular brick takes. Thus,
you can now break the brick only when the number of hits crosses a threshold; or, you can
weaken the brick by making it smaller with each subsequent hit.
Take a shot at building a super strong brick in the game that takes repeated hits to break.
In the current design, you can place the brick above or below the current rows.
Chapter 7
[ 169 ]
Adding more bricks to the level with a custom block
Currently, we have two rows of yellow bricks. Our next task will be to create a new brick
color and add two more rows to the game using this new brick color. However, this will
require us to revise our exisng code that redraws the bricks, and through this revision,
we will turn the current script into a custom block, which is a new feature in Scratch 2.0.
Time for action – creating a second brick
There are a couple of dierent ways to create a new brick color in the game. We can create
a new sprite with the color or we can add a costume color to the exisng brick sprite.
This exercise will take the costume approach so that we can use a single custom block
to draw all the rows and colors. The steps are as follows:
1. Let's ensure the brick has a valid name that will represent our changes.
I recommend that you use the name brick instead of yellow brick.
2. From the Costumes tab of brick, add a new costume by using the paint new
costume icon.
3. When the blank canvas of the paint editor opens, convert the image to vector
and draw a solid red rectangle that is 45 pixels long and 25 pixels tall because that's
how big the yellow bricks were. We did this exercise in Chapter 6, Making an Arcade
Game – Breakout (Part I).
To give you more control and make it easier to draw the image to a
specific size, zoom in on the image using the zoom icon, as shown in
the following screenshot:
4. Aer you draw the second costume, rename the costumes according to their color;
for example, yellow and red.
Creang these bricks is the kind of process that could very well drive you mad. If you have
problems, go get the book's code bundle and grab the same from the chapter code le.
Also, note that the paint editor has a Clear buon. You can use it to start over.
Programming a Challenging Gameplay – Breakout (Part II)
[ 170 ]
While resizing the sprites, try drawing the sprite smaller than you need it to
be intenonally. Then, drag the edges of the sprite unl it is the right size.
What just happened?
This exercise mirrors our eorts in Chapter 6, Making an Arcade Game – Breakout (Part I).
However, we now have a single brick sprite that has mulple colors, which we'll use in
the game.
Time for action – drawing rows of bricks with custom blocks
The script to create the two rows of yellow bricks is working well; however, we're about to
duplicate a lot of code and potenally have a really large and a dicult-to-manage script.
Let's break the duplicate code into a procedure, also known as a custom block in Scratch 2.0,
as described in the following steps:
1. From the Scripts tab of the brick, click on the More Blocks palee and click on the
Make a Block buon.
2. In the New Block dialog that opens, type in lay bricks in the text eld of the
purple block and then click on OK to create the block.
3. Aer you create the block, Scratch places a block with the name lay bricks in the
More Blocks palee, and in the scripts area, you now have a block tled dene
lay bricks.
4. If you look closely at the code to create the bricks, you'll note that everything in
the repeat blocks is an exact duplicate. Break the script apart and aach one of the
repeat blocks to dene lay bricks.
Chapter 7
[ 171 ]
5. Discard the other repeat block. We don't need it any more.
6. To ensure we're on the right track, let's get our script back to the state where
it makes two rows of yellow bricks. Aach a lay bricks block to the rst
go to x: () y: () block.
7. Then, add the second go to x: () y: () block followed by another lay bricks block.
Finish the stack by reaaching the hide block. The following screenshot shows
our revised script alongside our old script:
The preceding screenshot is only for illustration purposes. Running both of these
scripts at the same time will produce wrong results.
8. If you haven't already tested the code, click on the green ag to ensure it sll works.
9. Now, let's add the red brick. Detach the hide block for a few steps. Add a switch
costume to () block to the stack and select red.
10. Aach a duplicate of the go to x: (-216) y: ((y posion) + (25)) block, followed by a
lay bricks block.
11. Repeat the previous step and reaach the hide block. Refer to the following
screenshot for our new script.
Programming a Challenging Gameplay – Breakout (Part II)
[ 172 ]
12. Add a switch costume to () block aer the show block at the top of this script and
choose yellow.
To delete a custom block, you must first remove all instances of the
custom block from the scripts area. Then, you can drag the define
block to the blocks palette to remove the custom block.
What just happened?
Have you ever built a fort in the backyard, a snow castle, or a LEGO house? If so, this process
should look familiar. First, build a layer of a wall. Then, go to the top of the layer and add a
new one. It's a repeve process where you repeat steps unl you're nished or red.
As Scratch programmers, the repeon of code is a real pain. Note that in the rst version
of the script, we were required to duplicate all the code in the repeat block, two mes for
each brick color we add to the game. By refactoring our code to use a custom block, we've
made the script easier to build, read, and maintain. Note that I'm not saying all duplicaon
is bad or can be avoided, as we've clearly duplicated small snippets of blocks in previous
exercises. However, duplicang two blocks, for example, is much more manageable than
duplicang ten.
Now, for example, if we decide to change the width of the bricks, we have one place where
we can make the change—in the dene lay bricks stack.
Chapter 7
[ 173 ]
I can hear you poinng out the obvious. "But Mike," you're saying, "what's with all the
duplicate go to blocks?". Good point. We'll come back to that.
Introducing procedures by way of custom blocks
Procedures allow us to give a stack of blocks a name that can then be reused in other scripts,
which avoids duplicaon. If you check out other languages, you may come across the term
method or funcon.
The power custom blocks can be seen in the previous exercise. It's a consolidaon of code in
a single line or block.
In Scratch 2.0, a custom block is only available to the sprite that you create it for,
which is the sprite with the dene block.
Prior to Scratch 2.0, Scratch programmers could use broadcasts as a way to provide some
script deduplicaon. There are some obvious dierences as you use custom blocks and
broadcasts. For example, custom blocks accept inputs, whereas broadcasts do not support
inputs (arguments). One of the less obvious dierences is that the custom blocks can support
recursion, which means the dene stack can use the custom block as part of the procedure.
Setting custom block inputs
When we created the custom block in our exercise, you may have observed the New Block
dialog had an Opons menu. The opons include Add number input, Add string input,
Add boolean input, Add label text, and Run without screen refresh, as shown in the
following screenshot:
Programming a Challenging Gameplay – Breakout (Part II)
[ 174 ]
In the Have a go hero – creang a custom block with opons exercise that follows, you'll
have a chance to explore the custom block inputs. We'll also use custom block inputs in
Chapter 9, Turning Geometric Paerns into Art Using the Pen Tool. The following table
provides an overview and a sample of each custom block opon:
Option Description Sample usage
Add number
input
This option passes a
number to the custom
block definition.
The code blocks in the
sample usage column
will shake the sprite six
times.
Add string input With this option, the
text that gets passed
to the custom block
definition can be
printed via the block.
In the sample usage
code shown in the
screenshot (on the
right hand-side of
this table), the block
is passing a variable
with a value 5 and the
text Earthquake.
When the block runs,
the sprite will shake
five times and then say
Earthquake.
Chapter 7
[ 175 ]
Option Description Sample usage
Add boolean
input
With this option, the
statement is evaluated
and runs the custom
block if true.
The sample usage
screenshot (on the
right-hand side of this
table) shows a block
that evaluates whether
or not the current
costume equals 1. If the
costume is 1, the sprite
will shake 10 times.
Add label text This option will provide
a block label that can
give some context to
the type of value that
should be passed to the
custom block.
In the string input example, times and say is the
label on the block.
Run without
screen refresh
If this option is checked,
the block runs all
at once rather than
waiting between blocks.
This block can be used for very large calculations
or scripts.
Have a go hero – creating a custom block with options
We demonstrated the power of procedures by way of custom blocks as a way to consolidate
the code, but the current script to create the rows of bricks sll has a lot of duplicaon.
Here's a two-part challenge. Pass the height of the brick costumes to the custom block,
and incorporate the go to x: -216 y: ((y posion )+ (25)) calculaon as part of the lay bricks
procedure. You'll only need to pass the height of the brick because the procedure we created
already accounts for the width of the brick in the go to block in the procedure. Even though
the height value can always be 25 to match the actual height of our brick, we can change
the height to be bigger than our current brick size, which would create white space between
each row.
You can edit the procedure and add opons by right-clicking on the dene
block or the block name in the More Blocks palee.
Programming a Challenging Gameplay – Breakout (Part II)
[ 176 ]
Part two is to consolidate the script even further by passing the number of brick costumes
you want to use as an input opon to the procedure. By adding this input to the procedure,
you have the necessary variables to make the procedure perform the enre work of building
two rows of bricks for each costume.
The following screenshot shows a modied lay bricks block that passes the number of
brick costumes and the height of the brick or height of row into the procedure. This stack
successfully builds two yellow bricks and two rows of red bricks, just as we le o in our
previous exercise. However, it uses considerably less blocks.
Need a hint? You need to have a control for three values: total costumes, row width, and two
rows per costume. We have already built the procedure to handle two rows for one costume,
so don't throw out what we've done.
Time for action – coordinating the ball play
Now that we have the rows of bricks built and we know all about custom blocks, it's me
for an easier problem. In our script, the ball starts before the bricks are built. We can use
broadcasts to coordinate the two events. The steps are as follows:
1. With the brick sprite selected, add a broadcast block to the end of the stack that
builds the rows of bricks. Give it a clear name, such as play.
2. On the ball sprite, nd the forever block with the move (10) steps and if on edge,
bounce blocks.
3. Replace the when ag clicked block with the when I receive block. Select the
play message.
Chapter 7
[ 177 ]
4. Now, when you start the game, the ball should not start unl aer the bricks are all
created. However, the ball remains visible on the screen. We must hide it by adding
a hide block to the script that inializes the lives variable and sets the starng
posion and direcon. Then, add a show block to the when I receive (play) block.
What just happened?
We don't want the game to start before the screen is fully set up. So, this exercise was all
about geng our ming right by using the broadcast block to ensure the ball doesn't go
into play while the game setup is sll placing the bricks on the screen.
Have you noced a trend yet? One change introduces another problem, which requires
another incremental change. This iterave revision process occurs with any creave
endeavor. Enjoy it.
Increasing ball speed and difculty
At the moment, the ball is moving at a leisurely pace. We know by now that the higher the
value we assign to the move block, the faster the ball goes.
Time for action – increasing ball speed
There are several criteria that we could use to increase the ball speed, such as score or
number of hits. However, we're going to increase the ball speed based on the duraon
of the game. The steps are as follows:
1. To manipulate the ball speed as the script runs, we'll need a variable. So, create a
variable named speed for the ball.
2. Find the ball script that begins with when I receive (play) and add a set () to () block
from the Data palee at the top of the stack. Select the speed variable and give it a
starng value of 5.
Programming a Challenging Gameplay – Breakout (Part II)
[ 178 ]
3. From the Sensing palee, add a reset mer block. We'll use this block with the
understanding that we won't use reset mer anywhere else in the project.
4. Inside the forever block, add an if () then block.
5. We're going to evaluate whether or not the mer block is greater than 10
by snapping the () > () block from the Operators palee into the if () block.
Then, we will add the mer block from the Sensing palee into the rst value.
Type in 10 into the second value.
6. Inside the if (mer > 10) then block, add a change () by block. Select the speed
variable and add a mulplicaon block from the Operators palee to the value.
Mulply the speed variable by 1.2.
7. Add a reset mer block to the if block.
8. Finally, add the speed reporter block from the Data palee to the value of the
move block.
9. Your script should look like the following screenshot. Play the game.
What just happened?
For every 10 seconds the player stays alive, the ball speed will increase by a factor of 1.2,
which ensures we steadily increase the speed and progressively make the game harder.
This project introduced the mer block, and if you enable the mer reporter block, you'll
noce that the built-in me connually runs. By reseng it in our script, we have an easy
way to count me intervals. Using more than one reset mer block in a project will have
unintended consequences and create bugs.
Chapter 7
[ 179 ]
There are three key adjustments in the script we just created: the starng value of the speed
variable, the mer duraon that we evaluate, and the mulplier value in the change () by ()
block. This won't be the only diculty that we will add to our game, but you can adjust these
sengs to get just the right ball speed.
Using Boolean evaluations
In Scratch, the Boolean blocks are hexagonal in shape and t into the hexagonal values
of other blocks. When a Boolean block is evaluated, it reports either true or false. Our
previous exercise demonstrated a common way to control a script using the Control block
and a Boolean evaluaon. The Boolean evaluaon, that is, speed > 10 will either be true or
false. If it's true, then the script increases the speed and the reset the mer block will run.
The following table shows the Boolean blocks included with Scratch:
Block Location Description
() < () Operators This block returns true if the first value is less than
the second value. It also compares the text (for
example, a < b).
() = () Operators This block returns true if the two values are equal.
It also compares the text (for example, f = f).
() > () Operators This block returns true if the first value is greater
than the second value. It also compares the text (for
example, z > a).
() and () Operators This block combines two Boolean blocks where
both have to be true to report true.
() or () Operators This block combines two Boolean blocks but only
one of them has to be true in order to report true.
not () Operators This block evaluates the Boolean to see whether
it is false and reports true if the condition is
false; likewise, it reports false if the condition
is true.
touching ()? Sensing This block reports true if the current sprite is
touching the specified sprite.
touching color ()? Sensing This block reports true if the current sprite is
touching the specified color.
color () is touching ()? Sensing This block reports true if the specified sprite color
is touching the specified color of the stage or any
other sprite.
mouse down ()? Sensing This block reports true if the left mouse button is
clicked.
Programming a Challenging Gameplay – Breakout (Part II)
[ 180 ]
Block Location Description
key () pressed? Sensing This block reports true if the specified key is
pressed.
sensor ()? Sensing This block is only available for use with a PicoBoard.
It reports true if the specified button is pressed or
the specified port is connected.
() contains () Data This block reports true if the specified list contains
the specified text. This block only shows up when a
list is created.
All programming languages will use Boolean expressions, comparisons, and condional
statements as fundamental ways to control what happens in the program.
Keeping score based on a clone's costume
Our Breakout game deserves another challenge. This me, we're going to keep track of the
costume number of the cloned bricks so that we can decrease the paddle size when some
of the yellow bricks are broken.
Time for action – decreasing the paddle size based on the
clones' costume
We have three main tasks. We need to create a smaller costume for the paddle, create the
script to keep track of how many mes the ball touches the brick's yellow costume, and then
build the script that changes the paddle's costume.
To detect the yellow costume of the brick, we have mulple soluons available to us.
However, we're going to pick a slightly more complicated soluon because it oers us more
exibility for future enhancements. We'll revisit some alternaves aer we work through
the exercise. The steps are as follows:
1. Let's start with the paddle rst. Duplicate the exisng paddle costume and then use
the eraser tool to make the costume smaller. Let's name the costumes something
meaningful, such as big and small.
2. While we're thinking about it, let's ensure our game always starts with the big
paddle costume visible. Create a when ag clicked stack for the paddle and add
the switch costume to (big) block.
3. Now, we need to keep track of how many mes the ball hits the yellow sprite's
costumes. To do this, we're going to assign a unique ID number to each clone.
For the ball, create a variable named clone id and set it to For this sprite only.
Chapter 7
[ 181 ]
4. In the dene lay bricks stack, add a change (clone id) by (1) block before the create
clone of (myself) block.
5. Remember, any me we manipulate a variable or seng, we need to reset the
value at the start of the game. Add a set (clone id) to (0) block to the when ag
clicked stack that builds the rows of bricks. The following screenshot shows the
modicaons to the brick sprite's scripts. Your stacks may be slightly dierent if
you did the hero exercise earlier in this chapter.
6. Now that each clone has an ID, we need to evaluate that ID when the ball touches
the clone to determine if we count the hit. To track the hits to the yellow bricks,
create a variable named yellow hits and set it to For all sprites.
7. When Scratch creates a clone of the sprite, the clone inherits the variables assigned
to the sprite. If the variable is local to the sprite, it becomes local to the instance of
the clone and will only be accessible to the clone. However, a global variable will
be available to all clones. Add an if () then block to the if (touching ((ball)?) then
condional statement in the when I start as a clone stack and evaluate the ((clone
id) < (21)) statement.
Programming a Challenging Gameplay – Breakout (Part II)
[ 182 ]
8. Add a change () by () block to the if (clone id) < 21) then statement. Select the
yellow hits variable and enter 1 for the change by value. The following screenshot
shows the script:
9. Now, we need to tell the paddle to shrink, so select the paddle sprite. Start a new
stack with the when I receive (play) block. Add an if () then block.
10. In the if block, evaluate if yellow hits = 0.
11. Inside the if ((yellow hits) = (10)) then block, add the switch costume to () block
and select small.
12. Aer the change (yellow hits) by () block and evaluate the ((yellow hits) = (10))
statement.
Chapter 7
[ 183 ]
What just happened?
The challenge of this exercise is detecng the costume of another sprite, or in this case,
a clone. Scratch does not provide us with a touching (costume #) of (sprite) block.
This block would have alleviated a lot of code. Instead, we had to get creave.
By assigning the clone a unique ID number at the me the clone is created, we can track
that clone no maer where it is on the stage. This is just like the GPS signal from your smart
phone that can be used to locate your posion anywhere in the world among millions of
similar devices. Cloning the costumes of the bricks is a systemac process, and we've already
dened the math behind that process. Each costume gets cloned 10 mes per row for two
rows. That's a total of 20 cloned bricks per costume.
This means the yellow bricks are represented by clone IDs 1 through 20. The red bricks can
be idened by clone IDs 21 through 40. This gives us the rst Boolean evaluaon, that is,
if ((clone id) < 21)).
If the clone ID is less than 21, we instruct the script to add 1 to the yellow hits variable.
Then, the paddle connually checks to see whether yellow hits equals 10. When it does,
the paddle switches to the small costume, thereby creang a more challenging game.
If you followed my step-by-step instrucons, then your game should work. However, if you
doubted the reason to make the yellow hits variable global and instead opted to choose
For this sprite only, then you have a broken script at the moment. If you make yellow hits
a local (For this sprite only) variable, then the change (yellow hits) by (1) variable will not
increment. This is because all clones can access a global variable; however, the For this sprite
only variables are assigned to individual clones, which means the brick clones would not be
able to access the yellow hits variable of the parent sprite unless it is created for all sprites.
In the game, shrinking the paddle aer ten yellow bricks are broken does not mean that
no red bricks were broken. You can opt to shrink the paddle aer 10 bricks of any color.
As a game designer, determining how hard you make the game and at what point you add
a challenge is your privilege.
Considering alternative solutions
Here's another way to solve the problem of tracking the hits to the yellow bricks.
In the following screenshot, the script checks the costume number to determine when to
increment the yellow hits variable. All the yellow bricks have a costume equal to 1 and all
the red bricks have a costume equal to 2.
Programming a Challenging Gameplay – Breakout (Part II)
[ 184 ]
This would be a really good simple soluon. However, it's liming in that we have 20
instances of costume 1 displaying on the stage. What if we wanted to single out the tenth
yellow brick? Looking for costume 1 is not going to help us.
Next, consider the following screenshot, which shows that we can use the () and () block to
ensure that the hit only counts the updated yellow hits variable if the ball is touching the
brick and the color of the brick is yellow:
The code in the previous screenshots would eliminate a variable and the step of assigning a
unique clone ID.
The clone IDs give us more exibility for future features precisely because we can idenfy
each clone individually. By using the clone ID, we can assign weighted points to each brick,
which aects the game score, or we can count the number of total bricks broken as a way
to detect when the level is clear.
The point is that no perfect soluon exists, so we roll with the best one that meets our needs
and abilies at the me.
Time for action – detecting when we clear the level
How do we know when the level is over? The answer is simple, that is, when all the bricks
are broken; so, let's build the simple answer. We know that at the start of the game, there
are 40 bricks on the screen. Let's follow the given steps to detect when we clear the level:
1. The cloud id variable has a record of the total number of bricks we built. Let's assign
that value to a new variable named level hits. Then, we'll actually count down the
level hits variable with each broken brick.
Chapter 7
[ 185 ]
2. Select the brick sprite. Add the set () to () block to the end of the stack that uses
the lay brick custom block. Select level hits as the variable and drag the cloud id
reporter block from the Data palee to the to value. Check your blocks against the
following screenshot:
3. Each me the ball breaks a brick, we will reduce the value in the level hits variable.
Add a change (level hits) by (-1) block aer the change (score) by (1) block in the
when I start as a clone stack.
4. Finally, we need to stop the ball when the level hits variable is equal to zero. Add an
if () then block aer the change (level hits) by (-1) block. Then, add the condion
(level hits) = (0) block.
5. Add a broadcast block to the if ((level hits) = (0)) then block. Create a new message
named level clear. The following screenshot shows the revised script:
Programming a Challenging Gameplay – Breakout (Part II)
[ 186 ]
6. To the ball, add a new script that starts with a when I receive (level clear) block.
7. Then, add a hide block.
What just happened?
We now have a way to stop our game aer the player successfully clears the level. Stopping
the game at this point really means we stop the ball by hiding it. We didn't use the stop (all)
block because you may want to add a second level and the stop (all) block will not allow to
connue with the project.
No maer how many bricks we place on the screen, our script will always know when all the
bricks have been broken by using the clone ID value to provide the total number of bricks on
the stage.
Keeping the score using cloud variables
We'll wrap this chapter up with a small script to assign the player's score to a high score
variable that we will store in the cloud. Consider this a value-added feature because you
could stop right now and have a fully funconal game. Depending on your privacy concerns,
you may not wish to record informaon to the cloud, which will include the user name,
score, and access me. The cloud refers to storing informaon on an internet-based server,
which is hosted by the Scratch Team in this case.
Time for action – keeping a global scoreboard
Currently, there are two condions in our script that signify the end of the game. The rst is
when the player clears the level. The second is when the player's lives become zero. Because
we have some duplicaon, we'll use a custom block to set the score. The steps are as follows:
1. With the ball sprite selected, select the More Blocks palee and click on the Make a
block buon to create a block named update scoreboard.
2. Add the scoreboard block to the when I receive (level clear) block.
3. Add the scoreboard block before the stop (all) script in the if ((lives) = (0))
then block.
Chapter 7
[ 187 ]
4. We need to add a new cloud variable to use in the dene update scoreboard block.
From the Data palee, click on the Make a variable buon. Name the variable
scoreboard and select the cloud variable (stored on the server) checkbox.
5. When you click on OK to create the project's rst cloud variable, you will get an
informaon box that tells you the cloud variables can only be numbers. You can
click on this message to clear it.
6. Add a set () to () block to the dene update scoreboard block. Select scoreboard
as the variable and add the score reporter block to the to value. The following
screenshot shows the changes we just made to the scripts for the ball:
Programming a Challenging Gameplay – Breakout (Part II)
[ 188 ]
What just happened?
By using a Scratch 2.0 feature called cloud variables, we created a scoreboard that gets
stored on the Scratch website. It can only be accessed by our game, but everybody who
plays the game can potenally record their score in the cloud.
If you decide to add a second level to this game, then you will need to remove the custom
scoreboard block from the when I receive (level clear) block and add it to the new last level.
Understanding cloud variables in Scratch 2.0
Being able to store data in the cloud that all users of a Scratch project can access alludes
to great programming possibilies. In the current implementaon of Scratch 2.0, cloud
variables' main benet is the ability to track high scores in games and to conduct surveys
because of the limitaons the Scratch Team has placed on their use. As the exercise pointed
out, cloud variables are limited to numbers.
Cloud variables are only available to users who are signed into their Scratch account;
however, not all Scratch users can access cloud data. New users will most certainly not
be able to access cloud data. According to the cloud data FAQ by the Scratch Team, users
must achieve a Scratcher status before being able to access the cloud. How one aains the
Scratcher status is ambiguously described by the Scratch Team as follows:
You can become a Scratcher through acvely parcipang on the website.
The FAQ secon has more informaon at http://scratch.mit.edu/help/
faq/#clouddata.
These limitaons are in place as of early 2014. As Scratch 2.0 matures, I would expect the
cloud data features to evolve and become more exible.
Viewing the cloud data log
Aer you share a project with the world and the users start interacng with it, the cloud data
is wrien to the Scratch website (that is, the server). When another user remixes a project,
the new project has its own cloud data. The signed-in users can see it by viewing the project
page on the website and clicking on Cloud Data Log.
Chapter 7
[ 189 ]
The following screenshot shows the kind of informaon displayed when a user is logged on
to the server:
As you can see, the user, the informaon about the data, and the access me are all
recorded and are publicly available.
Pop quiz – reviewing the chapter's concepts
Q1. A custom block can be used by:
1. All sprites in the project.
2. All sprites with a global variable.
3. Only scripts that use a Boolean value.
4. Only the sprite it was created for.
Q2. A Boolean reports:
1. The value of the variable.
2. Either true or false the high score of the game.
3. A comparison of two numbers using the and operator.
4. None of these.
Q3. When using variables with clones, you should make the variable:
1. For all sprites.
2. For this sprite only.
3. A cloud variable.
4. Clones can't access variables.
Programming a Challenging Gameplay – Breakout (Part II)
[ 190 ]
Q4. A cloud variable enables a project to:
1. Pass data from one sprite to another sprite.
2. Consolidate duplicate code into a single script.
3. Simulate a sky theme.
4. Store variable data on the Scratch server.
Have a go hero – extending Breakout
There are a many ways you could improve and extend this project based on the foundaon
we've built in the last two chapters. Here are several things to do: add a second level, add
more levels of bricks, design a welcome screen, and calculate a score bonus.
Summary
We nished this chapter with a technically sound framework for a Breakout game that
introduces a couple of Scratch 2.0's highly touted features—custom blocks and cloud
variables. Of course, the concepts we've used in this chapter can be combined with
everything we've learned so far to create an enrely dierent game of your own design.
In the next chapter, we'll create a snarky fortune teller to help answer all our quesons. The
project will prompt the player for a queson and the all-knowing psychic will provide an
answer. In the process, we'll introduce lists to store groups of data and work on scanning
text strings.
8
Chatting with a Fortune Teller
In the Breakout game we created in the previous chapters, we learned how
easy it is to create projects that keep track of the changing values by using
variables. However, variables have a limitation in they store only one value at
a time. In this chapter, we're going to create a random fortune-spewing teller,
which will require the sprites to have access to a list of multiple values at
one time.
Welcome to lists. In Scratch, a list feature allows us to associate one list with
multiple items or values in almost the same way we create a list before going
to the grocery store. We can think of the items in the list as variables. Each list
item can be changed, removed, or added to.
In this chapter, we will take a trip to the fortune teller to demonstrate lists, and I am sure
you'll learn how to:
Store and retrieve informaon in lists
Prompt the player for project inputs, check for errors, and idenfy paerns with
the mod block
Use the if () then else block to control the program
Develop a project test plan
Create a keyword scanner to split and idenfy words and leers
Chang with a Fortune Teller
[ 192 ]
Creating, importing, and exporting lists
Most of us enjoy a good circus, carnival, or county fair. There's fun, food, and fortunes.
What would a fair be without the fortune teller tent? By the end of the chapter, you'll know
everything you need to spin your own fortunes and amaze your friends with your wisdom.
Time for action – creating lists to store multiple values
Before we start the rst exercise, create a new project with exactly two sprites. The rst
sprite will be the seeker. The second sprite will be the teller. Choose any sprites you want and
edit them in any way you wish. My seeker will be Pico and my teller will be a Wizard, both
from Scratch's image library. The seeker will ask the quesons and the teller will provide the
fortune or the answers to the seeker's quesons. As you import your sprites, name them
seeker and teller because that is how I'll refer to them throughout the rest of the chapter.
In order to have a successful fortune telling session, we need two things: a queson and an
answer. Let's start by dening some quesons and answers as given in the following steps:
1. Select the seeker from the list of sprites.
2. From the Data palee, click on the Make a List buon.
3. In the list name dialog box, type in questions and select For all sprites.
4. Click on OK to create the list. Several new blocks will be displayed in the Variables
palee, and a stage monitor tled quesons displays on the stage.
Chapter 8
[ 193 ]
5. Think about a couple of quesons you may be tempted to ask; for example,
"Are you a real physic?" or "If a tree falls in the woods, will it make a sound?".
6. Let's add our proposed quesons to the quesons list. Click on the plus sign (+)
located at the boom-le corner of the quesons stage monitor (on the stage) to
add an item to list; a text input eld will be displayed. If Scratch populates your text
box with ***, remove them and then type in your rst queson.
7. Click on the plus sign (+) again and enter the second queson. We now have two
quesons in our list.
8. Let's add a say () for () secs block to the scripts area of the seeker sprite so we can
start the dialog.
9. From the Data palee, drag the item (1) of (quesons) block to the text value of the
say() for () secs block.
10. Click on the block for the seeker to ask the rst queson in the list.
11. Change the posion value on the item block to last and click on the block again.
This me the seeker asks the second queson, which is also the last queson.
Chang with a Fortune Teller
[ 194 ]
What just happened?
I'm certain you could come up with a hundred dierent quesons to ask a fortune teller.
Don't worry; you'll get your chance to ask more quesons later.
Our exercise introduced another group of Data blocks that allow us to work with lists.
Like variables, making a new list makes several new Data blocks available. The new list
contains zero items, and as we saw in the exercise, we can add items directly to the list.
Another similarity with the variables is that the scope of the list can be limited to this sprite
only or extended to all sprites. We chose to make the quesons list for all sprites because
we will want the teller to access the list of seeker quesons later.
If you work with other programming languages, then you will likely refer
to the lists as arrays.
A quick way to access the items in the list was with the item () of () block. In our example,
we accessed two items in the list: 1 and last. This value was passed to the say block so we
saw it being displayed on the screen.
The most notable dierence between lists and variables is that lists can contain mulple
items, and therefore, mulple values which are accessible via a numbered index. It's a lot
like creang a to-do list.
Working with an item in a list
We can use lists to group related items, but accessing the items in the list requires an extra
level of specicity.
To access an item in a list, we need to know the list name and the
posion of the item in the list. In Scratch, the rst item of the list is made
available by using the number one. In other programming languages,
however, the rst item may be accessed via the number zero.
Chapter 8
[ 195 ]
The following table shows the available ways to interact with the items in a list and the
associated blocks:
Position Description Use and blocks
1 This position identifies the first
item in the list
It is found in the following blocks:
delete () of ()
insert () of ()
replace item () of ()
random This position selects a random
item from the list
It is found in the following blocks:
insert () of ()
replace item () of ()
last This position selects the last
item in the list
It is found in the following blocks:
delete () of ()
insert () of ()
replace item () of ()
all This position selects all items in
the list for deletion
It is found in the following blocks:
delete () of ()
reporter This option reports all the items
in the list as a string
The most common use is to show the list
monitor on the stage by clicking on the
checkbox next to the block's name in the
Data palette
Specify an item
number
This option enters a specific
item number
Type in a number, such as 3, to access the
third item in the list
Importing a list
Entering one item at a me via the Scratch interface is funconal, but the small size of
the list monitor can be dicult to use when you need to add a large number of items.
Fortunately, there's an easier way. You can create a text le outside of Scratch and then
import it to your list.
Time for action – importing fortunes to a list
Now, we'll see how easy it is to import an exisng text le to a Scratch list called answers.
You can use any answers you want, but I'm going to use a list of the common Magic 8-Ball
responses available via Wikipedia at http://en.wikipedia.org/wiki/Magic_8_ball.
My list will contain 20 answers to start.
Chang with a Fortune Teller
[ 196 ]
Let's follow the given steps for imporng fortunes to a list:
1. Create a new list for the teller called answers.
2. Build a plain text le with the answers you want to use in response to the
seeker's quesons. Enter one answer per line in a plain text editor. The following
screenshot shows my list of answers. The book's source les will include a sample
answers.txt le.
3. To import the list, right-click on the answers list monitor and choose import.
This will erase any items you previously added to the answers list.
4. In the Import List dialog box, browse to the answers text le you saved on your
computer prior to starng this exercise and select it. The answers list in Scratch
now contains the contents of the text le.
Chapter 8
[ 197 ]
What just happened?
I don't know about you, but I had a much easier me typing in a text editor than I did typing
in the list monitor that gets created on the Scratch stage. Actually, if you took my lead, you
copied the Magic 8-Ball responses from Wikipedia and pasted them into a text le. That way,
the only typing you had to do was to clean up some formang.
If you completed the cloud variable exercise in Chapter 7, Programming a Challenging
Gameplay – Breakout (Part II), you might be thinking that creang a cloud list would be
a good feature. As of early January 2014, Scratch does not include the cloud funconality
for lists. The early alpha versions of Scratch 2.0 did include references to cloud lists, so it's
reasonable to expect that a future release will put lists in the cloud.
Exporting a list from Scratch
As you create your projects, the contents of a list may change. In that case, you may want
to export the new list, or as a game designer, you may want to export a backup of the list
so that you could revert to a saved copy, because aer an item is removed from the list,
it cannot be recovered.
To export a list, right-click on the list monitor and click on export.
Exporng and imporng a list has one big limitaon. There are no Scratch blocks to either
import or export a list.
Prompting the player for a question
If we wanted to have the seeker and teller interact independently of the player, then the two
lists we have would accomplish that. We could randomly pull a queson from the seeker's
list and then match it up to a response from the teller's list. Our game, however, is going to
be more interacve than that.
By using Scratch's ask () and wait block, the teller can prompt the player for a queson on
behalf of the seeker. In other words, the seeker sprite will represent the human player.
Let's take a look at an example.
Time for action – asking a question
Our task is to make the seeker have a conversaon with the teller and ulmately, ask
a queson. Select the seeker sprite, and let's begin:
1. First, clean the cluer from the stage. Right-click on each of the list monitors and
select hide.
Chang with a Fortune Teller
[ 198 ]
2. Let's stch together some dialog between the two sprites. From the Events palee,
add the when this sprite clicked block to the scripts area.
3. Aach a say () for () secs block and change the text value to a pleasant introductory
sentence such as Hi, wise teller. Do you have my fortune?.
4. Add a broadcast () block, and create a new message named intro (short for
introducon) as a way to signal the teller that the seeker is ready, as shown
in the following screenshot:
5. For the teller, add a when I receive (intro) block to the scripts area, and aach an
ask () and wait block from the Sensing palee. Replace the text value of the ask
block with something that prompts the player to ask a queson on behalf of the
seeker, such as What would you like to know?.
6. Aer the teller receives the queson, add a broadcast () block and create a new
messaged named fortune. Refer to the following screenshot for the teller's script:
7. At this point, if you click on the seeker, you should be prompted for the queson. You
can type in a queson in the text box provided and then press Enter. Pressing Enter
saves the text you typed to the answer block, which is located in the Sensing palee.
The following screenshot shows the teller prompng the seeker for the queson:
Chapter 8
[ 199 ]
8. Let's add the queson to the queson list when the seeker receives the fortune
broadcast. Select the seeker sprite and add the add () to () block from the Data
palee to a when I receive (fortune) block from the Events palee. From the
Sensing palee, drag the answer block to the rst value. Select quesons for the
second value.
9. As a debug step to verify whether the queson was properly stored, add the
following block to the seeker's when I receive (fortune) stack: say (item (last)
of (quesons)) for (1) secs. The following screenshot shows both the scripts we
created for the seeker. You can remove the say block aer you do the vericaons.
What just happened?
Coordinang the back and forth conversaon between the seeker and the teller by using the
broadcast () blocks should be second nature to you by now. In our fortune teller game, the
player is the seeker, so the ask () and wait block prompts you, the seeker, for a queson.
The ask () and wait block forces the script to wait for the keyboard input, which means our
script stopped unl we provided input.
We'll make the teller answer the queson in an upcoming exercise, but for now, we've
prompted the player for a queson and saved that queson to the quesons lists via the
answer block. By saving each queson, the seeker has a growing list of quesons.
Because the queson list is for all sprites, we could have the teller add the item to the list.
However, I've made a self-imposed decision that only the seeker will modify the quesons list
even though I want the teller to be able to see it—we are creang a fortune teller, aer all.
Also, by sending a broadcast, we provide a cue back to the seeker that a fortune is coming.
This is an opportunity for future game enhancement by changing the seeker's reacon.
We can use the stored quesons in a variety of ways. For example, we could script an
automated demo of the game, or we could check for duplicate answers as a way to prevent
sneaky seekers from repeang quesons and uncovering the teller's decepon.
Chang with a Fortune Teller
[ 200 ]
Using stored questions
If we wanted to make the seeker repeat the queson, the say (answer) for (2) secs block
that we used as a vericaon step provides the way to access the last queson in the list.
In our game, we will use the list of stored quesons as a way to check for duplicate quesons
from the player, which will allow us to add error checking into the game.
Time for action – validating the seeker's question
Now that we're prompng the player for a queson via the seeker and adding it to the
quesons list, it is a good idea to check for some common errors that may come our way.
First, we're going to make sure the seeker types something into the textbox when prompted.
Secondly, we're going to check for the duplicate quesons because receiving dierent
answers for the same queson may expose the teller's randomness.
Select the Scripts tab of the teller sprite and let's begin:
1. In the when I receive (intro) stack, add a repeat () unl block right before the
broadcast (fortune) block.
2. As we have two condions to check, insert the () and () block from the Operators
palee to the value in the repeat () unl block.
3. In the rst value of the and block, add a greater than (>) block.
4. To the rst value of the greater than block, add the length of () block from the
Operators palee. Then, add the answer block as the length value.
5. In the second value of the greater than block, type in a relavely small number,
such as 5.
6. Now, let's build the second condion in the and block. From the Operators palee,
add the not () block. Then, add the () contains () block from the Data palee. Select
quesons from the available lists. Add the answer block to the contains value.
7. The command that we want to repeat unl both condions evaluate as true is
the ask () and wait block. Add the block and change the ask value to something
appropriate, such as Please ask your question.
Chapter 8
[ 201 ]
8. Test the script by running the program and don't forget to provide invalid answers.
The following screenshot shows the revised script:
What just happened?
We just added a bit of error handling to our script by way of the repeat () unl block. We rst
evaluated the answer to ensure that the length of the answer is more than ve characters.
This essenally creates a minimum length requirement for quesons. In reality, I don't know
of any queson that can be asked in ve characters, but having this condion provides a
starng point for us. Feel free to make the minimum length more dicult by increasing the 5
value in the length of (answer) > 5 block. A false value will cause the teller to prompt the
seeker for a new queson.
In the second condion, we check to see whether the seeker has asked the queson before.
The () contains () block checks the value stored in the answer variable with each item in
the quesons lists. If it nds a match, it reports true. A true value will cause the teller to
prompt the seeker for a new queson because the not operator inverts true to false.
Only when both condions are true do we allow the teller to respond with the fortune,
which is signaled with the broadcast (fortune) block.
One of the limitaons of this approach is that we can only detect exact matches between
the answer value and the contents of the quesons list. An extra space or a typo creates a
dierent value.
Deleting the list values
As you spend me creang and tesng the scripts, you may want to clear your quesons list
so that you can start with an empty list. Scratch has a block for that.
Chang with a Fortune Teller
[ 202 ]
The delete () of () block can be found in the Data palee. The rst value of the block accepts
a posion in the list and the second value selects the list. You can specify a number, 1 or
all. The following screenshot shows the full command to remove all the items from the
quesons list:
You could run the block manually to remove the list items or add it as part of the start up
script when the green ag is clicked.
Have a go hero – nding and using the player's username
You want a smart and cordial fortune teller, right?
Scratch 2.0 introduced a new block in the Sensing palee called username, which reports
the username of the player who is viewing the project. Modify the teller's inial response to
address the player (also known as the seeker) by his or her username.
Remember that not all users will be signed into their Scratch account, or they may be using
an oine version of Scratch, which means the username will not be available. Your script
should check for the value of the username. How do you know if the player's username
block has a value? Think about how we evaluated the length of the seeker's queson.
Selecting a random fortune
The reason we visit the fortune teller is to hear a fortune. It's me to make the teller pull
a random fortune just like real life.
Time for action – selecting a random fortune
We're going to use a separate stack of blocks to handle the script to issue a fortune. The
steps are as follows:
1. With the teller sprite selected, add a when I receive (fortune) block to the scripts
area. Aach a say () for () secs block.
2. From the Data palee, drag the item () of () block into the rst value of the say
block. Select random for the posion value and answers from the available lists.
Chapter 8
[ 203 ]
3. Test the program by clicking on the seeker sprite. If all goes well, you will receive an
answer (that is, a fortune) in response to your queson. If your seeker repeats the
queson, you can remove the say block we used as a debug step in the previous
exercise. The following screenshot shows our sample script so far.
What just happened?
We'll pause here for a brief moment, so you can reect on your future life as a physic in
the carnival. Our game framework is complete in that we have everything we need to ask
a queson and receive a fortune.
In this exercise, we reiterated our use of the item () of () and say blocks. Based on our use of
the item () of () and say blocks, we can answer any queson that can come our way, and our
response will seem profound. At least, that's what we'll choose to believe.
Time for action – counting our fortunes with mod
Now, we will rene how the teller determines what fortune to give by counng the quesons
and issuing a negave response for every h queson. If you copied the list of Magic 8-Ball
responses, as I did, then your negave responses are items 15 through 20 in the answers list.
If you added your own answers to the list, move the negave responses to the end of the
list. You can do this in a text editor and reimport the answers list. The steps are as follows:
1. Our rst task is to set up a variable to count how many quesons the seeker asks
so that we can calculate whether or not it's me to answer in negaves. Select the
teller from the sprites list and create a new variable named question number
and make it For this sprite only.
2. Add the when ag clicked block to the scripts area.
Chang with a Fortune Teller
[ 204 ]
3. From the Variables palee, add the set queson number to (0) block to the when
ag clicked block. Now, we have a way to reset our counter at the start of the game.
Refer to the following screenshot:
4. Next, we need to assign a value to the queson number variable when the teller
answers the seeker. We can do this by adding a change (queson number) by
(1) block to the end of the when I receive (fortune) script. Refer to the following
screenshot:
5. Our goal is to make the teller sprite give a range of answers based on the queson
number. From the Control palee, add the if () then else block to the change
(queson number) by (1) block.
6. Drag the say ((item (random) of (answers)) for (2) secs block to the "c" part of the
if () then else block.
7. Add a pick random () to () block to the posion value of the item () of () block, which
replaces the block's random selecon. Does it seem strange that we're replacing
the block's built-in random value with a pick random block? If it does, the reason
why we're doing this will be revealed soon.
8. Type in the number 15 to the rst value of the pick random block. For the second
value, add the length of () block from the Data palee. Insert the answers block
as the value.
9. Now, we need to supply a condion to the if block to test whether or not we should
force a negave response. Add the equals to (=) block to the if block.
10. Drag the () mod () block from the Operators palee to the rst value.
11. We're going to use the () mod () block to divide the queson number variable by 5
so that we can calculate the remainder. Add the queson number block to the rst
value of the () mod () block.
Chapter 8
[ 205 ]
The () mod O () block reports the remainder of a division problem,
which makes it useful to identify intervals with numbers.
12. Change the second value of the () mod () block to 5 so the block reads
(queson number) mod (5).
13. Test the script by seeking a fortune. With our current setup, the teller only
responds on the h queson, and it's always a negave response. Refer to the
following screenshot:
If you display the question number stage monitor, you can display
a slider by right-clicking on the stage monitor. The slider lets you
assign a value to the variable, which can help you test your scripts,
as shown in the following screenshot:
What just happened?
We asked our teller to only issue a negave response every h queson, but we needed
a way to let our teller sprite determine when the h queson was asked. We created the
queson number variable as a counter to track the quesons the seeker asked.
In our script, there are a couple of dierent ways to think about the queson number.
The variable is counng the number of fortunes received, which could be further qualied
as the number of quesons accepted by the teller. By incremenng the counter in the when
I receive (fortune) stack of blocks, we ensure the seeker's queson has passed the error
checks we created.
Chang with a Fortune Teller
[ 206 ]
The () mod () block gave us the logic we needed to let the teller calculate whether or not
to issue a negave response. The () mod () block returns the remainder, which means our
script is looking for a remainder of zero—in other words, if we divide a number by ve and
receive a remainder of zero, we know that the queson being asked is an increment of 5
(for example, 5, 10, 15, 20, and so on). And when the remainder is zero, we pick a negave
answer from the list. If we wanted to change the paern to every fourth queson, then the
check would become queson number mod 4 = 0.
Prior to this exercise, we used the default posion value of random in the item () of () block
to select a random item from the list for the fortune. However, in our exercise, we wanted
to restrict the range of possible fortunes, so we used the pick random (15) to (length of
(answers)) blocks. The length of () block reports the current length of the list in terms of
items. In my answers list, the length is 20; therefore, the calculaon picks a random number
between 15 and 20.
The else part of the if () then else block is empty, which is why the teller only issued a
response on every h queson. We'll build the rest of our script as we work through
the remaining exercises.
Using magic numbers
In programming, one of the denions of magic numbers is using constant values in your
code when those values don't really have a clear meaning, and if you work on somebody
else's code, you'll encounter this frequently. Someone's else hack is your pain.
Our expression that picks the negave answer ts the denion of a magic number because
we're dening the range between 15 and the last item posion in the list. When someone
else edits this project, they're going to wonder why we chose this range. Addionally, it will
be worse if someone else adds items to the answers list; that person won't know that the
specied range has a purpose.
Do we have to x this? At the very least, that secon of code should be commented so that
people have some understanding about what it accomplishes. One soluon would be to
move the negave responses to a new list. Then, we run the risk of maintaining duplicate
answers across mulple lists, among some other potenal problems. Another soluon
would be to use variables to set the start and end posions of our negave responses.
In the next exercise, we will x our magic number and make our code clearer.
Creating a custom say fortune block
At this point, we have our teller that issues a negave fortune every h queson, but we
don't have any blocks in place to provide an answer to the rest of the quesons. So, we'll
x that.
Chapter 8
[ 207 ]
Time for action – creating a custom say fortune block
We're about to duplicate a script, so we're going to take this opportunity to create a custom
block to select an item from the answers list based on a specied range of items.
1. With the teller sprite selected, click on the Make a Block buon from the More
Blocks palee. Name the block say fortune in range:. Then, add a number
input and change the input name to start range. Next, add a label with the text
and; nish the block by adding another number with the name end range.
The following screenshot shows the resulng dene block:
2. We want to use a similar set of blocks that we've already added to the if () then
else block as we previously added to the when I receive (fortune) stack. The new
expression will be say (item (pick random start range) to (end range) of (possible
answers)) for (2) secs, as shown in the following screenshot:
3. Let's put the custom block to use in the when I receive (fortune) script. Find the
say () for () block that runs when the condion in the if () then block evaluates
to true and replace it with a say fortune in range: () and () block from the
More Blocks palee.
4. Now, let's x our magic number. Create two variables named start neg resp and
end neg resp. They can be for this sprite (teller) only. Note that I'm abbreviang
my names due to space constraints. Feel free to be verbose.
5. Add the start neg resp reporter block to the rst value in the say fortune block and
the range () and () block. The end neg resp reporter block goes in the second value.
6. We can inialize the values of the new variables as part of the exisng when
ag clicked stack by seng the start neg resp variable to 15 and the end neg
resp variable to 19, or we can use the numbers that represent your range of
negave answers.
Chang with a Fortune Teller
[ 208 ]
7. Next, we need to have the teller predict a fortune when the queson does not t
the paern of every h queson. The expression in the else part of the block is say
fortune in range: (1) and (length of (answers)).
8. The following screenshot shows our revised scripts, including the inializaon script:
What just happened?
Blocks are cheap. Don't be afraid to throw your chosen blocks out in favor of something beer.
In this exercise, we opted to create a custom block so that we can have more control over
the range of answers the teller selects from. The scripts funconally achieve what we've
already done; however, we avoided some duplicaon in the script as well as created a
procedure that could be easily adapted and expanded upon.
Using the if () then else block
In earlier chapters, we've become familiar with the if () then block as a way to run a script
when a condion is true. The false condion doesn't trigger any code.
Chapter 8
[ 209 ]
In contrast, the if () then else control block evaluates a condion, and if the evaluaon is
true, the code in the if part of the block executes. If the condion evaluates to false, then
the code in the else part of the block executes. This can be helpful in scripts where you want a
default acon to happen, regardless of the condional evaluaon. For example, in our project,
we always want a fortune, which is what we get in the else poron. If the fortune answers the
h queson, we want to be more selecve in the response.
Manipulating the text
In this chapter, we've been capturing and storing text as a way to create a dialogue between
the sprites. We use the text in a variety of ways: we type directly in a block, we access a list
item, and we retrieve the text from a variable.
In programming, a piece of text is generally referred to as a string,
and working with strings is a fundamental task.
Let's go beyond whole strings and look at the individual characters of a string.
Time for action – ensuring grammatically correct questions
We have a good grasp on accessing groups of words as a single item, but this exercise is
going to look at the individual characters of those strings. Right now, the teller has a script
that starts with the when I receive (intro) block. It ulmately prompts the player for a
queson and validates the queson before issuing the answer. We're going to revise this
script. The steps are as follows:
1. Detach the broadcast (fortune) block from the boom of the stack and move it
out of the way for now.
2. The exisng repeat unl () block already provides a check for a minimum
length and a duplicate queson. We can perform a third check by adding a
second () and () block to the exisng evaluaon. You'll need to reconstruct the
expression by replacing the not ((quesons) contains (answer)) expression with
an () and () block. The following screenshot shows the revision:
Chang with a Fortune Teller
[ 210 ]
3. To the open value, we want to add the following evaluaon: ((leer (length of
(answer)) of (answer) = (?)). Refer to the following screenshot for details:
4. Aach the broadcast (fortune) block to the end of the script.
5. If you want to revise the text in the second ask () and wait block, feel free to make
it provide some context for the repeated queson; for example, something like,
"Please ask a properly punctuated and unique question".
6. We now have a compact script that validates the queson in three dierent ways.
What just happened?
With some creave block assembly, we're able to idenfy the last leer in our string.
When we nest blocks, Scratch evaluates the innermost block rst. So, the rst value
evaluated in the check for the queson mark is the length of (answer) block. This results in
a number, which tells us how long the string is. That number is used as the rst value of the
leer () of () block. The second value of the leer () of () block is the answer block. Now, it's
a simple equality check to see if the last leer in the answer block equals a queson mark.
We structured our script such that three condions must be true in order for the teller to
provide an answer to the player. The player's queson must be more than ve characters
long, the queson must be original, and it must contain a queson mark. If all three
condions are true, the teller provides an answer to the player. If any of the three
condions are false, the teller prompts the player for a new queson.
Testing your project
One of my greatest joys is soware tesng. It's the reason I know anything about
programming. The layers of queson validaon we're adding to the teller's script is
geng more intricate as we go, which means we have lots of opportunies to create bugs.
Tesng our project requires deliberate steps, and it's a good idea to do some structured
before you turn it loose to the greater Scratch community.
Whether you use a sheet of paper, rely on your memory, or use a spreadsheet, it helps to
create a matrix of tests with the expected results. That way you can verify whether your
script works as you expect it to.
Chapter 8
[ 211 ]
The following table shows a quick matrix to help us test the queson validaon part of the
fortune teller project:
Test Expected result
Enter a question with three letters or characters The teller prompts for a new question
Enter a question that's greater than five letters, is not a
duplicate, and contains a question mark at the end
The teller provides a fortune to the
seeker
Enter a question with more than five characters that is
also a duplicate
The teller prompts for a new question
Enter an original question that is greater than five
letters and does not end with a question mark
The teller reports the error and prompts
for a new question
Enter a question that's greater than five letters, has a
question mark, but is an exact duplicate
The teller prompts for a new question
Creating a keyword scanner
The next logical step in our project is to scan the seeker's queson for individual keywords,
but that will require us to write a script that analyzes the text in the answer block. We know
that words are separated by spaces, so that will become the character we scan for.
Time for action – scanning a text string to build a list of words
The main task in this project is to look for spaces and create new entries in a list when we
nd one. Let's step through the blocks:
1. For the teller, create a new list named scanned words and a new variable
named leer#.
2. Since we will recreate the scanned words list each me we get a new queson from
the seeker, we need to delete all the items before we analyze the new answer block
value. Drag a delete (all) from (scanned keywords) list from the Data palee to the
Scripts area.
3. Next, set the leer# variable to 1, which will track our progress through the
answer value.
4. To iterate through the characters in the answer value, aach a repeat (length of
(answer)) block to the stack.
Chang with a Fortune Teller
[ 212 ]
5. Then, add an if () then else block. We will evaluate the current character of the
answer value to determine if it is equal to a space. The Boolean expression will be as
follows: ((leer (leer#) of (answer)) = ( )). You need to actually type a space in the
second value of the equal to block.
6. If the condion evaluates to true, add an entry to the scanned words list with this
Data block: add () to (scanned words).
7. Add the replace item (last) of (scanned words) with () block to the else branch of
the block condion.
8. In the with value of the replace item block, add a join block. In value one of the join
block, insert item (last) of (scanned keywords). For value two, insert leer (leer#)
of (answer).
9. Finally, increment the leer# counter by inserng a change (leer#) by (1) block
aer the if () then else block.
10. Your project should already have a mulword value stored in the answers from your
previous tesng. Click on the stack of blocks to run the scanner. If the scanned words
list monitor is not showing on the stage, then you need to show it so that you can
inspect the results.
11. The good news is that the script runs and adds an entry to the scanned words list.
The bad news is that the script is only adding the last word in the answer block to
the list. We've got a bug.
12. The error in our script occurs in the inializaon of the lists. Insert an add () item to
(scanned words) block aer the delete (all) of (scanned words) block. Let the value
of add be empty. This inializes the list before we start looping through the repeat
block. Now when you run the script, it should split the string into individual words
and store all those words in the list.
13. The following screenshot shows the nished script:
Chapter 8
[ 213 ]
I rst encountered this script on the Scratch Wiki:
http://wiki.scratch.mit.edu/wiki/Separating_a_
String_Into_Wordhttp://wiki.scratch.mit.edu/wiki/
Separating_a_String_Into_Word
What just happened?
We've seen most of these blocks throughout our work in this chapter. One of the keys to
making the word scanner work is the iteraon through each character of the answer value
and tracking that progress with the leer# variable. I've been using leer and character
interchangeably, but the script is ulmately looking for leers (for example, a, b, c), but
we need to examine all the non-leer characters too. As the script examines each leer,
it checks for a space. A space signals the beginning of a new word, so the add () to () block
adds a new empty word to the list. If you remember our previous encounter with this block,
you know that the new item is added to the last posion of the list.
If the player enters a queson with consecuve spaces, our script will create a new
item with an empty word. Depending on how you use this scanner, that may or may not
be a problem.
As the script encounters a non-space leer, it joins the leer to the current item in the
last posion of the scanned words list, which is the paral word. This is the second key to
understanding this script. For a simple example, let's assume the rst word in the answer is
dog. The last item in the scanned words will be "d", the rst me through the loop. On pass
two, the last item becomes "do". The third pass yields "dog". During the fourth pass, the script
encounters a space and therefore, creates an empty word in the list. You can verify this by
inserng a say ((item (last) of (scanned words)) for (1) secs) block aer the replace item block.
Have a go hero – creating a more intelligent chat bot
The addion of the word scanner script opens up the possibility of scanning the answer value
for a word or words that can be used to trigger a more intelligent or at least a contextual
response. For example, if you scan for "chicken", you could program the teller to respond
with a fortune related to chicken, such as, "Pasture raised chicken has great avor. You will
eat some in the near future".
Currently, our scanner is not integrated into any of our scripts. Your challenge is to scan the
player's answer and respond based on a keyword or keywords. The teller's answer can be
manually issued for each keyword, or you may create a separate list of keywords that trigger
one or more alternate responses.
Oh! And don't forget to update the word scanner to ignore punctuaon when scanning the
answer value.
Chang with a Fortune Teller
[ 214 ]
Pop quiz – understanding how to work with text
Q1. If you wanted to group ten related items together, you would create a:
1. Variable.
2. Numbers block.
3. List.
4. Forever loop.
Q2. If you want to add many items to a list at one me, how would you do it?
1. Type in each item one at a me into the add block.
2. Type in each item into the list monitor that displays on the stage.
3. Export the list from Scratch.
4. Create a list in a text le and import it via Scratch.
Q3. The mod block:
1. Modies a number in the list.
2. Creates a variable that tracks an interval.
3. Transforms the sprite into a leprechaun.
4. Divides two numbers and reports the remainder.
Q4. We use a "counter" variable to:
1. Track how many mes an event occurs.
2. Idenfy how many sprites we have in the project.
3. Select a random item from a list.
4. Add a new item to a specic posion in the list.
Q5. Which of the following blocks gives us the exact length of a piece of text?
1. (leer#) > (length of (answer))
2. Length of () from Data palee
3. length of () from Operators palee
4. item () of ()
Chapter 8
[ 215 ]
Summary
We're well on our way to creang an intelligent conversaon with our fortune teller. I hear
you. Can a conversaon with a fortune teller really be intelligent? An implicit lesson in all of
this is that somemes you need a suspension of disbelief in order to enjoy a good book, a
movie, or a Scratch project.
We have seen the power that the lists and variables give us to create dynamic, exible, and
fun projects. As you worked through this chapter, you probably realized that we could have
used lists in some of our previous projects. For example, our scripts in Chapter 05, Creang
a Mulmedia Slideshow, would have been much smaller had we used lists. However, by
avoiding lists in the earlier chapters, I ensure the projects are suitable for the youngest of
Scratchers, and it sets up a nice illustraon of the pragmac usefulness of lists and variables.
By the me we nished this chapter, we have the foundaon to work with a piece of text
that you may encounter from list items all the way down to individual words and characters.
Whether we're looping through a list, a string, or providing data validaon, manipulang all
that text requires a rm grasp on the use of condional statements and control blocks.
Our programming knowledge has been accumulang nicely to this point even though you
may not know it. In the next chapter, we're going to draw on everything we know as we learn
to draw geometric art in Scratch. We'll turn shapes into owers, pinwheels, and interesng
paerns in addion to creang string art. We'll also explore how to use the nd and use the
color opon in Scratch.
9
Turning Geometric Patterns into Art
Using the Pen Tool
Feeling artistic? Don't worry if you're not. This is art that anyone can do.
We'll make the sprite do all the hard work.
As we work our way through the chapter, we'll be programmatically creating
designs in Scratch by giving the sprite a precise pattern of movements to follow.
At the end of this chapter, we'll have created a shapes drawing project, a color
finder application, and some string art.
These projects will have a place on their own and can be quite addictive to
experiment with. However, they are highly applicable to the work we've done
through the first eight chapters. These art projects, or animations, can be used
in a variety of places including when the player loses in Breakout, to draw stars
on a card, or as level and scene transitions.
In this chapter, we will draw on many of the concepts we've learned so far in addion to
the following:
Exploring the pen blocks to draw basic and user-dened polygons
Capturing user input to create paerns via a custom procedure
Understanding and using color and shade
Drawing asymmetrical paerns and string art
Turning Geometric Paerns into Art Using the Pen Tool
[ 218 ]
Drawing basic shapes
What can you do with a triangle, square, pentagon, hexagon, octagon, and other polygons?
Let's nd out.
Time for action – drawing our rst square
Let's start a new project and call it shapes. We'll work with the default cat sprite using the
following steps:
1. Add the when () key pressed block from Events, and choose the leer d for draw.
We'll use this key to draw the shape.
2. From the Pen palee, add the pen down block.
3. Aach a move () steps block, and set a value of 50.
4. Aer the move (50) steps block, add a turn () degrees block, and change the
value to 90.
5. Duplicate the move (50) steps and turn (90) degrees blocks three mes.
Your script should look like the following screenshot:
6. Press the d key, and observe that the cat quickly draws a square as shown in
the following screenshot. Press the d key repeatedly, and note that the shape
doesn't change.
Chapter 9
[ 219 ]
What just happened?
We drew a square even though it happened too quickly to see, and the cat is parally
obstrucng the line. We'll make our script more concise soon enough, but this simple script
introduces us to the Pen blocks in scratch. By using pen down, we instruct the sprite to draw
using a color. Right now, we're using the default color, but we'll work on changing colors as
we work through future exercises.
If you keep pressing the d key to redraw the square, the cat will connually retrace its path;
however, its moon will be undetectable. Noce that as we move the cat, it's facing in the
same direcon that we started with. If we leave o the last turn (90) degrees block, and press
the d key four mes, the cat will draw the paern as shown in the following screenshot:
Noce that as you draw this shape, the cat draws the smaller squares in a counterclockwise
paern. This is because aer drawing the rst square, the cat is facing up so that when you
draw the second square, the cat rst moves up before making the rst 90-degree turn. And
the paern repeats unl you draw one big square.
Have a go hero – exploring squares
Really quickly, explore this simple script a bit more by removing or adding the move and turn
blocks in the script. For example, what paern do you get if you remove the boom three
blocks of the script we built in the exercise?
Turning Geometric Paerns into Art Using the Pen Tool
[ 220 ]
Time for action – building on the square
Let's clean up our code, get back to a common starng posion, and explore some
addional shapes by performing the following steps:
1. Aer the when (d) key pressed block, add a hide block and a clear block from
the Looks and Pen palees, respecvely. This will hide the sprite and remove
the previous drawing if any.
2. Aer the clear block, add the go to x: (0) y: (0) and point in direcon (90) blocks.
3. Now, aach a repeat () block to pen down. Then drag the move (50) steps and
turn (90) degrees blocks inside the repeat () block. Delete the remaining move
and turn blocks.
4. Change the value in the repeat () block to 4.
5. At the end of the stack, add the pen up block.
6. Double-check your work by pressing the d key. You should get a square, and the
cat should be hidden. The nal script should look like the following screenshot:
7. Now, change the value in the repeat (4) block to 3 and in the turn (90) degrees
block to 120 to get a triangle.
Chapter 9
[ 221 ]
8. Next, try repeang a 72-degree turn ve mes to get a pentagon.
9. Now if you repeat a 36 degree turn 10 mes, you'll get a decagon.
Can you nd the point at which you get a circle? As you experiment and the shape becomes
too large for the stage, experiment with the length of the sides in the move (50) steps block.
What just happened?
Did you noce that the product of the repeat () block and the turn () degrees block always
equaled 360? By controlling the number of sides via the repeat () block and the number of
degrees each line moved, we were able to change shapes.
The following are the outside angles of some common shapes:
A square consists of four 90 degree angles (4 * 90 = 360)
An equilateral triangle has three 120 degree angles (3 * 120 = 360)
A regular pentagon has ve 72 degree angles (5 * 72 = 360)
A regular octagon has eight 45 degree angles (8 * 45 = 360)
When we're drawing our shapes, we're calculang the exterior angles, which will total
up to 360 degrees. The interior angles of various polygons will change with the shapes.
For example, an equilateral triangle has three interior angles of 60 degrees each for a
total of 180 degrees. The interior angles of a regular octagon are 135 degrees each.
Drawing user-dened shapes
Manually changing the values each me we want to create a dierent shape is a real pain,
even for us, project developers. By using variables and stage sliders, we can very easily
create a user interface that allows anyone to draw custom shapes based on the number
of sides, side length, and pen size.
A user interface provides a way for people to interact with the computer program. Enre
disciplines are devoted to designing user interfaces. If you think back to our joke book in
Chapter 4, Creang a Scratch Story Book, the table of contents is an example of a user
interface—it allowed us to select a story. The Breakout game we created in Chapters 6,
Making an Arcade Game – Breakout (Part 1) uses the arrow keys as a way for the user
to control the project.
Turning Geometric Paerns into Art Using the Pen Tool
[ 222 ]
Time for action – enabling the user to create custom shapes
In this exercise, we're going to create variables and enable user-entered values via sliders:
1. Create four variables named sides, length, angle, and pen size. This
automacally adds a stage monitor for each variable.
2. Hide the angle stage monitor. We're going to turn the other monitors into
slider controls. Right-click on each monitor and select slider, as shown in the
following screenshot:
3. Next, add a set () to block from the Data palee as the rst block aer the when (d)
key pressed block. We want to calculate the angle of the shape by dividing 360 by
sides. The set () to block becomes set (angle) to (360/sides).
4. Add the sides reporter block to the repeat block.
5. Add the length reporter block to the move () steps block.
6. Add the angle reporter block to the turn () degrees block.
7. Insert the set pen size to () block above pen down. Add the pen size block as the
size value in set pen size to ().
8. The script looks like the following screenshot:
Chapter 9
[ 223 ]
9. Now use the slider to set dierent values and draw. The following screenshot shows
a solid octagon:
Turning Geometric Paerns into Art Using the Pen Tool
[ 224 ]
What just happened?
We've just made it incredibly easy to doodle with basic shapes. By using variables for the
key values, we eliminate tedious eding of the script every me we want to create a shape.
The slider control makes entering values a snap.
Changing the stage monitor to a slider is a very popular way
for Scratchers to collect user input for use in interacve games
and art.
We introduced the set pen size to () block, which changes the width of the line we draw.
As my previous screenshot depicts, it's possible to use set pen size to () to create a shape
with solid colors. To create a solid square, you can set the pen size variable to the same
value as the length variable. To create other shapes in a solid color, you can experiment
with pen size and/or use a calculaon of length/tan(180/sides) as seen in the following
screenshot. The following code expressions assign the calculaon to a variable named
solid pen size, which would be used in the set () to () block.
It's shown as follows for illustraon purposes and won't be integrated into our project:
In the script we're building, we chose to ask the user for a number of sides, and then we
used that number to calculate the angle of our shape. We could just as easily do the reverse;
ask the user for the angle. Then calculate the number of sides as 360/angle. It's more likely
that the user will know the number of sides.
Time for action – turning triangles into pinwheels
We're just a few blocks short of turning our basic shapes into art and paerns. Let's perform
the following steps to do so:
1. Create another variable called revs (short for revoluons). We'll use this as
the number of mes to repeat our shape. Turn the stage monitor into a slider.
2. Enclose the repeat (sides) block with a new repeat () block. Add the revs
variable as the value in this new block.
3. Add a turn () degrees block aer the inner repeat (sides) block. Use the
calculaon 360 divided by revs for the turn value. The nal script looks
like the following screenshot:
Chapter 9
[ 225 ]
4. Now things are geng interesng. Set the values for the sides, length, revs
variables as 3, 100, and 3, respecvely. Then redraw the shape by changing revs
to 6, 12, and 24, respecvely. The following screenshot shows the paern:
Turning Geometric Paerns into Art Using the Pen Tool
[ 226 ]
What just happened?
The revs variable allows the users to determine how many mes to repeat the paern,
but the most important block to drawing this paern is the turn () degrees block that runs
aer the primary shape is drawn. Without this turn block, the paern would simply retrace
its original path, and we'd only see one shape on the screen.
We calculate the number of degrees to turn by dividing 360 by the user-specied number
of revoluons so that a value of 3 for revs will rotate 120 degrees between each paern.
This calculaon ensures the paern turns a full 360 degrees. This gets us back to the original
starng point and creates symmetry. If you were to show the cat sprite, you'd see that it's
sll facing right at the end of this script in the middle of the stage—exactly where it started.
Have a go hero – adding a stem to the ower
Using the pen tools, draw a stem on the ower. How do you control if the stem appears in
front of or behind the shape? Can you create a square ower?
Dening procedures for home and shapes
Let's take a minute to clean up our scripts and create some custom blocks for the parts of
our code that we're likely to repeat from this point forward. The custom blocks will also
make great addions to our Scratch Backpack.
Time for action – creating a custom shapes procedure
We're going to make procedures (custom blocks) for home and shapes. Home will inialize
our drawing environment, and shapes will handle the drawing:
1. We'll start with dening a home block that sets our inial sprite posion and
values. From the More Blocks palee, click Make a Block, and name it home
as a representaon of an inial starng posion. It will inialize the our
drawing project.
2. Drag these four blocks from the exisng stack, and add them to the dened
home block: hide, clear, go to x: (0) y: (0), and point in direcon (90).
Chapter 9
[ 227 ]
3. Then use the home block from the More Blocks palee to replace the four
blocks you just removed from the when (d) key pressed script. Check the
following screenshot:
4. Next, we'll make a custom block out of the repeat (sides) block. Create a new
custom block named shapes that takes three numbers as inputs: sides, length,
and angle. For clarity, you should add a text label to each number input and
give each input a descripve name. You can see how I chose to do it in the next
screenshot. I tried to nd a balance between name length and comprehension.
5. Drag the repeat (sides) loop out of the exisng script and aach them to the
dened shapes block.
6. Add the shapes block to the script in place of the repeat (sides) loop we just
moved. Then add the reporter blocks for sides, length, and angle into the
respecve values of the shapes block.
Turning Geometric Paerns into Art Using the Pen Tool
[ 228 ]
7. Go back to the dene shapes block to do some clean up. Replace the values
in the script with the custom block values. The following screenshot shows the
new block and scripts:
8. Take a moment to verify that your script sll works.
What just happened?
Aer some inial experimentaon, we ended up with code that will be benecial to our
other drawing projects by creang our own custom procedures. The shapes block now
properly turns the user-specied values into the correct paern.
Plotting the coordinates of shapes
In the examples so far, the length value controlled how long each line segment was.
Even though we started at the center of the stage, we didn't need to worry about the
actual coordinates of our lines. It's incredibly easy to create the paerns that we did.
Chapter 9
[ 229 ]
Throughout the book, we've used the Cartesian coordinate system as a way to move and
posion sprites. The center of the stage is represented as (0,0). Let's take a quick look at
what it would take to draw our simple square using x and y coordinates.
Time for action – plotting x,y coordinates to draw a square
To complete this exercise, just create a new script in the exisng project. That way, we can
make use of our custom home block. Let's perform the following steps to do so:
1. Start the script with the custom home block, and add a pen down block.
2. Next, we need to add four go to x: () y: () blocks. The coordinates for each block
are (100, 0), (100, -100), (0,-100), and (0,0) respecvely.
3. Finish the stack with a pen up block. The following screenshot shows this quick script.
As you run this stack of blocks, you'll conrm that you do, in fact, get a square.
What just happened?
I picked an easy example. We're drawing the square by plong absolute points, meaning we
need to know exactly where to posion the sprite in terms of its x and y posions in order to
get the shape we want. Drawing a pentagon would have been much more dicult. But let's
get back to the square.
In previous exercises, we rotated our shape around a center point to make a paern. If
we try to make similar paerns by plong coordinates, we make the programming more
dicult because now we'll need to know more than the number of degrees to turn. We'd
need to calculate the new coordinates of the square for each revoluon in the paern,
and that would simply make our life unnecessarily hard for this project.
Turning Geometric Paerns into Art Using the Pen Tool
[ 230 ]
The following screenshot represents an alternate stack of blocks that will also draw a square
that is a hybrid between the move and the go to approaches:
In the previous screenshot, we no longer have to worry about the coordinates of the shape.
We're moving by coordinates, but it's relave to the sprite's current posion. However, as
the shapes get more complicated, this method will also become more dicult to use.
Can you spot the dierence between the examples using the go to x: () y: () and the change
by () blocks compared to the move () steps block that we built inially?
In our shapes procedure, we're controlling two points of movement: direcon via the turn ()
degrees block and distance via the move () steps bock. The signicance of this is demonstrated
by the alternate soluons in this exercise.
Understanding and using color
Adding a splash of color can transform a cool shape into a beauful drawing. Next, we'll look
at the set pen color to () and change pen shade by () blocks.
Time for action – coloring our shapes
Let's take a moment to add some color to our drawing by performing the following steps:
1. In the stack that begins with when (d) key pressed, add a set pen color to () block
from the Pen palee below the set pen size to (pen size) block. Enter a value of 15.
There are two set pen color to () blocks. One is a color picker,
and the other block takes a number input.
2. Now draw a shape, and you'll see that the shape is in orange color.
Chapter 9
[ 231 ]
3. Find the set pen shade to () block, and add it aer the set pen color to () block.
Change the shade value to 25.
4. Draw the shape again while leaving the color value set to 15. The color of the
shape has now changed based on the shade.
5. Let's iterate through several colors by adding a change pen shade by () block
inside the end of the repeat (revs) block. Set its value to 25.
6. Now draw the shape again, and observe the color change as each paern gets
drawn. Our script looks like the following screenshot:
What just happened?
When we work with color, it may help us to think of color as having hue, shade, and
saturaon. Saturaon involves the intensity of the color, but we're not going to worry
about it for this discussion. Instead, we'll look at hue and shade as our previous exercise
has already demonstrated. When we work with the set pen color to () and pen shade by ()
blocks, we specify a numeric value that represents the color hue.
The set pen shade to () and change pen shade by () blocks adjust the shade of the color, so
we combine the shade and color hue as in our exercise to get dierent colors, such as red,
orange, light blue, and dark green.
Turning Geometric Paerns into Art Using the Pen Tool
[ 232 ]
The set pen color to () block takes a range from 1 to 200
before the color hues start repeang.
Our sample script shows us a very important feature of the values in Scratch's color blocks.
The default shade is set to 50, which makes a color value of 15 draw in orange. Changing the
shade to 25 drew a dierent orange.
Understanding color shades
The set color shade to () block accepts a base range of 0 through 100. Shade values close
to zero turn darker (for example, black) while values close to 100 turn the color lighter.
However, if you enter shade values greater than 100, the dark/light color alternates. Shade
values 0, 200, 400, and so on will draw dark shades. The values 100, 300, 500, and so on
will draw in light shades depending on the pen color. There are sll only 100 shades, but the
range alternates every 100 so that 1 to 100 goes black to light, 101 to 200 goes light to black,
201 to 300 goes black to light, and so on.
Working with the set pen color to () block
The second set pen color to () block is a color picker. Like the touching color ()? block in the
Sensing palee, the set pen color to () block with the color picker only allows you to select
colors that are visible in the project editor. To use it, click on the color swatch of the block,
and then click on the color you want by selecng it from anywhere in the project editor.
While this method of seng the pen color works if you want to coordinate colors with your
background or sprites, or if the color you want happens to be visible in the project editor,
its limited use in an art project should be self-evident. Sll, picking a color like this is a lot
easier than entering a random number and hoping you get a color you want.
We can create a color sprite to make picking colors easier.
Time for action – nding a color picker workaround
Let's import a color picker sprite from the book's source les so that we can have a full
range of hues to select from in our art projects by performing the following steps:
1. For those of you who do not wish to or are unable to download the source les for
the book, one opon would be to use an image of the color picker in Scratch's paint
editor. You could take a screenshot and crop the image so that only the color palee
is included. Then import the new image into Scratch as a sprite.
2. The easier opon is to look in the code folder for this chapter and nd the image le
named Color_picker.png.
Chapter 9
[ 233 ]
3. From Scratch, click on the Upload sprite from the le icon. Browse for and select the
Color_picker.png le to import it. The image le we're imporng is from the
Scratch Wiki; however, this is the same color picker image that can be found in the
set pen color to () block in Scratch 1.4.
4. Now you can select a color for use in the set pen color to () block by clicking on the
color swatch in the block and then clicking on the new color picker sprite.
5. The following screenshot shows the new sprite. Aer you pick a color, you can hide
or delete the sprite to keep it out of the way of your art project.
What just happened?
With a bit of creave thinking, we now have our own picker that shows the various color
shades. I'd recommend adding this sprite to your backpack so that it becomes available
in all your projects when you need to pick a color.
There's a change from Scratch 1.4 to 2.0 that needs to be acknowledged parally because
I called it out in the exercise. In Scratch 1.4, the set pen color to () and touching () blocks
(from Sensing) actually displayed a color picker similar to what we imported in the exercise,
making color selecon a snap. Scratch 2.0 no longer uses the color picker in conjuncon
with the blocks, and that was the point of the exercise.
In the Sensing palee, the Scratch 2.0 method makes a lot of sense as you generally only
want to sense the colors of the exisng costumes and backdrops. However, when you're
drawing, it's safe to assume that the needed color is not visible in the project and therefore
can't be selected. This exercise gave us a workaround.
Finding a color to use by its number
In the previous exercise, we imported a color picker image into Scratch that contains a wide
range of hues. That's a great color selecon workaround if the project creator is selecng
colors and drawing. However, what if you were to create a drawing that let the user select a
color value? The pickers won't work, but we could allow the users to enter number values.
It would be nice to have a reference that showed the associaon between numbers and colors,
but there doesn't appear to be one available in the Scratch resources. So we'll create our own.
Turning Geometric Paerns into Art Using the Pen Tool
[ 234 ]
Time for action – creating a color palette
How do we know that a color value of 15 will get us orange? Let's create a simple app for
that. We know that we have 200 color values, so let's script a program to draw each color
value for a specied shade.
For this exercise, I'd recommend that you build the script for the color picker sprite we
added in the previous exercise, and then you could add the sprite to your backpack and
have both the picker and the script in one place. Let's run through this exercise, and then
we'll discuss some variaons. If you completed the Breakout game, then the logic for
creang the color swatches in the following exercise will look familiar:
1. Since we will be repeang a paern a set number of mes, create a new variable
called count.
2. Create a custom block named draw colors.
3. Let's set the starng values for our script by aaching the following blocks to the
dene draw colors block:
clear
go to x: (-240) y: (180)
set (count) to (0)
set pen size to (18)
set pen shade to (50)
set pen color to (0)
4. Repeat the following commands unl the count variable is equal to 200:
pen down
move (35) steps
pen up
move (13) steps
change (count) by (1)
set pen color to ((count) + (1))
5. Inside the repeat unl() block, add an if () then block, and evaluate the statement
(count) mod (10) = 0.
Chapter 9
[ 235 ]
6. If the previous statement evaluates to true, then add go to x: (-240) y: ((y posion)
– 18) inside the if () then block.
7. Check your script against the following screenshot, and then run it. The following
screenshot shows a two block script that can be used to clear any pen eects and
then run the new draw colors block:
8. Adjust values in the set pen shade to () block, and compare the colors you get.
Turning Geometric Paerns into Art Using the Pen Tool
[ 236 ]
The following screenshot shows the paern of color our app creates for a shade of 50:
What just happened?
We just applied all of our Scratch learning to solve a problem that we encountered while
trying to create another Scratch project. If you've been through all the chapters in the book
so far, you'd recognize the concepts we used, including mod to track the paern in order to
dynamically build the rows.
We have 20 rows of 10 swatches, and numbering starts at zero in the top-le hand side
corner and ends at 199 in the boom-right hand side corner. That should allow you to nd
color value 15. We drew the grid of colors in such a way that you could easily pick a color
and idenfy the corresponding number by counng. You'll have a chance to automacally
report the number of each color in the next secon, but before we talk about the next
steps, we need to reect on some of the math in the current exercise.
The paern shown in the previous screenshot will take up the enre stage, which is why we
started at (-240, 180). We're drawing 10 colors per row for a total of 20 rows. That gives us
200 colors. In order to make each row span the width of the stage, we need to make each
color take up 48 pixels. Our script actually uses two move () steps blocks to get this done.
We rst set the move (35) steps block, put the pen up block, and then set the move (13)
steps block. This creates the visual whitespace you'll see in the paern of colors. If you
use a single move (48) steps block, there would be no visual separaon. We use 48 in our
calculaons because the stage is 480 pixels wide, and when we divide 480 by 10, we get 48.
To move the paern down the stage horizontally, we need to know that the stage is 360
pixels tall, so when we divide 360 by 20 we get 18. We make 18 the pen size, and we move
the rows down the stage by 18 pixels.
I'd suggest adding this script to your backpack as well.
Chapter 9
[ 237 ]
Have a go hero – nding all shades for a color
There are mulple ways to build upon the color app we just created. We have a quick way to
see all the color hues for a specied shade. The following are a few potenal modicaons:
The script can be duplicated and modied to draw the shades of a specied color.
You can also create a script that reports the color number when you click on a point
on the stage. The code sample includes a possible soluon by rst determining the
x posion and then the y posion. If you think carefully about the numbers that we
used and talked about, you'll have a good starng point. I'll give you a hint by giving
you the coordinate to idenfy the posion on the x axis. The missing part of the
script in the following screenshot is calculang the row based on the y coordinate.
You can develop an applicaon that draws all 100 shades for each of the 200 color
hues. If you want inspiraon for that, check out the project at http://scratch.
mit.edu/projects/18089786/. Actually, this project will give you some hints
about how to use the mouse cursor to idenfy a point on the color picker that
we built. However, it won't translate directly to the version that we created in our
exercise, but it does get you in the right direcon.
Adding color slider inputs to the shapes project
As one of the last pieces of customizaon to this project, let's give the user a way to add
color via a stage slider just as we do for sides, length, pen size, and revs.
Time for action – limiting color values with a slider
Let's perform the following steps to limit color values via the slider:
1. We have two color values to manipulate, so create two more variables with the names
color and shade. Turn each new variable into a slider control on the stage.
Turning Geometric Paerns into Art Using the Pen Tool
[ 238 ]
2. Let's limit the input that the user can enter. Right-click on the color slider, and select
the opon set slider min and max. This will open a Slider Range dialog box as
shown in the following screenshot:
3. In the Min and Max elds, enter 0 and 199 respecvely. Click on OK to save the range.
4. Test the slider control out, and verify that you cannot select a value higher than 199.
5. Now incorporate the color and shade variables into the appropriate blocks in the
script as shown in the following screenshot:
Chapter 9
[ 239 ]
What just happened?
Now, every value in our shapes project can be set by the user via slider controls that are
displayed on the stage. This exercise showed us that we can force the user to enter a range
of values via the set slider min and max opon, which is obviously very useful when we
want to restrict values that a user can enter via the slider controls. In a Scratch project, a
non-programming user will have access to edit the project, but we assume that most of our
users will interact with the project via the user interface we designed. And you'll noce that
if you try to move the slider all the way to the edges, it never passes the dened range.
Even with the sliders, as programmers, we can sll use the set () to () block to assign any
value we want to the variable. The slider controls only limits the the values through the
user interface.
Have a go hero – expanding the shapes application
The shapes applicaon we created has a lot of potenal, and it seems to be well suited to
exploring symmetrical paerns of dierent shapes. The interface could use some renements
before being published to the Scratch community. One recommendaon would be to hide the
sliders when the user draws the shape. That way you can use the enre screen to draw. That
would require an extra step to reset the sliders on the stage perhaps when the green ag is
clicked. You also need to provide some instrucons to the user.
Technically, what else can you do with this basic shape drawing applicaon? Can you move
the paern to a dierent spot on the stage and draw mulple copies? Maybe you can ask
the user for the number of mes to repeat the enre paern and then write the script to
arrange that paern on the stage using all the user-dened informaon. Sll, another idea
would be to instruct the user to click on a point on the stage and then draw the paern
around that point.
Creating asymmetrical patterns
While our work in this chapter has been interesng and insighul, everything has been
symmetrical. In the next exercise, we're going to create a new explosion paern with ever
increasing line lengths and odd angles.
Turning Geometric Paerns into Art Using the Pen Tool
[ 240 ]
Time for action – creating an explosion
Let's draw a paern, and then we'll completely change the paern by changing a couple of
key values. You don't have to, but I'm going to start with a new project.
1. Create a variable named counter. Let's inialize our script with the following set
of blocks:
clear
go to x: (0) y: (0)
set (counter) to (1)
pen down
2. Add a repeat () block and change the value to 125.
3. Repeat the following set of blocks:
move ((counter) * (2)) steps
turn (204) degrees
change (counter) by (1)
4. Next, nish the script by adding the pen up block outside the loop.
5. Check your script against the following screenshot, and then draw the shape:
6. First, remove the (counter) * (2) block from the move () steps block. Then change
the value in the move () steps block to 100, and draw the shape.
Chapter 9
[ 241 ]
7. Now put the (counter) * (2) block back into in the move () steps block. Then change
the value in the turn () block to 185, and draw the shape.
8. The following screenshot shows the three paerns we just drew. Can you gure out
how to draw the fourth paern?
9. You might noce that some of the paerns have a tag end visible where the paern
stops. You can clean that up by adding a move (60) steps block aer the repeat ()
loop. That will not work with the symmetrical paern that we drew using the move
(100) steps version. Experimentaon is the name of the game.
What just happened?
We created a simple but cool project. Our rst twist is the use of the counter variable.
In the past, we've used this type of variable to control the number of mes to loop through
the repeat() block. Even though counter tracks the number of mes the paern has run,
it's used as a mulplier in the move () steps block.
We demonstrated the impact the (counter) * (2) calculaon had on the move () steps block
by removing it and using a constant number, such as 100. The paern became very even
compared with the explosive appearance of the original calculaon.
If you want an easy way to slow down and see the paern develop,
add a wait (.3) secs block at the end of the repeat () loop.
Turning Geometric Paerns into Art Using the Pen Tool
[ 242 ]
Turning straight lines into string art
So far, we've used the pen tools to draw paerns using angles and forward movements
to trace a connuous path. For our next art project, let's straighten our movements out
and create something using nothing but straight lines, which is a technique oen called
string art. The lines will not be connuous.
Time for action – animating a radar screen
To pull o a radar paern, we'll rotate straight lines around a circle, but we'll need to draw
upon our earlier work with colors to make the animated eect. Let's create a new stack of
blocks by performing the following steps:
1. Let's inialize our starng point with the following blocks:
clear
go to x: () y: ()
set pen shade to (50)
pen down
2. Then add a forever block. We want to repeat the following set of blocks:
set pen size to (1)
turn (90) degrees
set pen color to (15)
move (60) steps
move (60) steps
set pen size to (1)
set pen color to (101)
move (-120) steps
turn (1) degrees
3. When you run the script, you should get a paern similar to the following
screenshot. As the paern repeats, the thin, dark lines create a movement
around the center point while the background color remains solid. It's a
relavely noisy paern.
Chapter 9
[ 243 ]
To speed up the pattern, use the turbo mode by shift-clicking the
green flag.
4. Now let's experiment a bit. To see the eect properly, rerun the script so that the
previous paern clears. Set the rst set pen size to () block value to 20, and note
the change in the animaon.
5. Now change the value in the second set pen size to () block to 10.
6. For the next animaon, change the value in the third move () steps block to -60,
and update the last turn () degrees block to 5 degrees.
7. The following screenshot shows a snapshot each of the animaons we just created:
What just happened?
To create these animaons, we're not only drawing on our recently discovered color
knowledge, but we're moving forward and then retracing the line to create some curious
eects. It's the combinaon of color and movement that creates the visible animaon in
the paern.
Remember what we said about color? The smaller numbers such as 15 will be darker, while
the larger number such as 101 will be lighter. The rst two move () steps blocks move forward
60 steps each in the orange color. The third move () steps block advances -120 steps, retracing
the original forward movement; however, this me the color is a light blue, which becomes the
dominant color.
Turning Geometric Paerns into Art Using the Pen Tool
[ 244 ]
There's a lot happening in the animaon. There is a turn (90) degrees block at the beginning
of the loop, and at the end we have a turn (1) degrees block. This second turn will ensure
that the paern eventually overlaps itself. If we run this animaon at normal speed and
not in turbo mode, we noce that it takes many revoluons before we see the noisy
paern of the darker line shows up. Running in turbo mode enhances the visual eect.
The combinaon of the speed of the animaon combined with the slight hesitaon caused
by the two consecuve move (60) steps blocks appears to be the primary reason we see the
paern, because if we consolidate the two move (60) steps blocks with a single move (120)
steps block, the paern disappears.
In our fourth paern, we shortened the backward movement to half of what the forward
movement was; the thick orange circle in the middle of the paern is a direct result of that
uneven movement. The bigger angle at the end of the paern creates a thicker blue line.
Time for action – breaking out of the circle
Not all of our art needs to create a circle, and just to prove it, the following is a quick example:
1. For this paern, we'll use a variable called counter as both a way to control the
number of mes to repeat the paern and a mulplier for the ever-changing x and
y coordinates. Create the variable, if you don't have one in your current project.
2. Set the inial values for the paern as shown in the following set of blocks:
set (counter) to (0)
clear
hide
set pen size to (1)
3. Add a repeat () unl block and use the condion (counter) > (25) as the value.
Repeat the following set of blocks:
pen up
go to x: ((counter) * (10) y: (0)
pen down
go to x: (0) y: (250) – ((counter) * (10))
change (counter) by (1)
4. The resulng paern should match the following screenshot:
Chapter 9
[ 245 ]
What just happened?
The key to this paern is the use of the counter variable as a mulplier. The paern starts
at (0, 0) and moves right along the x axis in increments of 10 with each iteraon, which is
controlled by the calculated value of counter * 10.
The second go to x: () y: () block calculates the desnaon point of the line, which is constantly
dropping vercally. If we were to slow this paern down with a wait () block, we'd be able
to see that at about the sixth pass, the line crosses the top of the paern for the rst me,
creang the curved perspecve—all without a turn () degrees block, you'll note.
There's another signicant value in this script. The loop is repeang 25 mes and we're
using a calculaon of 250 – (counter) * (10) to draw. Repeang 20 mes would not give us
the same complete paern, while 30 would be too much. If we repeat the paern 30 mes,
we would need to calculate the y coordinate as 300 – (counter) * (10). See a paern?
Have a go hero – twisting your perspective
Can you twist your perspecve to gure out how to draw the following paern?
Turning Geometric Paerns into Art Using the Pen Tool
[ 246 ]
Pop quiz – getting into shape
Q1. If you want to draw a square and an octagon, what is the sum of the all the exterior
angles in the shape?
1. You can't do that.
2. 90 degrees.
3. 45 degrees.
4. 360 degrees.
Q2. If you want to select a light shade, which of the following shade values would you use in
the set pen shade to () block?
1. 0.
2. 10.
3. 100.
4. 200.
Q3. How can you restrict the user input to a variable with a slider stage monitor?
1. Users should never be able to control a variable.
2. The slider control cannot be restricted.
3. Right-click on slider, and use the set slider min and max opon.
4. Write a script to validate the user entry.
Summary
Whether it's the simple elegance of a square rotang 18 mes in 20 degree increments or
animated string art, there is a lot to be fascinated by in this chapter. What's more, you could
spend hours exploring these paerns one angle at a me. While not every project has a need
for drawings, adding a strategic drawing to help with level transions or as an indicator that
something happened can add a nice design touch.
The color sprite and app we created in this chapter should go into your backpack so that
they are available for use in all your Scratch projects. You never know when you need to
nd a specic color. Likewise, the custom blocks we created for our home and shapes
projects would be nice addions to your backpack.
In the next chapter, we'll explore our physical world by adding the PicoBoard, our
webcam, and our computers' built-in microphone to our Scratch projects. We'll capture
environmental eects that we can use to control our projects or that we can display via
a Scratch-generated graph.
A
Connecting a PicoBoard to
Scratch 1.4
There are various ways to connect Scratch to the physical world, including
Makey Makey, LEGO® WeDo, Raspberry Pi, and PicoBoard. Even though all
of these devices require add-on hardware to interact with Scratch, they
extend the Scratch experience and enable Scratch projects to connect to the
physical world.
We're going to use the PicoBoard as the basis for our examples, because it
tends to be one of the most popular devices used with Scratch and has a long
history with the Scratch team. With slight modifications, each project can be
adapted to work without a PicoBoard, and therefore, to work with Scratch 2.0.
In this appendix, I will introduce the PicoBoard and show you how to:
Animate webcam images based on detected sound
Monitor and collect environmental data and then graph the results
Explore electrical resistance
As of the publicaon of this book update, Scratch 2.0 does not have full support for add-on
hardware such as the PicoBoard; however, the Scratch team foresees full support at some
point in 2014. Unl Scratch 2.0 fully supports the PicoBoard, you may use Scratch 1.4 to
complete these projects.
Connecng a PicoBoard to Scratch 1.4
[ 248 ]
I've selected projects that have components that will apply to Scratch 2.0 right now,
including the webcam, detecng sound, recording data at set intervals, and graphing.
The fact that I choose to use the PicoBoard to develop these projects acknowledges the
wealth of opportunity to extend Scratch. It's also a nod to Raspberry Pi users for whom
Scratch 2.0 is not currently an opon, but the PicoBoard works on the Pi.
Using Scratch 1.4, the PicoBoard, and Raspberry Pi
Unl Scratch 2.0 fully supports the PicoBoard, you'll need to use Scratch 1.4 to interact with
the PicoBoard. It just so happens that the Raspberry Pi only supports Scratch 1.4 at this
me, and the PicoBoard will work just ne on the Pi. Pi users are a custom-built audience
for Scratch and hardware such as the PicoBoard.
If you run a Linux-based system, then your choice of Scratch versions gets more complicated.
Adobe, the developer of Flash, has announced that it's no longer supporng AIR or Flash on
Linux aer Version 11.2 of its player unless you're running the Chrome browser. Adobe and
Google have a deal to provide a Chrome-only plugin. If you work in an open source operang
system world, then you know the intricacies and frustraons of managing mainstream
soware from companies such as Adobe.
We won't get sidetracked here. Just know that if you're on an open source operang system
and you have problems with Scratch 2.0, then seek out the 1.4 Version. You'll sll have a
great experience.
The boom line is that it appears as if Scratch 1.4 will coexist with Scratch 2.0
for the foreseeable future. Your chances of encountering 1.4 are great.
Finding Scratch 1.4
Scratch 1.4 is available from the following resources:
Installable version: http://scratch.mit.edu/scratch_1.4/
Source code: http://info.scratch.mit.edu/Source_Code
Purchasing the PicoBoard
The PicoBoard is an add-on piece of hardware that has sensors to detect the amount of light,
sound, and resistance. There is also a slider controller and a buon. Today, the PicoBoard is
manufactured and sold by SparkFun (https://www.sparkfun.com/products/10311),
but previous versions of the board were sold by PicoCricket. Consult the manufacturer for
installaon instrucons.
Appendix A
[ 249 ]
Time for action – enabling and testing the PicoBoard support in
Scratch 1.4
The blocks we need to interact with the PicoBoard are hidden by default. Let's enable them
by proceeding with the following steps:
1. Plug your PicoBoard in to your computer and start Scratch. In the Sensing palee,
there are two blocks related to the PicoBoard: the () sensor value reporter block
and the sensor () Boolean block as shown in the following screenshot:
2. Let's ensure we have a signal. Click on the checkbox for the (slider) sensor value
block to show the stage monitor.
3. Then move the slider back and forth and ensure that a value is being reported as
you move the slider. The following screenshot shows the stage monitor:
4. If the block is not detecng a value, double-check your connecons, and ensure you
have the drivers from the manufacturer installed correctly. You should also close
Scratch and reopen it.
Connecng a PicoBoard to Scratch 1.4
[ 250 ]
What just happened?
The PicoBoard is connected, and Scratch is reading values from the board. The () sensor
value and sensor () blocks will be used as values and condional evaluaons for many
other blocks in Scratch.
Adding the PicoBoard support to Scratch 2.0
I know what you're thinking. At the beginning of this appendix, I said Scratch 2.0 doesn't
support the PicoBoard—at publicaon, that's true. You can check if PicoBoard is supported
in 2.0 by shi-clicking on the More Blocks palee. That will display an Add an Extension
buon, which will give you access to Extension Library.
If PicoBoard is available, it will be an opon in Extension Library. You can select it, and then
test the PicoBoard just as we did in the previous exercise. At various mes, the PicoBoard
opon has appeared and reappeared in Extension Library, but it's only a guess as to when
the support might ocially show up in Scratch 2.0.
The following screenshot shows the proposed PicoBoard blocks in 2.0 (from a me when the
extension was available):
Appendix A
[ 251 ]
You can keep yourself updated on Scratch 2.0 and the PicoBoard support via the
following resources:
Scratch News: http://scratch.mit.edu/news
How to connect to Physical World: http://wiki.scratch.mit.
edu/wiki/How_to_Connect_to_the_Physical_World and
http://scratch.mit.edu/newshttp://wiki.scratch.
mit.edu/wiki/How_to_Connect_to_the_Physical_World
Connecting to the Physical World forum: http://scratch.mit.
edu/discuss/32/
Animating webcam images by detecting sound
One of the coolest features of Scratch is its ability to work with your computer's webcam.
The ability to incorporate backdrops (in Scratch 2.0), backgrounds in Scratch 1.4, and sprites
by taking pictures with the webcam has been a long-me feature of Scratch, including the
current version. In this project, we'll incorporate webcam photos with a sound sensor on
the PicoBoard.
Don't have a PicoBoard? Then I'll show you how to use the computer's built-in microphone.
Time for action – creating a talking head
In previous examples, we've seen how easy it is to import images from Scratch's built-
in libraries or from les on our computer. Now, it's me to circle back and check out the
webcam. This exercise will also use the PicoBoard's sound sensor to detect our voice.
To start, create a new project, and delete or hide the Scratch cat and then complete
the following steps:
1. With the stage selected, click on the Backgrounds (Backdrops in 2.0) tab,
and then click on the camera icon. A new window is displayed and shows
what the webcam sees.
On Scratch 2.0, an Adobe Flash Player settings' dialog box will prompt
you to allow or deny access to the computer's camera and microphone.
You must allow access in order to use the webcam.
Connecng a PicoBoard to Scratch 1.4
[ 252 ]
2. Look at the camera with your mouth closed, and click on the camera icon to import
the image. Then open your mouth, and take another snapshot. Click on Done to
close the dialog box. We now have two background images.
3. Name the rst imported image silent and the second one talking.
4. Now let's script our snapshots. Click back to the Scripts tab, and start with
a when ag clicked block.
5. Add a switch to background () block, and select the silent background.
This block is called switch backdrop to ().
6. Now we'll need to connually evaluate whether or not the detected sound
sensor value is greater than 15.
7. Add a forever block followed by an if (), else block from the Controls palee.
Add the greater-than block to the condion value. From the Sensing palee,
add the () sensor value block, and select the sound sensor. Enter 15 for the
block's second value.
If you are completing this exercise without the PicoBoard,
substitute the loudness block for () sensor value to use the
computer's built-in microphone.
8. If the sound is greater than 15, we want to alternate between the two backgrounds.
Add a switch background to (talking) block, followed by a wait (.1) secs block,
which is then followed by a switch background to (silent) block.
9. As the else condion, add a switch backdrop to (silent) block.
10. Click on the green ag and talk. Feel free to experiment with the detected loudness
value and the wait value of the script to see what eects you end up with.
11. Let's make one more enhancement to this script to give our animaon the feel of a
1980s television staon that went o air. Add the following block to the if condion:
set (ghost) eect to ((100) – ((sound) sensor value). Then to the else condion,
add this block: set (ghost) eect to (100). Depending on how loudly you talk, you
might want to experiment with mulplying the (sound) sensor value by some
number, such as ve. Now the image will fade in and out based on the loudness.
The following screenshot shows our script:
Appendix A
[ 253 ]
What just happened?
By combining the backgrounds that we saved from the computer's webcam and the detected
sound levels, we very quickly and easily integrated external data into our Scratch project. The
fact that our talking head looks a lile goofy makes it fun. It reminds me of translated movies
where the English translaon is dubbed in over the original movie. The sound never quite
matches the mouth movements, but it is oen close enough to get the point across.
By adjusng the ghosng eect, we took some of the emphasis o the ming of the script.
The visual strength of the image depends on the strength (loudness) of the detected sound.
With the sound sensor on the PicoBoard, a higher sound value corresponds to a louder
noise. The sensor will report values from 0 to 100 like the loudness block.
When we apply the ghosng aect while speaking, we calculate the new ghost value by
subtracng the sound value from 100. You'll need to experiment with your sounds, but if
the sensor measures a sound value of 20, then the ghost value becomes 80. This ensures
our image is visible but not in full strength. Remember that with ghost, 0 is fully visible and
100 is transparent.
Have a go hero – using sound to move a sprite forward and backward
The talking head makes a great way to introduce Scratch programming in the physical world
because it's quirky and generally makes people chuckle. It's really well suited for an audience
such as workshops or presentaons. I've seen this project done with animated lips, and I've
used it in the past to strobe two colors based on the sound.
Connecng a PicoBoard to Scratch 1.4
[ 254 ]
You could also use the sound value in other projects to change a sprite's costume, to move a
sprite, or to apply a graphical eect. Explore the sound values some more by wring a script
that moves a sprite forward and backward based on the detected loudness of the sound.
Sharing Scratch 1.4 projects online
If you create a project in Scratch 1.4, you can sll share that project to the new Scratch 2.0
website. Other people will be able to view your project on the website. The Scratch 2.0
website will not export a 1.4 le, and as soon as you edit the older le online, it will be
saved as a new Scratch 2.0 format.
You can tell a Scratch 1.4 le by its le extension; they end in .sb while
Scratch 2.0 projects have a .sb2 extension.
Sensing the environment with the PicoBoard
Each of the PicoBoard's sensors is described in the following table:
Sensor Values Description
sound 0 to 100 Captures the sound from via the board's built-in microphone. A
quiet noise will register a lower value than a louder noise.
light 0 to 100 A higher value means that the sensor is detecting more light. As
you block light from reaching the sensor, it reports lower values.
button true or false Clicking on the button causes the sensor to register a true value,
and it will continue to register a true value for as long as the
button is pressed.
slider 0 to 100 Move the slider to select a value. Could be used to provide
numeric input, such as setting the size of a sprite to the selected
value.
resistance 0 to 100 The board includes four analog ports (A, B, C, D) with alligator
clips to measure the resistance in a circuit.
Measuring resistance
The PicoBoard comes with four analog ports labelled A through D. Each port has its own set
of alligator clips to form circuits. We'll be connecng a thermistor to the alligator clips in
order to record the resistance of the thermistor over me. We'll complete this project in
two exercises: one to record values and the other to chart the values.
Appendix A
[ 255 ]
Thermistors are commonly used as temperature sensors, and the next exercise will show
us how to collect values from our thermistor that can be used in conjuncon with
temperature-based experiments. Wikipedia states that:
A thermistor is a type of resistor whose resistance varies signicantly with
temperature, more so than in standard resistors.
Thermistors are inexpensive and available from electric supply outlets that can be found
online and in stores near you.
Time for action – recording the resistance of a thermistor
over time
The following exercise walks us through creang a script that records resistance values based
on an interval. If you don't have a PicoBoard or a thermistor, you could alter the script to
record loudness. We're going to be seng up this project as a way to conduct experiments
with resistance, and because we're using the thermistor, we can draw some conclusions
about temperature.
We'll create the framework to do the monitoring, and at the end of this exercise, you'll have
a thermistor measuring the resistance at room temperature. (Non-PicoBoard users can set
this framework up with the loudness block to capture sound.)
We'll discuss ways to apply our environmental monitor in other interesng ways aer we get
the framework nished up. We create the framework as follows:
1. Let's set up our project. Create a new project, and replace the Scratch cat with a
small circle sprite that you create in the paint editor. You may name it circle sprite.
2. Add a new list called measurements as a place to store the collected results.
3. Make sure the PicoBoard is connected to the computer and has one of the alligator
clips plugged into one of the ports.
4. Connect one lead of the alligator clip to one lead of the thermistor. Aach the
second clip to the other lead of the thermistor.
5. Next, add the when ag clicked block to the Scripts area. Aach the following blocks
to inialize the project:
hide
delete (all) of (measurements)
add (resistance-B) sensor value to (measurements)
Connecng a PicoBoard to Scratch 1.4
[ 256 ]
6. Add a forever block to the script so we can connually run the following blocks:
wait (60 secs)
add (resistance-B) sensor value to (measurements)
7. The following screenshot shows the script. Note that this script will run forever.
We'll review why I chose this script in the upcoming discussion.
What just happened?
If we examine the values that we recorded in the measurements list, they likely do not vary
signicantly at room temperature. The key control point of this script is the interval at which
we collect informaon. Basically, we collect a sample every 60 seconds. We actually record a
measurement before we start the forever loop, which gives us a reading at minute zero that
which would correspond to the start of the experiment, assuming we use this script as the
basis for the experiment.
The script, as wrien, is an innite loop. I'm okay with that. The real queson is, are you?
The reason I chose not to provide an exit for the data collecon is that it may be dicult to
know how long the script should run, and depending on what you choose to measure, you
will be present to manually stop the script and the collecon. If you measure the resistance
of boiling water, you'd be present. If you measure the warming of water from solid ice to
room temperature, you're not sure how long that would take. So, you could set the script
and come back several hours later to check on it.
In other words, you pressing the stop buon in the project is the condion that stops the
data collecon. For example, if you wanted to ensure that you had an exact number of
measurements, you could replace the forever block with a repeat () block. Your choice!
Appendix A
[ 257 ]
The data we collect is dependent on using the alligator clips to form a circuit using
the thermistor. As I alluded, thermistors can be used to calculate a temperature based
on the measured resistance. A widely used formula called the Steinhart-Hart equaon
(http://en.wikipedia.org/wiki/Steinhart%E2%80%93Hart_equation) can be
used to calculate a temperature in Kelvin based on resistance values that could then be
converted to Fahrenheit or Celcius.
Scratch interprets resistance on a scale from 0 to 100, which limits our ability to perform the
actual temperature calculaon based on the measured resistance. For now, the recorded
resistance values could be used to make observaons about temperature; the actual
temperature calculaon is not a goal of our exercises.
Completing a circuit
When we connect the alligator clips together, we basically replicate a switch, like the one
that turns the light in the room on and o. Connect the clips to complete the circuit (that is,
turn it on). Remove one clip to break the circuit (that is, turn it o). In Scratch, a resistance
value of 100 is equivalent to o; no current passes through the circuit. A resistance value of
0 means that current is owing freeing through the circuit without any resistance. Values
between 0 and 100 measure the amount in the circuit.
The following screenshot illustrates the resistance values. The value in resistance-A is
100.0 because the alligator clips are not connected. The 53.8 value for resistance-B is the
resistance value recorded by a thermistor at room temperature (approximately 70 degrees
Fahrenheit), and the resistance-C value of 0.0 is a circuit with no resistance from two
alligator clips connected together.
The loudness reporter block is working in a similar way. A loudness value of 0 means there
is no detected sound, while a value of 100 indicates maximum loudness (as measured
by Scratch).
You can only create a circuit using the alligator clips aached to a
single sensor. In other words, connecng the clips on sensor A to
sensor B will not create a circuit and the values for sensors A and B
will remain 100.
Connecng a PicoBoard to Scratch 1.4
[ 258 ]
When we measure electrical resistance, we want to know by how much the material
impedes an electrical current. In the case of our PicoBoard sensor, the higher the value,
the more the material impedes the current. How we use that value is le to our imaginaon
and the needs of our project.
Time for action – charting our measurements
Now that we have some data in our measurements list, we can create a graph to display the
results. If you did not collect a list of measurements through the previous exercise, you can
import 0724OS_measurements.txt from the book's code les into your measurements
list. If you remember our work with lists in Chapter 8, Chang with a Fortune Teller, you
recall that you can import a list by showing the list monitor, right-clicking on the monitor,
and choosing import. Then you'll have everything you need in order to create a graph.
The following screenshot shows what our nished graph will look like:
I haven't told you much about a thermistor's relaonship with temperature and resistance
yet, which makes drawing any conclusions about the graph dicult. We'll get there, but rst,
let's chart the data as follows:
1. Create a new variable named count that we can use as a way to track our script's
posion in the measurements list.
2. We'll use the when (g) key pressed block as the event to draw the graph. Our rst
group of blocks will inialize our drawing condions as follows:
point in direction (90)
clear
set size to (5) % (You may need to adjust this percentage based on the
original size of your circle sprite.)
Appendix A
[ 259 ]
set (count) to (1)
pen up
go to x: (-150) y: (0)
pen down
3. We should recognize the border around the graph as a rectangle. To draw the
rectangle, repeat the following blocks two mes:
move 300 steps
turn clockwise 90 degrees
move 150 steps
turn 90 degrees
pen up
4. Stop drawing by adding the pen up block aer the repeat (2) block.
5. Now we plot the points. To ensure we see the circle sprite, add a show block. Add a
repeat () block with the following value, which will represent the number of mes to
repeat the blocks: (length of (measurements). Then repeat the following blocks:
go to x: () y: ()
stamp
change (count) by (1)
6. Let's ll in the x: value of the go to block with a simple calculaon (x posion) +
(15). Based on our recorded data, this makes one minute equal to 15 pixels, which
runs along the x axis.
7. For the y: value, we'll use (item (count) of (measurements)) * (2). This means
that we scale each resistance value to two pixels so that a resistance value of 44
will be ploed at 88 on the y axis. This spreads our data out to present a more
readable format.
Connecng a PicoBoard to Scratch 1.4
[ 260 ]
8. Aer the repeat (length of (measurements) block, add a hide block so that the circle
sprite is no longer visible. Our nished script looks like the following screenshot:
9. You can nish up the graph by adding some labels as seen in the screenshot at the
top of the exercise. Using the paint editor to create labels that you posion on the
stage to represent key points would be sucient.
What just happened?
We've used all of the previous concepts throughout the book. The key to making our graph
display is determining how to scale our graph to t onto the Scratch stage. I made a decision
to run the x axis in the center of the screen at y=0.
Our test data was a small sample size, so we actually scaled up to make the graph legible;
if you end up with a lot of data that exceeds your screen size, you would have to scale the
graph down. Making each minute correspond to ve pixels instead of 15 pixels could be
an example.
Appendix A
[ 261 ]
To scale the resistance value on the y axis, we scaled those values up. Knowing some basic
informaon about what we're graphing certainly helps make these decisions. For example,
examining the measurements, I knew the largest value was 44, and we drew the chart
boundary to be 150 pixels tall. Scaling the resistance values by two means that my rst
point is ploed 88 pixels high on the graph's y axis, and everything looks just ne.
We also use the stamp tool from the Pen palee to place individual dots, but a bigger
dataset might be beer served by drawing the curve with a connuous line.
Interpreting the graph
I've been holding back some informaon about a thermistor, but that informaon is
important to understanding what we're graphing. As the temperature rises, the resistance
of the thermistor decreases. So, that means our graph (in the 0724OS_measurements.txt
list) is charng a rising temperature. That graph is shown as follows:
As you see from the graph's now-visible tle, the graph is charng the change in temperature
by way of the resistance as the water rises to boil. Because this is the type of experiment
where you would be monitoring things very closely, you'd know through observaon that
the water started to boil at approximately 12 minutes, which is represented by the levelling
out of the points on the graph. Looking at the actual values in the measurements list, we see
that the resistance levels out at 8.2, making 8.2 the resistance of boiling water as observed
with this thermistor.
This project is more about showing you the possibilies of using a PicoBoard to conduct
experiments and less about teaching you that the temperature of water does not rise the
longer it boils.
Connecng a PicoBoard to Scratch 1.4
[ 262 ]
The graph labels are highlighng key values. The 44 on the resistance (y axis) is marking the
rst recorded value. On the x axis, we measure me, starng at 0 and ending at 20 minutes.
The rst point on the graph is represenng our rst resistance value of 44 (44.1 actually). As
the water warmed, the resistance dropped unl the twelh minute. At minute 12, the water
was in a rolling boil, which is 212 degrees Fahrenheit. From that point on, the resistance was
at, meaning the water doesn't get hoer the longer it boils.
If this was a temperature graph, we would expect to see the graph rise as the temperature
approached boiling. However, with a thermistor, as the temperature rises, the resistance
falls. The graph is accurately describing what happens with the resistance as the water heats.
And here's a general disclaimer. I collected my measurements by suspending the thermistor
into the top one-fourth inch of water and protecng my PicoBoard from the heat source.
I'm not responsible for your acons. Only do experiments if you think through your safety
and consequences. Suspending a thermistor in ice water and measuring values as the water
warms to room temperature would be a less risky alternave.
Time for action – revising the graph
As you see in the previous screenshot, the rst point on the graph is moved to the right by
15 pixels. Our rst measurement in the data that we graphed occurred at zero minutes is not
accurately reected in our graph. Let's make the graph match the numbers more closely by
moving the circle sprite to the le for the rst point as follows:
1. Add a go to x: () y: () block before the repeat () block.
2. Add the expression ((x posion) – (15)) to the x value.
3. Add the expression ((item (count) of (measurements) * (2)) to the y value. The
following screenshot shows the revised script:
Appendix A
[ 263 ]
What just happened?
Our inial graph didn't properly mark the rst point at zero minutes. In our revised script,
we moved the circle sprite to the le by 15 pixels so that when we graph the rst point in
the repeat (length of (measurements)) block, the point was placed properly on the graph.
Have a go hero – brainstorming data collection topics
Unless you're monitoring a doorway that frequently opens and closes, recording the room
temperature probably doesn't provide much excitement. Other items to measure might
include a pot of boiling water or measuring how long it takes for a glass of ice water to
reach room temperature.
You could also run a series of resistance tests with common materials. For example, aach
the alligator clips to a potato, a paper clip, and so on. Record the values and then graph the
results. You may need to modify the collecon framework to record a value based on the
occurrence of an event such as the buon click on the PicoBoard or a key press on
the keyboard.
Let's see what you can come up with!
Pop quiz – connecting to the real world
Q1. What Scratch block can provide an alternave to the PicoBoard's sound sensor?
1. There is no alternave block.
2. The play sound block.
3. The loudness block.
4. The microphone block.
Q2. Why would you choose to use Scratch 1.4?
1. You want to use Scratch on the Raspberry Pi.
2. You want to use the source code.
3. Your current web browser does not support Flash.
4. All of the above.
Q3. What do the analog ports on the PicoBoard measure?
1. Sound.
2. Resistance.
3. Temperature.
4. Weather.
Connecng a PicoBoard to Scratch 1.4
[ 264 ]
Summary
The PicoBoard makes Scratch programming tangible. We can hear the sounds we collect
or feel the temperature we record through the analog ports. Scratch allows us to interpret
those environmental smuli through our projects whether we create a goofy talking head or
more seriously chart measured data as part of an experiment.
The strength of the PicoBoard is that it gives us a new context to apply to our Scratch
projects. We sll use the same programming concepts, but the perspecve of the
informaon we have changes to things we can touch.
That's it! You have all the tools you need to turn your imaginaon and the imaginaon of
your children into your very own mad sciensts' laboratory.
Happy Scratching!
Pop Quiz Answers
Chapter 2, A Quick Start Guide to Scratch
Pop quiz – getting started with scratch
Q1 4
Q2 2
Q3 3
Q4 1
Q5 2
Chapter 3, Creating an Animated Birthday Card
Pop quiz – reviewing the chapter
Q1 4
Q2 3
Q3 4
Q4 1
Q5 3
Q6 1
B
Pop Quiz Answers
[ 266 ]
Chapter 4, Creating a Scratch Story Book
Pop quiz – reviewing the chapter
Q1 2
Q2 1
Q3 4
Q4 3
Chapter 5, Creating a Multimedia Slideshow
Pop quiz – reviewing the chapter
Q1 2
Q2 2
Q3 2
Q4 3
Q5 4
Chapter 6, Making an Arcade Game – Breakout (Part I)
Pop quiz – reviewing the chapter
Q1 4
Q2 2
Q3 1
Q4 2
Q5 3
Appendix B
[ 267 ]
Chapter 9, Turning Geometric Patterns into Art Using the
Pen Tool
Pop quiz – getting into shape
Q1 4
Q2 3
Q3 3
Appendix A, Connecting a PicoBoard to Scratch 1.4
Pop quiz – connecting to the real world
Q1 3
Q2 4
Q3 2
Index
A
Add boolean input opon 175
Add label text opon 175
Add number input opon 174
Add string input opon 174
animaons
making 10
stop-moon animaons 10
arrows
hiding, mouse locaon used 127-129
arrow sprites
used, for ipping through images 114-116
art projects
creang 13
aspect rao 113
asymmetrical paerns
creang 239
explosion paern, creang 240, 241
Atari game 135
B
backdrop blocks
backdrop name 117
backdrop number 117
next backdrop 117
switch backdrop to () 116
switch backdrop to () and wait 116
when backdrop switches to () 117
Backdrop Library
background images, adding from 81-83
backdrop name block 108, 110, 117
backdrop number block 117
backdrops
photos, imporng as 107-114
photos, imporng from les 108-111
Backpack feature
sprite, adding to 83, 84
used, for storing scripts 84
used, for storing sprites 84
ball play
coordinang, broadcast block used 176, 177
ball, Pong project
posion, evaluang to end game 140-142
ball speed
increasing 177, 178
barnyard joke book
clickable table of contents, designing 80, 81
outline, designing 79
pages, adding 81-83
sprite, adding to Backpack 83, 84
basic shapes
color, adding 230, 231
coordinates, plong 228, 229
procedures, dening 226-228
square, building on 220, 221
square, drawing 218, 219
user-dened shapes, drawing 221-226
[ 270 ]
bitmap eding tools
Brush 55
Ellipse 55
Erase 55
Fill with color 55
Line 55
Rectangle 55
Select 55
Select and duplicate 55
Text 55
bitmap images
or vector images, choosing 53
bitmap image size
changing 52
Boolean blocks
() < () 179
() = () 179
() > () 179
() and () 179
color () is touching ()? 179
() contains () 180
key () pressed? 180
mouse down ()? 179
not () 179
() or () 179
sensor ()? 180
touching ()? 179
touching color ()? 179
Boolean evaluaons
using 179, 180
Breakout game
history 135, 136
brick rows
drawing, with custom blocks 170-172
bricks
cloning 145-147
drawing 144, 145
brightness eect 72
broadcast () and wait block 98, 99
broadcast () block
adding 100
used, for coordinang ball play 176, 177
buon sensor 254
C
Cartesian coordinate system
used, for dening posion 91
change tempo by () block 97
circle
breaking out of 244, 245
clear graphical eects block 70
clickable table of contents
designing, in scratch book 80, 81
hiding 100, 101
navigang back to 103, 104
clone costume, detecng
paddle size, decreasing 180-183
clone costume, detecng(alternave soluons)
paddle size, decreasing 183, 184
cloned sprite
working with 147, 148
cloning blocks, Scratch
create clone of () 151
delete this clone 151
when I start as a clone 150
cloning feature
rapid re shoong 149, 150
used, for creang idencal sprites 144-149
cloud data log
viewing 188, 189
cloud variables
in, Scratch 2.0 188
used, for keeping global scoreboard 186-188
color
adding, to shapes 230-232
color eect 71
color palee
creang 234-237
color picker workaround
nding 232, 233
color shades
applying, set color shade to () block used 232
color values
liming, slider used 237-239
[ 271 ]
comments
adding, to script 67, 68
computaonal thinking 9
condional blocks, Scratch
if () 156
if () then 156
if () then else 156
repeat unl () 157
wait unl () 157
condional statements 157
coordinates
plong, to draw square 229
sprite, posioning by 89-93
sprites, locang with 91-93
used, for moving dog 89-91
costume, sprite
comparing 94, 95
creang 93
duplicang 93, 94
ipping 93, 94
switching 93, 94
create clone of () block 151
Creave Commons Aribuon-Share
Alike license
URL 30
custom block
ball play, coordinang 176, 177
inputs, seng 173-175
procedures, introducing 173
used, for adding more bricks 169, 170
used, for drawing rows of bricks 170-172
custom block opons
Add boolean input 175
Add label text 175
Add number input 174
Add string input 174
Run without screen refresh 175
custom say fortune block
creang 207, 208
custom sound eects
composing 95-99
drum sound eects, creang 96
D
delete this clone block 151
Digital Millennium Copyright Act (DMCA) 30
dog
moving, with x and y coordinates 89-91
dog scene
displaying 101, 102
Dog TOC buon 101
drum sound eects
creang 96
E
events
used, for triggering acon 33
events, used for triggering acon
walking moon of cat, animang 33-35
F
fade in eect
using 126
fade out eect
using 126
ll with color tool
used, for painng stage 57-59
sheye eect 71
Following Orange project
details, displaying 17-20
For all sprites opon 159
forever blocks
comparing, with repeat blocks 72
forever loops
about 37
block, clicking to run command 41
cat, rotang right-side up 39, 40
used, for controlling sprite 39
used, for keeping cat in moon
indenitely 37, 38
fortunes
counng, mod block used 203-206
imporng, to lists 195-197
fullscreen presentaon mode
project, displaying in 132
[ 272 ]
G
game over
checking for 166, 167
games
building 12
ghost eect
about 72
used, for making sprite fade in 74-76
uses 72
global scoreboard
keeping, cloud variables used 186-188
gradient
applying 59- 61
graphical eects
used, for transforming sprites 68-70
graphical transformaons
brightness eect 72
color eect 71
sheye eect 71
ghost eect 72
mosaic eect 71
pixelate eect 71
whirl eect 71
graph, resistance
interpreng 261, 262
revising 262, 263
H
Happy Birthday card
more sprites, adding 61, 62
Happy Birthday sprite
displaying 64, 65
gradient, applying 59, 60
painng, Paint editor used 50-52
horse
animang, say() block used 86, 87
synchronizing, say() block used 86, 87
horse sound
imporng 87
playing, play sound () block used 88, 89
Horse TOC buon 100
I
idencal sprites
creang, cloning feature used 144, 145
if () block 156
if () then block 156
if () then else block
about 156
using 208
image eding tools
bitmap eding tools 55
reviewing 55
vector eding tools 55, 56
vector mode, erasing 56
images
ipping, arrow sprites used 114-116
resizing 112, 113
working with 111
Import List dialog box 196
J
joke
building, say blocks used 85-89
building, sounds used 85-89
joke sequence, dog
integrang 98, 99
K
keyword scanner
creang 211
text scanning, to build word list 211-213
L
le arrow control, Pong project
adding 139, 140
LEGO WeDo 13
level clearance
detecng 184-186
light sensor 254
[ 273 ]
lists
creang, to store mulple values 192-194
exporng, from Scratch 197
fortunes, imporng to 195-197
imporng 195
item, interacng with 194, 195
list values
deleng 201
lives
implemenng 164
tracking, with lives variable 164, 165
lives, implemenng
game over, checking 165-167
lives variable, adding to track lives 164, 165
mulple programming soluons,
evaluang 167, 168
lives variable
adding, to track lives 164, 165
louder eect
using 126
loudness reporter block 257
M
M
spinning, in circle 73, 74
magic numbers
using 206
Make a Block buon 207
Make a List buon 192
Make a Variable buon 158
media, free
nding online 30
MIT App Inventor 8
mod block
used, for counng fortunes 203-206
mosaic eect 71
mouse locaon
used, for hiding arrows 127-129
mulple programming soluons
evaluang 167, 168
mulple values
storing, lists used 192-194
N
New backdrop opons 108
New sprite icons 90
next backdrop block 117
P
paddle size
decreasing, based on clone’s costume 180-183
pages
adding, to book 81-83
Paint editor
about 50
bitmap image size, changing 52
bitmap or vector images, choosing 53
ll with color tool, using to paint stage 57-59
image eding tools, reviewing 55, 56
used, for painng Happy Birthday sprite 50-52
vector image, drawing 53, 54
vector image size, changing 54
photos
imporng, as backdrops 107-114
PicoBoard
about 13
purchasing 248
sound sensor, used for creang talking
head 251-253
using 248
PicoBoard sensors
buon 254
light 254
resistance 254
slider 254
sound 254
PicoBoard support
adding, in Scratch 2.0 250, 251
enabling, in Scratch 1.4 249, 250
pinwheels
triangles, turning into 224-226
pixelate eect 71
pixilaon 53
play drum () for () beats block 96, 97
[ 274 ]
play note () for () beats block 97
play sound () block
about 122
used, for playing horse sound 88, 89
play sound unl done block 122
point in direcon () block
ball, ricocheng o bricks 154-156
sprite direcon, seng 153, 154
sprite starng posion, seng 153, 154
used, for changing sprite direcon 151-153
Pong, legacy version
remixing 138
Pong starter project
game play, customizing 139-143
imporng 136, 137
playing 136, 137
reporter blocks, using to set values 138
sprite, moving with mouse/arrows 138
presentaon mode
project, displaying in 131
procedures (custom blocks)
about 173
creang, for home 226-228
creang, for shapes 226-228
programming concepts
arrays (lists) 14
boolean logic 14
cloning 15
cloud data 14
concurrency 14
events 14
interface design 13
loops (iteraon) 14
procedures 14
random numbers 14
synchronizaon and coordinaon 14
variables 14
vector graphics 14
video 15
Q
queson
asking, to seeker sprite 197-199
validang, for grammacal errors 209, 210
queson number variable 205
queson, seeker
validang 200, 201
R
radar screen
animang 242-244
random fortune
selecng 202, 203
rapid re shoong
cloning, used 149, 150
Raspberry Pi
using 248
repeat blocks
comparing, with forever blocks 72
repeat unl () block 157
reporter blocks
about 110, 138
used, for seng values 138
resistance sensor 254
resistance, thermistor
circuit, compleng 257, 258
graph, interpreng 261, 262
graph, revising 262, 263
measurements, charng 258-260
recording, over me 255-257
rest for () beats block 96, 97
reverse eect
using 126
right arrow control, Pong project
adding 139, 140
Run without screen refresh opon 175
S
say (answer) for (2) secs block
used, for repeang queson 200
say() block
used, for animang horse 86, 87
used, for synchronizing horse 86, 87
say () for () block
used, for making horse talk 85, 86
scenes(chapters)
coordinang, by backdrop name 102
[ 275 ]
scoreboard block 186
score variable
adding 158, 159
Scratch
about 8, 9
computaonal thinking 9
URL 26
uses 9
Scratch 1.4
PicoBoard support, enabling in 249, 250
projects, sharing online 254
URLs 248
using 22, 248
Scratch 2.0
cloud variables 188
PicoBoard support, adding in 250, 251
project details, displaying 17-21
using 15, 16
using, oine 21, 22
Scratch 2.0 project details
built-in image editor 20, 21
scripts area 18, 19
sprites pane 18
stage area 18
Scratch account
creang 26, 27
Creave Commons licensing 30
free media, nding online 30
key features 28, 29
terms of use policy 30
ScratchEd
URL 8
Scratch project
animaons, making 10
art projects, creang 13
basics 35
cat, moving across stage 31, 32
creang 31
deleon, undoing 37
displaying, in fullscreen presentaon mode 132
displaying, in presentaon mode 131
events, using to trigger acons 33
games, building 12
Pong, legacy version 138
programming concepts 13-15
second sprite with script, adding 42-44
Sensing 13
sprites, adding to 42
stories, telling 11
tesng 210
walking moon, animang with cat 33-35
work, auto saving 36, 37
scripts
storing, Backpack used 85
script, sprite
adding, to project 42-44
comments, adding 67, 68
second brick
creang, with custom block 169, 170
seeker sprite
queson, asking 197-199
seekers queson
validang 200, 201
set color shade to () block
used, for applying color shades 232
set instrument to () block 97
set pen color to () block
working with 232, 233
set size to () block 52
set tempo to () bpm block 96, 97
set volume to () block 97
silence eect
using 126
slider
used, for liming color values 237-239
used, for drawing user-dened shapes 221-224
slider sensor 254
slideshow controls
adding, to display images 114-117
soer eect
using 126
sound blocks, for creang sound eects
and music
change tempo by () 97
play drum() for () beats 97
play note () for () beats 97
rest for () beats 97
[ 276 ]
set instrument to () 97
set tempo to () bpm 97
set volume to () 97
sound editor
sounds, recording in 119-122
sound eects
adding, to recordings 125, 126
fade in 126
fade out 126
louder 126
reverse 126
silence 126
soer 126
Sound Library window 118
sound, recorded
appending 124, 125
eding 123, 124
sound related blocks
play sound 122
play sound unl done 122
stop all sounds 122
sounds
adding, from Scratch’s library 118, 119
recording, in sound editor 119-122
sound sensor 254
sprite costume center, Pong project
adjusng 142, 143
sprite direcon
changing, point in direcon () block
used 151, 152
guring 153
seng 153, 154
sprites
about 94
adding, to address Happy Birthday card 61, 62
adding, to Backpack feature 83, 84
adding, to project 41-44
controlling, forever loops used 39
hiding, when ag clicked block used 62-64
locang, with x and y coordinates 91-93
posioning, by its coordinates 89-92
renaming 66
storing, Backpack used 84
transforming, graphical eects used 68-70
variables, seng for 159, 160
sprite starng posion
seng 153, 154
sprites starng values
inializing 62-64
square
building on 220, 221
drawing 218, 219
drawing, coordinates ploed 229, 230
stage
painng, ll with color tool used 57-59
stop all sounds block 122
stop-moon animaons
URL 10
stored quesons
using 200
stories
telling 11
string art
about 242
paerns, creang 244, 245
radar screen, animang 242-244
supported sound formats
playing 89
switch backdrop to () and wait block 116
switch backdrop to () block 115, 116
switch costume to (face-le) block 94
switch to () block 94
T
talking head
creang, PicoBoard sound sensor used 251-253
thermistor
about 254
resistance, recording over me 255-257
third-party graphics editors
Adobe Photoshop 111
GIMP 111
MS Paint 111
Pixelmator 111
ming, animaons
controlling, broadcast () block used 76
controlling, wait () secs block used 76
triangles
turning, into pinwheels 224-226
turn () degrees block 224, 226
[ 277 ]
W
wait () secs block 69
wait unl () block
about 157
webcam images
animang, by sound detecon 251-253
when backdrop switches to () block 117
when ag clicked block
used, for hiding all sprites 62-64
when I receive (fortune) block 202
when I start as a clone block
about 150
used, for breaking bricks 148
whirl eect 71
word list
building, text scanned for 211-213
X
x posion block 137
U
Undelete opon
used, for undoing deleon 37
user-dened shapes
drawing, sliders used 221-224
user instrucons
providing 130, 131
V
vector eding tools
Color a shape 56
Duplicate 56
Ellipse 56
Line 56
Pencil 55
Rectangle 56
Reshape 55
Select 55
vector images
drawing 53, 54
or bitmap images, choosing 53
size, changing 54
video sensing feature
about 46
video-sensing project
reviewing 44, 45
Thank you for buying
Scratch 2.0 Beginner's Guide Second Edion
About Packt Publishing
Packt, pronounced 'packed', published its rst book "Mastering phpMyAdmin for Eecve MySQL
Management" in April 2004 and subsequently connued to specialize in publishing highly focused
books on specic technologies and soluons.
Our books and publicaons share the experiences of your fellow IT professionals in adapng and
customizing today's systems, applicaons, and frameworks. Our soluon-based books give you the
knowledge and power to customize the soware and technologies you're using to get the job done.
Packt books are more specic and less general than the IT books you have seen in the past. Our unique
business model allows us to bring you more focused informaon, giving you more of what you need to
know, and less of what you don't.
Packt is a modern, yet unique publishing company, which focuses on producing quality, cung-edge
books for communies of developers, administrators, and newbies alike. For more informaon, please
visit our website: www.PacktPub.com.
Wring for Packt
We welcome all inquiries from people who are interested in authoring. Book proposals should be sent
to author@packtpub.com. If your book idea is sll at an early stage and you would like to discuss
it rst before wring a formal book proposal, contact us; one of our commissioning editors will get in
touch with you.
We're not just looking for published authors; if you have strong technical skills but no wring
experience, our experienced editors can help you develop a wring career, or simply get some
addional reward for your experse.
Scratch Cookbook
ISBN: 978-1-84951-842-0 Paperback:262 pages
A quick and easy guide for building Scratch programs
intended for further learning through projects,
such as interacve animaons and games
1. Get started using Scratch, or take your programs
to a new level using simple, easy-to-read recipes.
2. Learn techniques for animang stories.
3. Create fun and engaging games.
Scratch 2.0 Game Development Hotshot
ISBN: 978-1-84969-756-9 Paperback: 330 pages
10 engaging projects that will teach you how
to build excing games with the easy-to-use
Scratch 2.0 environment
1. Discover how to make the most of the
new Scratch 2.0 interface.
2. Understand how video games work
under the hood.
3. Make your projects come to life, using
praccal programming principles.
4. Learn how to plan and build your own
interacve projects.
Please check www.PacktPub.com for information on our titles
GameSalad Beginner's Guide
ISBN: 978-1-84969-220-5 Paperback:308 pages
A fun, quick, step-by-step guide to creang games
with levels, physics, sound, and numerous enemies
using GameSalad
1. Learn to build three games; Ball Drop, Space
Defender, and Metal Mech with GameSalad.
2. Complete these games with sound eects,
use of physics, gravity, and collisions.
3. Learn ps and tricks to make a game popular
straight from the author's own experience.
Unity Android Game Development by
Example Beginner's Guide
ISBN: 978-1-84969-201-4 Paperback: 320 pages
Learn how to create excing games using Unity 3D for
Android with the help of hands-on examples
1. Enter the increasingly popular mobile market
and create games using Unity 3D and Android.
2. Learn opmizaon techniques for ecient
mobile games.
3. Clear, step-by-step instrucons for creang
a complete mobile game experience.
Please check www.PacktPub.com for information on our titles

Navigation menu