Learn CS Concepts With Snap! - Create Exciting Games and Interactive Animation in Snap! and Learn Computer Science Principles (Learning Computer Programming and CS Principles)
Learn CS Concepts With Snap! - Create Exciting Games and Interactive Animation in Snap! and Learn Computer Science Principles (Learning Computer Programming and CS Principles)
with
Snap!
Create exciting games and animation in Snap! and learn Computer Science
principles
2nd Edition
Abhay B. Joshi
Book series on "Learning computer programming and CS principles"
To Sam Mahableshwerwalla, who inspired me like no one else
Background
“Snap!” is a programming language that is based on MIT’s Scratch. You can run it in any web browser by using the link
http://snap.berkeley.edu/run. In the subsequent discussion I am going to call it “Snap” (instead of “Snap!”). This book is an adaptation
for Snap of my earlier book “Learn CS Concepts with Scratch”. It is an introductory, self-study tutorial in which you will learn all these
concepts through a series of exciting projects and programming activities.
The idea of using computer programming as a medium for learning is rapidly gaining acceptance. The benefits of learning
programming and computer science concepts well before college – even in elementary grades – are well-understood.
Here is a list of some of the amazing things that happen when students engage in computer programming:
They become active and creative learners, because they explore ideas through a hands-on activity with an infinitely
powerful tool.
They learn to think about and analyze their own thinking, because that is the only way to program computers.
They learn to solve complex problems by breaking them into smaller sub-problems.
They learn a new way of thinking (called "computational" thinking).
In the world of programming, answers are not simply "right" or "wrong"; this prepares a student's mindset for real-life
problems.
Students’ learning processes are transformed from acquiring facts to thinking creatively and analytically.
Audience
A lot of children these days begin their CS journey with block-based languages, such as Scratch. Snap can be considered as the next
step in that journey. Snap is a powerful language and offers access to lots of advanced ideas of Computer Science some of which are
appropriate even for a college-level programming course. We have not included some of these advanced ideas in this book since they
certainly deserve a separate book for a serious treatment.
In short, this book is for middle- or high-school students who are keen to learn CS concepts and who might or might
not have prior programming background.
Acknowledgements
I wish to thank Tanuja Joshi for reviewing the material of this book diligently and tirelessly and for providing me with valuable
suggestions. I wish to thank Ravindra Pande for creating a truly beautiful cover for the book.
I wish to thank TEALS (https://www.tealsk12.org) – a nonprofit organization dedicated to the cause of teaching computer science to all
high school students – for allowing me to teach Snap using their remote classroom infrastructure.
Finally, this book would not have been possible without the constant encouragement of my friends and family.
I do hope that you will find this book useful and enjoyable.
Abhay B. Joshi ([email protected])
Seattle, USA
5 October 2018
In this book, in addition to learning a lot of Computer Science concepts, you will do a series of interesting projects and programming
activities. You don't need to have any prior programming experience or expertise for this course. This is could be your first encounter
with computer programming.
You might ask: Why should I learn CS concepts and Snap? Why should I bother learning computer programming at all?
The fact is every one of us today works with computers. Your smartphone is a computer which you use for communication and games
and so many other things. When you go online to do shopping or to find information you are using computers. When you go to a
grocery store the person at the checkout counter is using a computer to scan your items. Your car most likely has a computer to control
certain things like the inside temperature.
But, in all these cases we are working with the computer as “consumers” or “users”. Someone else – people called “programmers” – at
companies such as Microsoft or Google or Cisco created all those services that we use.
I think it is much more exciting to engage with computers as creators, as designers. Can we not ask the computer to do things for us,
things which are not already made by someone else? Programming is the new kind of magic that will allow you to be a modern-day
wizard. And that is what is meant by “Creative Computing” – designing and creating things using programming.
By the way, there is another great reason to learn computer programming. Practically all future careers will use computers, and so, if
you are armed with the power of programming, you will have an edge in your career!
Ok, so, what tool should we use to do creative computing? For this course the tool we are going to use is a language called Snap. Snap
is an exciting environment in which we can design all kinds of cool stuff – animation, games, interactive art, science experiments, and
so on. Snap is freely available to anyone, and it was developed at UC Berkeley.
When you start Snap this is how it looks. It’s a bit like a movie maker’s studio. You are the movie director and your characters do
things according to your instructions.
The white area is called the “stage”. That’s where all the action happens. Whatever you tell your characters to do they do it on that
stage.
Your characters are called “sprites”. They are all lined up in the area below the stage.
Now, as you might know, in a movie or a play each character follows a script. Similarly in Snap every sprite has a script associated with
it. You, as the programmer, have to create that script. The “script area” in the above figure is where the sprite’s script appears.
How do you build a script? You build a script using the command blocks listed at the left. There are various types of command blocks:
motion, control, sound, etc. You drag and drop these blocks into the script area and connect them together (like jigsaw pieces) to build a
script.
You can save your Snap project in two ways: First, you can save it in your cloud account provided by Snap (see File->Save or File-
>Save as). Or you can save it locally (on your computer) by using the "Export project" feature in the File menu. This feature exports
your project to XML format.
You can then change the appearance of your sprite, by loading a new costume. There are multiple ways of loading a new costume. First,
you can choose from Snap's own collection of hundreds of readymade costumes. There are animals, people, fantasy characters, cars,
planes, and so on. To add a costume to your sprite from this Snap library, first click the costumes tab as shown below.
And then click the File menu to load the Costumes library as shown below:
Secondly, you can paint your own costume by using the built-in paint editor of Snap. Click on the paint icon to start the Paint editor and
draw the new costume. If you have used Microsoft Paint or some other similar drawing software, you will find this Snap Paint Editor
very easy to use.
Tip: You can also modify an existing costume using this paint editor.
Finally, you can import an image from your computer and use it as a costume. Use the "Import" menu item of Snap, or simply drag and
drop the image file on to the costumes tab.
Stage or background:
Similar to the costume library for sprites, Snap comes with a lot of interesting backgrounds which you can load for your stage. If you
want to use one of those, click on the File menu and then on the “backgrounds” menu item.
If you want to draw your own background, click on the little paint icon. You will once again see the Paint editor interface.
Tip: You can also modify an existing backdrop using this paint editor.
You can also import an image from your computer and use it as a background. Use the "Import" menu item of Snap, or simply drag and
drop the image file on to the backgrounds tab of your Snap project.
There are several categories (or palettes) of commands, such as “Motion”, “Looks”, “Sound”, and so on. We will learn about these
various command blocks throughout this book.
Every sprite has its own program(s) called script(s). You can create a script by snapping together command blocks.
If you want to simply check out what a particular command block does before using it in a script, you can just click on that command
block (without dragging it to the script area). For example, we have this command block . If you click on it the sprite
will turn by 15 degrees.
Once you build a script, you can click on it to run it. For example, this script below asks the sprite to move, take a turn, and move again.
When a script is running, a faint glow appears around it. That tells us that that script is running. For example, in the script below the
sprite turns around itself forever. When we click on it the white glow appears around it.
To stop a running script, click on it again. The glow disappears and the script stops running.
Review questions:
1. Snap allows you to use your own image/picture when you draw a new sprite. True or False?
2. What is “Snap”?
a. It is a computer programming language
b. It is a software (like Photoshop) in which you can create graphics and animation
c. It is a type of computer system like Windows or Linux
d. It is a collection of readymade animations and video games
Programming practice:
Experiment with the following command blocks and create your own scripts.
Chapter 1.2: Sequence and Sounds
Build a script as shown below and play with it. Understand the sequence of operations.
Do you have some understanding now of these different command blocks and how scripts are built in Snap? In this exercise, we learnt
the Sequence concept as summarized below.
Sequence:
Snap programs tell the computer precisely what to do, step-by-step. To create a program in Snap, you need to think about the order of
steps. Unlike humans, computer programs do not change the order of the commands given to it.
For example, let’s say you were given a “To do” list as follows:
You may not follow this task-list exactly in the given order. You might go to the grocery shop first, or even skip getting the mail.
Computers do not have this freedom. They would, if given the above list, follow it exactly in the given order, one after the other,
making sure every item was completed in a satisfactory manner before going to the next. This concept is called “Sequence” in computer
science.
Here is another example of a Snap script that demonstrates the concept of sequence. The color will change at the very end of the
program. The sprite will jump to the center of screen first. The order is exactly as given.
Playing sounds:
One of the exciting features of Snap is the ability to play sounds.
As shown above, every sprite has a tab called “Sounds”. Under this tab, you need to collect the sounds that you would like to play in
your program. You can import an existing sound from the Snap library (by clicking “File” and then “Sounds”). You can also import
your own sound file in MP3 format by dragging and dropping it in this area. Finally, the red button allows you to record your own
sounds if your computer is equipped with a microphone.
Once you create a list of sounds for a sprite, you can play these sounds using the following sound commands. We have imported a
sound called "Cat".
Review questions:
1. How many times will you hear "Cat" sound when you run the script below?
2. How many times will you hear "Cat" sound when you run the script below?
3. We’ve created the following program for our sprite. What will it do when we click this script?
Programming practice:
1. Write a script which when clicked does the following. Each action must be visible separately (so you may have to insert the
“wait” command).
The main problem you will notice is that there is no way to run both these scripts at the same time. You can only click one script at a
time.
Green Flag:
This is where the following green flag “hat” block comes in handy.
Just attach this block on top of each of the above scripts as shown below:
Now, if you click the Green flag at the upper right corner of the Snap interface (as shown below), you will see that both these scripts
start at the same time.
But, things are still not quite right. The two characters speak at the same time, without pausing for each other.
That is a problem with your scripts, not with Snap. The pauses must be built into the scripts, just like in real life we pause when
conversing with someone. See the addition of “wait” commands in the modified scripts below.
If you click on the Green flag now, you will observe a proper conversation between the two characters.
Next, we will learn the concept of looping.
In order to use looping effectively, it is essential to first get the basic sequence working properly.
For example, let’s say we want a sprite to jump up and down repeatedly. We should first get the basic command sequence, i.e. one
jump, working properly as shown below:
Now, making 4 jumps is a simple matter of putting this sequence inside a REPEAT block:
The sprite will jump to the right by 300 steps. It seems as if the jump was instantaneous. Indeed, most Snap commands take an
extremely short time to run. Looping can, in fact, reveal that these commands are not really instantaneous. Run the following modified
script:
The sprite goes the same distance (10x30 = 300) but a bit more smoothly. That’s because the extremely short but finite time taken by
each “move” adds up 10 times. (Note that the time taken by “move” is the same irrespective of its input, i.e. the # of steps.)
Now, try the following script:
Once again, the sprite goes the same distance (30x10 = 300) but it goes smoothly at a slower speed.
So, there you have it! You can use REPEAT to create smooth motion, and the speed of the motion depends on the size of each step.
The same principle applies to rotation (spinning). The following two scripts spin the sprite but at different speeds.
What if you wanted your sprite to just walk horizontally (east-west) forever? See the following script:
Note the “if on edge, bounce” command. It ensures that the sprite doesn’t go past the screen edges. See the screen-shot below to
understand how to control the sprite’s orientation after bouncing.
Rotation style:
The yellow box highlights 3 buttons that control how the sprite will behave when it bounces on edges (or turns). Click the one that
meets your needs.
The first button indicates free rotation, and it will cause the sprite to become upside-down after bouncing off an edge.
The second button indicates left-right orientation, and it will cause the sprite to only face either left or right after bouncing off an edge.
The third button indicates no rotation, and it will cause the sprite to always face right (or East) no matter where it bounces or how much
it turns.
The "wait" command helps to make the animation a bit more realistic.
Multiple backdrops:
The Snap stage can have multiple backdrops. There are a number of ways to create a new backdrop:
- Choose from the Snap library
- Paint using the paint editor
- Upload an image from your computer
Once you have lined up multiple backdrops for the stage, the stage can change the backdrop any time using the same costume
commands (listed under the “Looks” tab) as we have seen above.
Review questions:
1. Let’s say you have painted a new penguin sprite. When you run the command “point in direction 90” on the penguin sprite,
the penguin looks left instead of right. What is the problem?
a. Direction 90 means the left direction
b. You painted the original image of the penguin to look left
c. There is a bug in the script
d. The center of the sprite is not correct
a. 5 steps
b. 20 steps
c. 25 steps
d. 100 steps
3. To make your animation look realistic you should have as many costumes as possible. True or False?
Programming practice:
1. From the Snap library load a sprite that has flying costumes (e.g. bat or parrot). Write a script to make the sprite change
costume each time the space bar is pressed. Add code so that the sprite will face to the left, move a few steps and also change
costume when the left arrow key is pressed. So, it should look as if the sprite is flying west each time you press left arrow
key.
2. You can make the “Avery” sprite walk by using the “next costume” command as shown below. Do the same using the
“switch to costume” command.
3. Use existing costumes (in the Snap library) to create animation, such as, a walking boy or a fire-breathing dragon.
XY Geometry:
We use the screen in Snap as a geometric plane. Every point on the screen has X and Y coordinates. You might have learnt about this in
your school mathematics.
Every point on the screen has two coordinates: x and y. Imagine two number lines laid out on the screen: one horizontally and the other
vertically, both intersecting at 0. The horizontal line is called the X axis, and the vertical line is called the Y axis. The distance of a point
from the Y axis is called the X coordinate, and the distance from the X axis is called the Y coordinate.
For example, for the blue point here its distance from the Y axis is 80, so its X coordinate is 80. And its distance from the X axis is 120,
so its Y coordinate is 120.
For the dark red point its distance from the Y axis is -200, so its X value is -200. And its distance from the X axis is 0, so its Y
coordinate is 0.
Every sprite in Snap has a center point which you can view (and change) in the Paint editor. The X Y coordinates of this center point
are assumed to be the X Y coordinates of the sprite. When the sprite moves these values also change automatically.
How do you find out the X and Y values of a particular location on the screen? You can use the following reporter blocks for this
purpose. Look under the "Motion" category just below "if on edge bounce". (We will discuss reporters in greater detail later.)
Turn these reporters on (i.e. check the little boxes next to them), and they will report the current X and Y values of your sprite. If you
move the sprite to a different location, the reporters will indicate the new X and Y values.
Now that we understand what X Y coordinates are let us look at a few Snap commands that make use of these coordinates.
The SET commands are interesting because they move the sprite to a specific point no matter where the sprite is right now; whereas, the
CHANGE command depends on the sprite’s current location.
For example, if you say “CHANGE X by 10” the sprite will move to its right by 10 pixels. If you run “CHANGE X by 10” once more,
the sprite will again move to its right by 10 pixels.
But, if you say “SET X to 100”, the sprite will jump to where X is 100. And if you run “SET X to 100” once more, nothing will happen
because the sprite is already at X = 100.
There is one important thing to note about all these commands shown here. The orientation, or, the direction in which the sprite is
facing, does not change when you use any of these commands.
Orientation of a sprite is basically the direction in which it is facing. It is shown in terms of the angle made with the North direction. So
if a sprite is facing North its direction value is 0.
Initially all sprites are facing east, which means their direction is 90. You can change a sprite’s orientation using one of the commands
shown below.
Nested looping:
Nesting means having one loop inside another. See the example below:
The following script makes the sprite jump up and down. Repeat makes the jump appear smooth.
What if we wanted the sprite to jump 5 times?
The two inside repeat loops together make the sprite jump once, and the outside loop makes the jump happen 5 times. Thus, nesting of
loops can open up interesting opportunities.
Review questions:
1. A sprite has a script as shown below:
Programming practice:
1. Write a "commotion" program in which various animals are made to perform different actions, such as:
constantly jumping up and down
spinning around itself
roaming around the screen etc.
Chapter 1.5: Animation Mini-project
This is a mini-project assignment for you, in which you will apply all the concepts and commands learnt so far. The specification of this
project is as follows:
Project Requirements:
Green flag should start the animation.
Only 1 active sprite.
Use as many commands learnt so far as possible (movement, rotation, etc.).
Use sounds and costumes.
Chapter 1.6: More Motion and Broadcasting
Absolute motion:
Absolute motion refers to motion whose result does not depend on your current position and direction. For example, “Going to
Washington DC” is absolute motion because you will end up in Washington DC no matter where you currently are.
The following Snap commands (among others) describe absolute motion because the resulting position or direction does not depend on
the sprite’s previous position or direction.
Relative motion:
In contrast to absolute motion, relative motion depends on your current position and direction. For example, “Turn right” is relative
motion because the resulting direction depends on your current direction.
The following Snap commands (among others) describe relative motion because the resulting position or direction does depend on the
sprite’s previous position or direction.
To understand synchronization, let us look at an example, as shown above. Here, we have two sprites – Alonzo (he calls himself Gobo)
and Space Ranger – talking with each other. If you run the program what will happen? They both will talk at the same time! There is no
proper sequence or coordination. That’s not what you expect, right? To make it a proper dialog, Alonzo should say “Hi” first, then, the
space ranger should reply by saying “Hello”, and so on.
So we say that there is no synchronization in this program. Do you now see the meaning of synchronization? We have already seen one
way to fix this problem – by inserting "wait" statements. Let's now learn about a much more elegant technique called "Broadcasting".
You might have heard the word “Broadcasting” in the context of radio and TV. When you tune into a radio station, you are actually
listening to something that was broadcast from a radio station.
Broadcasting basically means sending a message to anyone who cares to listen. So, when someone gives a public speech, he/she is
giving a broadcast speech.
In Snap, broadcasting has a similar meaning. When you use the BROADCAST command (under the “Control” tab), your sprite sends a
message that goes to every sprite in your program and even to the stage.
But, just like not everyone is interested in listening to the radio, not every sprite may be interested in hearing the message. So, if a sprite
is interested in receiving that message it uses the command WHEN I RECEIVE. So, in effect, broadcasting can also be used to pass
messages one-to-one, i.e. between two entities.
So here are all the commands related to broadcasting:
WHEN I RECEIVE is an event and works just like other hat blocks. When the specified message is received, the script attached
underneath it runs.
Every time the exact same message is received the script runs again.
There are two flavors of the BROADCAST command as shown above:
In the first flavor, the sending sprite sends the broadcast message and immediately goes to the next command in the script, if there is
any.
But, in the second flavor, the sending sprite sends the broadcast message and waits – until all listening sprites have received the
message and completely run each of their “WHEN I RECEIVE” scripts.
Example:
To understand the difference between these two broadcasts, run the following experiment:
Take any two sprites sprite1 and sprite2. Create the following script for sprite1:
And now run the program by clicking on Green Flag. Observe the conversation. You will notice that it doesn’t look right. Now, replace
the “broadcast” command in sprite1’s script by “broadcast and wait”. Run the program again by clicking the Green Flag.
Review questions:
1. The Snap command “point in direction” causes relative motion. True or False?
2. If you run the command, the new position of the sprite on the screen depends on the current position.
a) True
b) False
3. We have two sprites sprite1 and sprite2. They have scripts as shown below:
B1:
B2:
a) Sprite1 should use command B1
b) Sprite1 should use command B2
c) Sprite1 should first use B1 and then B2
d) Sprite1 should first use B2 and then B1
5. Let’s say we have two sprites Kitty and Abby. Their respective scripts are shown below.
Programming practice:
1. Write a “circus” program in which the ringmaster calls animals/actors one by one and each performs some act.
2. Write a “roll call” program in which the teacher calls students one by one and each says “present” if present. Show one or
two as being absent – someone else will inform the teacher.
The property shows messages sent by a “send” command as a 2-D list (we will learn about “lists” in Unit 8).
Chapter 1.7: Project Animation
This is a project assignment for you, in which you will apply all the concepts and commands learnt so far. The specification of this
project is as follows:
Project Requirements:
Green flag should start the animation.
At least 2 sprites.
Draw at least one background.
Use as many commands learnt so far as possible (movement, rotation, broadcasting, etc.).
Use sounds and costumes.
Sprite names must be as per the story, and not sprite1, sprite2, etc.
As each line of the story appears on the screen (anywhere) animation of that line should be visible.
Story should be slow and easy to understand.
It should take at least 10 seconds but not more than a minute.
Events:
Events are outside happenings that create some sort of a signal. For example, the “ringing of a phone” is an event that tells us that
someone is calling. “Traffic light turning red” is an event that signals that cars need to stop. Real world is full of events. Following are
some of the commonly used events in Snap. You will find these blocks under the "Control" category.
Every sprite in your program will have scripts to respond to the events that that sprite is interested in. For example, the paddle sprite in a
game might respond to the “when up arrow key pressed” event by moving up a little as shown below:
We already understand several of these events such as "when green flag clicked" and "when key pressed". We will learn about rest of
the event blocks later in this book.
Reset script:
Every sprite has a set of attributes (properties). We can call this set its “state”.
- Position on the screen (X, Y)
- Orientation (Angle with North)
- Color (default value is 0)
- Size (default is 100%)
- Visibility (visible or invisible)
- Costume #
- Graphic effects
After we run scripts, one or more of these properties change. For example, see this script.
After running it, the sprite’s location, direction, color, size, and visibility will all have changed. We will need to reset these back to the
original values before we run this program again. This is done by the following script:
This is called a “reset script”. By simply pressing the “r” key (or whichever key you use in your script) you can set the sprite properties
to their original values.
Now if you click on the Green flag, the sprite will continue moving non-stop and say hello every 3 seconds.
Concurrency basically means doing multiple actions at the same time. People like you and me are doing multiple things at the same
time, all the time! For example, when we take a walk, we listen to music or talk on the phone, watch for road signs, react to a buzzing
fly, and so on. All these actions happen concurrently.
Here is another Snap example:
We have three scripts for the same sprite. The first script makes the sprite spin around itself. The second script changes its size
continuously. And the third script changes its color continuously.
Because all three scripts start with the same signal, which is “Green Flag clicked”, the sprite will appear as if it is performing these
actions at the same time, that is, concurrently.
Review questions:
1. A sprite has a script as shown below.
If you make a duplicate of this script and click on the green flag again, what will happen?
a. The sprite will run twice as fast since both scripts run at the same time.
b. Nothing will happen because there is an error.
c. Only one script will run because the two scripts are identical
d. The sprite will not run in a straight line.
3. See the following two scripts written for the Dog sprite:
Programming practice:
1. Make a bird sprite fly around the screen while changing size and color at the same time. Also have it make some sound every
5 seconds.
2. Make a ball roll from left to right of the screen. The ball appears at the left edge, rolls to the right, disappears across the right
edge, and reappears again at the left edge.
Graphic Effects:
Snap provides a bunch of interesting graphic effects that you can use to make your animation very exciting. They are available under
the “Looks” tab.
Color effect:
At the top of the list is color. Changing colors is of course very exciting, isn’t it! The SET command simply sets the color to a specific
value. There are about 200 different values you can use – from 0 to 200. The “CHANGE” command adds a number to your current
color value. Why don’t you experiment with these values and discover which value gives you which color?
This example script will show you 10 different colors in the range 0 to 200.
Ghost effect: this effect has to do with disappearing slowly. Every time you increase the ghost value, the sprite will
become fainter and fainter. At the value of 100 it will disappear completely. If you want to make the sprite appear
again, reduce value gradually back to 0.
Fisheye Effect: This effect is like pumping air into a balloon. Except in this case you pump air into your sprite. Just
like the balloon bulges slowly as the air is pumped into it, your Sprite will bulge as you increase the FISHEYE value.
There is no limit to how much air you can pump into your sprite. To deflate, that is, to take the air out again, decrease
the FISHEYE value gradually.
Whirl Effect: This effect is about stirring your sprite with a stirrer as if it were a liquid. Or, think of your washing
machine in which you wash clothes. The machine twists and turns the clothes, right? Similarly, the WHIRL effect
twists your sprite in either direction – right or left – depending on whether you increase the WHIRL value or decrease
it.
Pixelate Effect: This effect allows you to zoom into your sprite making it grainy. You might have seen this type of
effect in some of the older video games. To bring it back to normal, reduce the PIXELATE value.
You might find a few more (or less) effects depending on your Snap version. Feel free to experiment with them.
How to clear effects:
For any of these graphical effects that we saw so far, there are 2 simple ways to cancel the effect, and bring your sprite back to its
normal appearance. The following command cancels all graphical effects. If you want to just cancel one of the effects, use the SET
command and set the value to 0.
Review questions:
4. Your sprite has undergone a lot of color change in your animation. So, in your reset script you would like to restore the sprite
back to its original color. Which command will you use?
i.
ii.
iii.
a) i only
b) ii only
c) iii only
d) i or iii
e) ii or iii
Programming practice:
3. Insert graphic effects in your earlier animation program or in a new animation.
Chapter 2.2: Keyboard Interaction and Conditionals
User interaction using keyboard:
One of the most interesting features of Snap is that it allows the user to interact with programs. Your programs need not be just
animations that one has to watch, but, they can be interactive.
Snap provides the event block in which you can pick any key. Its purpose is similar to the block
. If you write a script under this event, it will run every time the user presses the specified key.
See these examples. In game programs arrow keys are typically used to move sprites. Here, the UP ARROW key runs a script in which
the sprite moves 10 steps upwards.
In the second example, the h key makes the sprite visible for a short time – this sprite could possibly be a “HELP” screen which pops up
for a short time and then goes away.
Sensing touch:
In Snap, you can check if things are touching each other, and use that information in the conditional statements (such as IF, Wait until,
Repeat until, etc.) which we will learn shortly. Here are the sensing conditions:
TOUCHING is a condition which basically is the question “Am I touching so and so?” There is another diamond block called
TOUCHING COLOR which is the question “Am I touching this color?” The comparison operators compare numbers.
In real life, we use the TRUE-FALSE questions to take some action. For example, if the answer to the question “Is it raining?” is TRUE
(or YES), we might decide to take the umbrella to school.
Similarly, in Snap we have a command called IF that we can use if a condition is TRUE. In the example shown below, if the sprite is
TOUCHING another sprite called “fire”, the sprite will say “Help! Help!” and then back off by 100 steps.
We want to move the sprite upward but not take it beyond the top edge. The condition in the above command is: “Is the sprite touching
the edge?” If the answer is YES, the sprite doesn’t move. If the answer is NO, the sprite moves up 5 steps.
So, the IF-Else command offers a fork in the process of decision-making.
Review questions:
1. Which of the following statements is true for this script?
Programming practice:
1. Design a program in which a ball bounces up and down and is deflected by a paddle. The user should be able to move the
paddle horizontally using the arrow keys.
2. Design a program in which there are several separate color circles (red, blue, green, etc.) on the screen. When the green flag
is clicked an animal sprite starts following the mouse pointer and whenever it touches a circle its color becomes the same as
the circle’s. (Tips: (1) To make the animal sprite follow the pointer, consider using the “point towards” and “move”
commands in a forever loop. (2) Consider using costumes for the animal.)
Stopping scripts:
The STOP commands (under the “Control” tab) allow us to stop Snap scripts in various ways.
The “STOP all” command stops all active scripts in your Snap project. For example, the script below checks if the allotted time has
been used up, and if so, it stops the game. (Note: “time” is called a variable; we will learn about variables later in this book.)
Finally, the command “STOP other scripts in sprite” is useful when you want to only stop scripts of the current sprite. If you want to
stop all scripts of the current sprite you would need to do as shown in the following hypothetical script:
The following flavor of the STOP command could be used when you wish to stop everything else but continue doing some work –
maybe it is some cleanup, or celebration of winning a game!
Finally, the following STOP command is used for custom blocks about which we will learn later in this book.
With the help of all the concepts learnt so far, we are now ready to take up a game project. Let’s go for it!
Chapter 2.3: Project Helicopter
Description:
Using arrow keys fly a helicopter. Show the effect of gravity, i.e. if you don't do anything, the helicopter should automatically move
down slowly. So, "Down" arrow key is not needed. The helicopter should be able to land on a helipad. Show moving clouds (just for
fun). Have some indication, such as blinking lights or spinning fans, to indicate that the Helicopter engine is running.
Concepts used:
User interaction (keyboard)
Costumes
IF-ELSE and sensing touch
Sprites:
1. Helicopter
2. Landing pad (can also be part of the stage)
3. Clouds
User Interaction:
Green flag resets everything and starts the helicopter engine.
SPACE BAR adds effect of gravity.
Arrow keys (except “down”) control the helicopter.
Additional requirements:
The helicopter should land only if its landing gear touches the helipad.
The next block includes a number of pointer events (as shown above):
1. Clicked – invokes a script when you click on that particular sprite. Imagine a button sprite, for example, that you could
activate through such a script.
In the script shown below, if you click on the dog sprite, the dog makes a “woof” sound and says “Woof! Woof!”.
2. Pressed – invokes a script as soon as you press the mouse button while it is over the sprite. It doesn’t matter if you
release the button sometime later; this script runs immediately after you have pressed the button.
3. Dropped – invokes a script after you drag the sprite to another place and drop it (i.e. after you release the mouse
button).
4. Mouse-entered – invokes a script after the mouse pointer enters the sprite area (this happens irrespective of whether the
mouse button is pressed or not).
5. Mouse-departed – invokes a script after the mouse pointer leaves the sprite area (this happens irrespective of whether
the mouse button is pressed or not).
All these events, except “dropped”, work for the stage also.
Another interesting thing you can do in Snap is that you can make a sprite follow the mouse pointer. The script shown below explains
how this can be done. You make the sprite point towards the pointer and then take a small step.
In fact, the same idea can also be used to make one sprite follow another.
When clicked, the button sprite sends a broadcast message to let everyone know that it was clicked. The actual drawing would be drawn
by some other sprite when it receives this message. (In case you are wondering, you can draw all kinds of designs in Snap – we will
learn all about it later in “Pen art”.)
Review questions:
1. We have the following script written for the Alonzo sprite.
What will happen when we click on the Green flag?
a) Alonzo will follow the mouse pointer all the time.
b) Alonzo will point away from the mouse pointer all the time.
c) Alonzo will point towards the mouse pointer all the time.
d) Alonzo will move away from the mouse pointer all the time.
Programming practice:
1. Write a program in which the sprite jumps to the pointer whenever you click anywhere on the stage.
2. Write a program in which the sprite doesn’t allow the mouse pointer to touch it. It runs away as soon as you move the pointer
to it. The sprite stays inside the visible screen.
3. Write a program in which a wizard performs various types of magic for his audience. Provide a button for each magic, such
that when you click on it, that particular magic is performed. For example, a button called “Frog” will turn a boy into a frog
temporarily and then back to human form.
4. Create a solar system teaching aid in which an information bubble pops up when you take your pointer on top of any of the
planets. For instance when you move the pointer over Jupiter, the bubble might say "Jupiter: the largest planet with 20+
moons." (Note: No clicking should be required.)
Chapter 3.2: Variables
Variables – numbers:
As you might know already, computers have a temporary memory called RAM. They use this memory to store information and do their
work. For example, when you use a calculator program to make calculations, the computer stores the numbers you type in its memory.
This memory is called “temporary memory” because the information goes away if you shut down the computer.
How does your program make use of this memory? That’s where variables come in the picture. A variable is a location in this
temporary memory, and each variable has a name. In Snap, you can create a variable by clicking on the button “Make a variable” under
the “Variables” tab. Once you create a variable it becomes available to your program to store information.
When you no longer need a variable, you can delete it by clicking on “delete a variable”.
The word “variable” means something that can vary or change, and indeed variables can contain any value. Snap provides commands
that you can use in your scripts to store information in variables and then change it later.
The SET command stores a value in a variable. The value can be any number – negative or positive, whole, or decimal.
Later, you can change the value by using the command CHANGE. The CHANGE command adds the given number to the variable.
Let’s look at an example of how variables can be used. Here we have a script for the game of maze. We have a variable called “Bonus
points”. In this script, this variable is incremented by 10 when a prize sprite touches the pacman.
Important: Always initialize number variables to some value (such as 0) at the beginning of the program.
Variables as sliders:
Let’s use an example to understand this concept. Let’s say we have defined a new variable called “speed”. After creating the variable, it
will show up on the screen as below:
If you right-click on this, you will see an option called “slider”. Select this option. Now the variable will look like this:
It has become a slider variable. The user can drag the white knob and change the value of “speed” even while the program is running.
You (the programmer) can set lower and upper limits on this slider variable. Just right click once again and choose “slider min” and
“slider max”. For example, if you entered min=10 and max=40 the slider will only allow values in this range.
Review questions:
1. For which of the following cases would we need to use a variable?
a) 100
b) 50
c) 150
d) 0
Programming practice:
1. Write a program in which the sprite counts 1, 2, 3, … infinity!
Chapter 3.3: Project Game of Maze
Before we look at the specification of this game, let’s learn a couple of new ideas which would be useful in this project.
WAIT UNTIL simply waits as long as the CONDITION is false. As soon as the condition becomes true, it stops waiting and the script
moves to the next command.
The other way is called “polling” in which the program actively checks if a particular key is pressed.
If you want to check this continuously you must use a forever loop:
Polling (in a Forever loop) runs continuously taking CPU time, whereas event handlers do not take CPU time, because they sleep and
are “woken up” when the event occurs. But, precisely for that reason, a tight loop like the one above is more responsive to user actions
than the event-based approach. Another advantage of polling is that the program has full control on when to handle keyboard signals.
When the program stops, polling also stops, whereas event handlers would run even if the program has stopped.
Another interesting advantage of polling is that you can combine multiple events using logic operators as shown below:
If we wanted to change the speed of this wheel, we would need to change the input of the “turn” command. Instead of manually
changing the number, we could use a variable in place of this input:
Now, whenever the variable “speed” changes, the spinning rate will also change immediately. So, the variable has become a “remote
control” of the spinning wheel.
If you create button sprites labeled “Faster” and “Slower” with scripts as shown below, you will see how the remote control works:
Replacing fixed numbers (called “constants”) with variables like this is also known as “parameterization”.
Review questions:
1. What will the following script do?
2. The “glide” command has 3 inputs: time, x value, and y value. Below, we have a script that makes the sprite jump up and
down. If we wanted to remotely control how fast the jump is, which input should we replace with a variable?
Programming exercise:
1. Write the above program to control a spinning wheel using variables. Include these buttons: start, stop, reverse, slow, and
fast.
2. Modify your pong program (ball and single paddle) to add speed control. Add a slider variable to control the ball’s speed.
Count hits and misses.
Chapter 4.2: Built-in Reporter Variables and Bouncing
Reporter variables:
Snap comes with many useful variables that provide some information about the sprites, the program itself, or something else. We will
call them properties to differentiate from variables that we create in the program.
For example, every sprite in your project has several properties; some examples are shown below. Their names clearly indicate what
type of information they report. For example, “x position” reports the current X coordinate of the sprite.
Properties can be used just like any other variable. For example, the command below will make the sprite move left or right where X=0.
Snap also provides a way for one sprite to access information about other sprites through a set of properties under the “Sensing” tab.
Some of these are shown below:
One big difference between your variables and properties is that properties are read-only; their values cannot be modified directly. For
example, the “x position” property will change only when the sprite moves along the X axis.
So, depending on what type of surface (horizontal or vertical) the sprite is bouncing off, the calculation of direction would be different.
Review questions:
1. A sprite’s “direction” property is 180. That means, the sprite is pointing towards:
a. North
b. South
c. East
d. West
2. Assuming the sprite is at the center (i.e. at x=0, y=0) what will the following script do?
4. When a ball bounces around the screen, its “direction” property changes only in sign every time it hits an edge. True or
False?
5. A sprite’s direction or orientation is a built-in Snap variable. Which Snap command sets this variable?
a.
b.
c.
d.
Programming practice:
1. Write a program in which a bird flies in the sky continuously and a cat (or an animal of your choice) runs around on the
ground exactly below the bird (in the hope to catch it).
2. Modify your Pong program that you wrote earlier and make the bouncing of the ball more realistic.
Chapter 4.3: Project Bricks
Project description:
This is a game you play with a ball and a flat paddle. A number of bricks are lined up at the top of the screen. As the ball bounces up
and down you use the paddle to hit the bricks and score points. The ball must not touch the ground: after 3 such touches you lose the
game. If you hit all the bricks you win the game. You can control the difficulty level of the game by changing the speed of the ball.
The following image will give you some more details of the game.
Sprites:
Ball and paddle
Bricks (10 or more, any shape)
Number of lives
User Interaction:
Green flag to reset everything.
Speed slider to set the speed of the ball.
SPACE BAR to start the game.
Additional requirements:
Paddle should only move horizontally, should follow the mouse pointer
A “score” variable should count # of bricks hit
Screens should declare win or loss
All of us know these operators, except may be the last one, which is called the ‘power’ (aka exponentiation) operator. Here are a couple
of examples that would explain what it does.
Be careful with the precedence of operations when you combine these operators. For example, if you wanted to perform (10 + (20 x 5))
you need:
And not:
Snap also offers several additional math operators, some of which are listed below:
String variables:
The SET command (under “Variables”) stores a value in a variable. Earlier we saw that the value can be any number – negative or
positive, whole or decimal. The value can also be a string of characters. For example, you can create a variable called “Name” and store
the value “John Luke Pickard” in this variable.
Obviously, the CHANGE command will not work for a string of characters.
Here is an example of how a string variable may be used. We have a variable called “Message”. In it we first store the string “Hello
World”. Then, the SAY command takes that string from the variable “message” and prints it on the screen.
So, as you can see, you can use variables instead of actual values. When you refer to a variable in your script, the value stored inside
that variable is used.
String variables can be modified by the “string operators” which we will consider next.
String operations:
A string is basically a sequence of alphanumeric letters:
The join operator allows you to concatenate two or more strings. In the script below, we combine 3 strings into a sentence:
The script asks you to type your name. If you type “George” the sprite will say “Hello George, how are you?” on the screen.
The “letter” operator lets you get an individual letter of the given string:
The above script asks you to type your name. If you type “Melinda” the sprite will say “Your initial is: M” on the screen.
The “length” operator tells you how many letters there are in the string:
The above script asks you to type your name. If you type “Devon” the sprite will say “Your name has 5 letters”.
Finally, the “split” operator lets you split a string into two or more strings. The second input (let us call it the "separator") allows you to
specify how the string should be split. The "separator" input can be one of the items in the drop-down list or it can be any string (with
one or more letters). The picture below only shows a partial list of available separators.
The resulting sub-strings are stored in a list. (We will study the list data type later in this book.) Let us see a few examples of how the
split operator works.
The “word” separator splits by whitespace (i.e. any combination of space, line breaks, or tab characters). The following will give a list
containing 4 words.
The “letter” separator simply gives a list of letters (including whitespace). The following will return a list containing 9 letters.
You can also specify your own letter (or string) as separator. The following reporter will give a list of 3 words.
Review questions:
1. What will the following expression give?
a. -190
b. 860
c. -300
d. 570
4. Assume that the “answer” property contains 100 before we run the following script. What will the variable “x” contain after
we run this script?
Programming practice:
1. Write a simple calculator program that takes 2 numbers and performs basic arithmetic on them. Provide a button for each
operation.
3. Ask for first, middle, last names, and then create full name and initials.
4. Count the number of lines, words, and letters in any given string. (Note: You can copy any amount of text from your
Notepad or other text editors and use it as input of the “split” operator.)
Chapter 5.2: Counters and Random Numbers
Variables – as counters:
In the script below, the variable “count” counts the number of repetitions:
Programming practice:
1. Write a program that creates a comma-separated string of numbers. For example, if you provide 3, it will print 1,2,3; if you
provide 5, it will print 1,2,3,4,5; and so on.
Random numbers:
Several outcomes (responses to events) in real life are unpredictable. Here are just a few examples:
Pick a ball out of a bag with your eyes closed.
Roll a die.
Toss a coin.
Decide what to wear to a party.
Outcomes of these acts are not completely random; they are random within some constraints. The outcome in each of the above is one
of a set of possible outcomes. Coin toss involves 2 possible outcomes; retrieving a ball from a bag depends on the number of balls in the
bag; roll of a die has 6 possible outcomes, and so on.
Snap offers a simple way to use randomness in programs through the following operator:
This operator returns a number from 1 to 10 – you can’t predict what it will return. You can use any range (e.g. -100 to 100); the range
can be in any order (e.g. 100 to -100). It can even be a decimal range (e.g. 1.5 to 11.5), although one of the numbers must be a true
decimal, e.g. 1.5, 2.3, 4.6, etc. – 1.0 is taken as 1!
The real key is to figure out how to use this simple operator to simulate the random events that you might want to use in your programs.
For example, how would you simulate the roll of a die? Easy! use since there are 6 possible outcomes.
Algorithms:
An algorithm is a step-by-step procedure that describes how a certain task can be performed. Strictly speaking, an algorithm has a
formal structure (sometimes called the pseudo-code), which includes the initial and final states of the procedure, description of all inputs
and the output, and so on. But, for the purpose of the programming projects in this book, we use algorithms rather loosely to create an
informal high-level description of program steps, and help us in the process of creating the final Snap scripts.
Here is an algorithm for a real-life problem: Let’s say we have 3 opaque bottles and one and only one of them contains salt. We need to
find out which one. Let’s assume all three bottles contain stuff that is eatable (i.e. not harmful to taste!).
Algorithm:
Arrange the 3 bottles in a row and name them A, B, and C.
Open A.
If the stuff inside is powdery and white
Taste some of it.
If taste is salty
Declare that A is the salt bottle.
Stop work
End-if
End-if
Open B.
If the stuff inside is powdery and white
Taste some of it.
If taste is salty
Declare that B is the salt bottle.
Stop work
End-if
End-if
Declare that C is the salt bottle. (No need to open and taste because at least one bottle contains salt).
Here is an example for an arithmetic problem: Let’s say we want to find out the largest among the given 3 integers.
Algorithm:
Given: P, Q, and R are 3 integers. “Temp” is a temporary variable.
Compare P and Q
If P > Q
Save P in Temp
Else
Save Q in Temp
End-if
Compare R and Temp
If R > Temp
Save R in Temp
End-if
Declare Temp as the largest number.
After clicking the Green flag, is it ever possible to have X=5, Y=5, Z=5?
a) No, because random always returns a different number.
b) Yes, because random may return 5 for all three.
3. See the script below. Which of the following letters is likely?
a. c
b. f
c. h
d. a
4. What range would you use in the RANDOM command to pick a month of the year?
5. If you wanted to use the “Go to x y” command to move your sprite such that it goes to any point at the top edge of the
screen, what range would you use in the RANDOM command for the X value?
6. An algorithm is:
Programming practice:
2. Write a fortune-teller program (similar to the 8-ball toy) in which the fortune-teller can answer any yes/no type of question.
For example, if you ask “Will I become the president?” the fortune-teller may answer “Maybe”, or “Sure, why not!”, or “No
way!” etc. (Hint: The fortune-teller basically has a bag of ready answers; every time a question is asked he fishes out one of
them.)
Although listed under the “Pen” tab, the STAMP command has no relation to the pen. So, to change the color of your image you must
use the “change color effect” command. See the example below:
To erase the images created by STAMP, use the CLEAR command.
Review questions:
8. Which of the following is true?
a. The stamp command modifies the appearance of the sprite.
b. The stamp command paints the sprite's image onto the stage.
c. The image created by stamp gets cleared when the program stops.
d. The image created by stamp can be moved using motion commands.
Programming practice:
3. Surprise flower: Upon every click of the pointer, a new flower comes up on the screen where you clicked. (Tip: Use multiple
flower sprites, and then choose size and color randomly before every STAMP.)
4. Russian roulette: This program implements a simplified version of the Russian Roulette in casinos. There is a circle with
each quadrant of a different solid color. A pointer is attached at the center of the circle. There are 4 buttons for each color.
User clicks on one of these buttons, which causes the pointer to spin a random amount. If its tip stops in the color that the
user picked, he makes money, else he loses.
Chapter 5.3: Project Falling Objects
Ok, it's time for another interesting project that will allow us to apply all the new ideas we learnt so far. But, before we discuss the
project, let's just do one more new idea!
In this script, we want the user to enter his/her age. But, what if he/she enters a negative number? In order to ensure the age is a positive
number, we need to continue asking the same question to the user until the user enters it correctly. “Repeat until” does exactly that: it
asks the same question until age > 0.
Review questions:
1. How long will the following script run?
a. 5 seconds
b. 6 seconds
c. 0 seconds
d. forever
Requirements:
Use your own idea of falling objects in the sky.
Use these concepts: conditional statements, broadcasting, sensing, user interaction, random.
Sprite names must be as per the story.
Objects must fall from random locations from the top so the catcher cannot predict where the next object will come
from.
Use variables to track points and/or # of attempts.
Use the “h” key to show help, “Green flag” to set things up, and “Space bar” to start the game.
Here is a sample game screen in which the catcher catches gold coins.
Write in your Design book:
A short description of your project
Answer these questions:
A clone inherits (gets its own copy of) all scripts of its parent sprite except the ones that begin with the event “When Green Flag
clicked”. In addition, every clone, when it is created, runs (only once) scripts that start with the following event:
All clones are deleted when you stop the program using the STOP ALL command or by clicking the STOP button. Each clone may also
delete itself using this command:
Although a clone is an identical copy of a sprite, it does not share the parent’s private variables: instead, each clone gets its own copy of
all private variables. For example, if the parent sprite has a private variable called “id”, the clone would also have its own private
variable called “id”.
Similarly, the clone also gets its own copies of built-in sprite-specific Snap properties such as, xposition and yposition.
Snap provides another way to create clones, using the “reporter” block below:
The purpose of this block is to pass a newly created clone to another method (Snap block) as input. We won’t be using this approach of
creating clones in this book.
Review questions:
1. Let’s say a sprite creates a clone. After creating the clone, if the parent’s direction changes from 90 to 180, the clone’s
direction will also change to 180.
a. True
b. False
After all clones have been created, if another sprite sends a broadcast message “hello”:
Programming practice:
1. Write a program in which bubbles or balloons continuously pop up from the ground (from random locations) and float up to
the top and then disappear. Use clones to create this multiplicity of bubbles (or balloons). Use a counter to track the number
of “live” bubbles at any instant.
2. Modify the “falling object” program you wrote in a previous unit and use the idea of clones for the falling objects.
3. Modify your earlier “Bricks” game to use a single brick sprite which clones itself to create multiple bricks.
Chapter 6.2: Game of Flappy Bird
Piggyback motion:
When you design animation in Snap, there are instances when you want one sprite to “ride” another sprite, i.e. track another sprite’s
motion. For example, consider a horse-rider. Or consider an animation in which a person gets into a bus, drives to downtown, gets off
and walks to his office. Such “riding” or “tracking” motion is called piggyback motion.
Achieving this piggyback effect is quite straightforward. You basically want one sprite (say sprite2) to track the motion of another
sprite (say sprite1). Motion comprises the x and y coordinates and direction. The following properties can be used to access these
values.
And sprite2 can use the following commands to continuously track the motion of sprite1.
In order to ensure sprite2 appears at the right place on top of sprite1, you may need to adjust the x and y values slightly by using the
arithmetic operators.
Here is an example of sprite2 piggybacking sprite1:
Design:
Use the following checkpoints and hints to design this program:
Checkpoint 1:
Checkpoint 2:
1. Add a "help" screen and start game with "space bar pressed" event
2. Add "Glide time" slider variable to control pipe speed.
3. Use clones to create “upper" and “lower” pipes:
“upper” parent will create a clone every few seconds (at random)
The clone will:
i. Save its Y position in a variable.
ii. Signal “lower” pipe and start moving
“lower" parent will create a clone when signaled by “upper”
The clone will calculate its Y position and start moving.
The pen commands listed under the “Pen” tab help you perform various operations on the pen itself, such as set or change its size, color,
and shade. Most of these commands are self-explanatory. Some of the important ones are shown below:
The Snap stage is shared by all sprites for drawing purposes. The command clears up the entire screen no matter which sprite
runs that command.
The pen color is a rather involved matter in Snap. Besides which gives you exactly the color you see, there is
a more elaborate way to get millions of different colors. If you are a serious digital artist, you could use the following command.
Go ahead and experiment with various values of these parameters and see what colors you get. Each parameter can take values between
0 and 100. The property allows you to inspect current values of these parameters.
is an interesting command that fills up the enclosed shape around the sprite with a color of the pen. See the following example:
Let's say we want to paint our favorite square with the color red.
We first draw the square using the following script:
In order to paint this square, the turtle needs to first jump inside. Remember, it has to jump, which means it cannot draw a line while
getting inside. Next, since we want to paint with RED, let's change the pen color to red. Finally, the actual painting job is performed by
FILL. The following script performs these remaining tasks.
The is an interesting reporter block that returns whatever the pen has drawn on the screen as a costume. You can save it
in your list of costumes as shown below:
This instruction adds the current pen drawing into your list of costumes. This sequence is handy if you want to create a costume that
looks like a complicated geometric design which is harder to draw by hand but easier to program!
Note: Refer to the book Pen Art in Snap! Programming written by the same author for a more comprehensive treatment of Snap’s Pen
capability and for numerous interesting programming problems.
Procedures:
A Snap instruction consists of a combination of one or more command blocks that we drag and drop in the script area, and which is then
run by Snap when we click on it. For example, the following is an instruction which evaluates the expression 20*30 and shows 600 on
the screen.
A Snap instruction, like the one above, always carries out a specific, well-defined, and repeatable task. If you look carefully, you will
notice that the instruction above contains the keyword “SAY” and the symbol “x” (for multiplication). Each of these words or symbols
is called a Snap procedure. In other words, every Snap instruction consists of one or more Snap procedures.
A procedure is like a recipe of how to do something. For example, the MOVE command is a procedure that knows how to move a
sprite. Several Snap blocks are thus individual procedures that carry out specific tasks.
Snap allows you to define your own procedures. At the bottom of every tab, is a button labeled “Make a block.” You can also right-
click in the script area and then choose “Make a block” from the menu. A dialog appears in which you can specify the name and type of
the procedure. “Command” is a procedure without a return value and “Reporter” is a procedure that has a return value (and is also
known as a “function”). “Predicate” is a reporter procedure that reports Boolean (true or false) values. We will not use the “predicate”
type in this book.
The following picture shows that we are creating a new “command” procedure called “Greeting”.
We have selected the “Looks” category (palette) for this new block.
When you click Ok, you see this dialog box:
Below the hat block “Greeting” you create a script by attaching existing Snap command blocks. This is what I created:
Clicking “OK” gives us a new procedure called “Greeting” in the “Looks” palette. You can use it in any script. For example:
Review questions:
1. What will the following script draw?
a. Straight line
b. Three parallel lines
c. Equilateral triangle
d. Incomplete square with 3 sides
a. An instruction
b. A procedure
c. Neither instruction nor procedure
d. Both instruction and procedure
4. The following script shows the definition of a new procedure called “jump”. How can I use this new procedure in my Snap
program?
Programming practice:
1. Write programs that draw the following patterns using repetition.
Hint: Each design involves a repeating pattern. Once you identify the basic pattern, you can just use the REPEAT command.
2. Using pen commands (including FILL) and the idea of looping (repetition), see if you can draw the following designs:
Chapter 7.2: Procedures with Inputs
Procedures with inputs:
The behavior of many procedures depends on how they are invoked. It depends on the input supplied. So, can do
its job only when you tell it how many steps to move. Or, command needs to know how many seconds to wait.
Snap allows you to define new custom procedures which take input. Right-click the new block “Jump” (which we defined earlier) and
click “edit”. You will see the block editor again.
We will add to “Jump” a number input labeled as “height”. The label has no importance really, other than giving a descriptive name to
the input.
Type the name “height”. Click the small arrow to choose your input type. In our case, the type is number. After clicking OK, you will
see the following:
Now, the input is useful only if it is actually used in the procedure. You can drag the new input and drop it wherever appropriate in your
sequence of commands. This is how our final “jump” procedure will look:
Note that we have to use the "multiply" operator in the second “change y” command to make the change negative.
If I use this new procedure in a script, say, as , the sprite will jump up and down by 100 steps.
To distinguish from do a little experiment. Run the following script for the above custom
block.
Now, edit the custom block SquareRoot and replace with . And now try the above script again.
Do you see the difference in behavior?
Abstraction:
Abstraction is an interesting concept which means capturing a (relatively) complex idea into a single word (or phrase), image, map,
audio clip, etc. Even in our day-to-day life we assign words to complex concepts or ideas. For example, “pedestrian” is an abstraction
for a person walking on a footpath. Once we assign such words to ideas, we refer to the ideas simply thru those words.
Similarly, your new Snap procedure "Jump" is the abstraction for the idea of moving a sprite some distance up and down. Defining a
new word which has a specific meaning is called abstraction.
Review questions:
1. Every Snap procedure requires input. True or False?
2. You can define a new Snap procedure that takes more than one input. True or False?
3. A sprite has a new procedure called “Square” as shown below. Which of the following is true?
a. It will draw a square as big as the input “size”.
b. It will not draw anything.
c. It will draw a square of size 100.
d. It will not draw a square but a set of 4 connected lines.
Programming practice:
1. Using procedure blocks that use input, draw the following shapes. Hint: Design your basic shape to accept inputs for size
and color.
Chapter 7.3: Going in Circles
Drawing a circle:
A circle is drawn when the pen moves and turns continuously. So the following script would draw a circle of length (circumference)
360.
In reality, this script does not draw a circle; it draws a polygon with 360 sides each of length 1. But, for all practical purposes it looks
like a circle. In fact, if you experiment a bit, you will discover that polygons of even less number of sides (say 180 or 100) also look like
circles on the screen. But, remember that the total of all turns must always be 360 degrees.
Next, we can use the following formula that relates diameter of a circle to its circumference and come up with a Snap procedure to draw
a circle of the given diameter.
So, “circle 50” will draw a circle of diameter 50; “circle 150” will draw a circle of diameter 150; “circle 200” will draw a circle of
diameter 200; and so on.
But, this delay can be problematic for some other occasions. For example, if you are drawing a complicated drawing, say a spiral, the
number of moves is quite large and so, the cumulative delay can make the drawing really slow. For such purposes, you can practically
eliminate the delay by using Snap's “turbo” mode. Suddenly you will notice that your drawing has become much quicker.
Using "true" as input would turn the mode ON, and using "false" would turn it OFF. With turbo mode on, the following two scripts will
be identical in behavior.
Review questions:
1. The following script is expected to draw a polygon of 180 edges. How much should the input to the “Turn” command be?
a. 1
b. 2
c. 4
d. 180
Programming practice:
1. Using the “circle” procedure block defined above, draw the following shapes.
Chapter 7.4: Project Traffic Light
Description:
Additional requirements:
As mentioned, the traffic light is not a sprite, but is drawn by the program using pen commands.
Define the following procedures:
“Fdcircle” procedure will draw a filled circle of the given diameter. The caller will choose the color.
“Frectangle” procedure will draw a filled rectangle of the given height and width. The caller will choose the
color.
“Traffic.Light” will draw the full traffic light. It will take the diameter of each light as input and calculate all
other dimensions accordingly.
Create two separate versions of the program:
In one, use only “broadcasting” to coordinate the interaction between the traffic light and the moving cars.
In the other, use only “variables” to coordinate the interaction between the traffic light and the moving cars.
Optional: Have a separate traffic light for each direction.
Unit 8: Beyond the Basics
All you need in this life is ignorance and confidence, and then success is sure.
– Mark Twain
In this Unit we will discuss a few additional CS and Snap concepts some of which have already been used in assignments and projects
discussed earlier in this book, and some that would be helpful to you to write more challenging Snap programs. If you are looking for
interesting and challenging problems to apply these concepts, please refer to the projects listed in the book “Adventures in Snap!
Programming” by the same author.
Nested IF:
Nested IF means having one IF command inside another.
There is no limit to how deep you can nest. You can have an IF inside an IF inside an IF … ad infinitum. But it is highly recommended
that you avoid nesting of IF statements if you can because the logic can get highly complicated and difficult to debug. Sometimes you
can avoid nesting by using Boolean operators instead. See the example below:
In this nested script, if a kid is less than 10 years old and is in high school, he/she must be a genius!
The same script can be written without the nesting:
Conditional assignment:
Snap offers an interesting shortcut – the reporter – for situations where we assign some value to a variable
that depends on a condition. See the example below:
The following script shows the definition of this new block called “max”.
As you can see, it takes n1 and n2 as input and returns the bigger of the two.
Try running the following commands to verify that “max” works correctly:
The best way to understand how the logic operators work is to construct “truth tables” as shown below.
The AND operator
As you can see, the output is true only when both conditions are true.
The OR operator
See this example:
This script checks if you are pressing any key or clicking the mouse pointer.
As you can see, the output is true when at least one condition is true.
The NOT operator
See this example:
NOT negates the given condition. So, for a NOT expression to be True, the condition must be False. In the script above, the sprite will
move towards the mouse pointer continuously but stop moving when it is touching the pointer.
As you can see, the output is the exact opposite of the input.
The value toggles between “true” and “false” when you click on the white circle. So, this operator always returns “true” or “false” as
indicated. This could be useful, for example, if you have a predicate reporter that needs to return true or false. See the example below:
This reporter returns true if the sprite size is > 100, otherwise false.
Programming practice:
1. When the mouse pointer touches your cat sprite, it meows. It meows only once after touching. If you remove the pointer
away and touch again, it meows again.
Recursion:
The idea of recursion is a property of procedures. Simply stated, a recursive procedure calls itself. For example, the following procedure
is recursive:
If you call this procedure, say by using , it will draw a rectangular spiral forever; it will never stop because it will call itself
indefinitely. What you will have is a program that runs forever!
Writing a program that never terminates is interesting but not very convenient. We would like to write recursive programs that do
interesting things and terminate (i.e. stop) when their job is done. The Snap command will stop the currently
running procedure and return to the calling procedure (or script). Thus, the infinite recursion will be broken.
Programming practice:
2. We used recursion above to draw a rectangular spiral. Modify your script to draw the following recursive patterns. As
indicated, you just need to modify the turning angle.
3. Refer to the chapter on “Recursion” in “Pen Art in Snap! Programming” and try to do the programming assignments given in
that chapter.
4. Write a program to compute the factorial of the given positive integer. For example, factorial of 3 is 3x2; factorial of 5 is
5x4x3x2, and so on. (Hint: Consider using recursive procedure that uses the block.)
List data type:
So far, we have only used numbers and strings as data types. A list data type can hold multiple pieces (and types) of information: words,
numbers, or sentences. In fact, a Snap list can contain even command blocks, scripts, and other lists.
To create a new list you use the reporter block and assign it to a variable. Click the little left-right arrows to add/delete
items to the list.
The above command creates a list containing one, 2, three, and 4 and saves it in the variable “mylist”.
We can then use the following basic commands to manipulate the list. Let’s imagine that we have a list variable called “fruits” and look
at these commands.
List traversal:
For most practical uses of a list – such as when we are searching for an item – we need to read a list from start to end. That’s what
“traversal” means. There are two ways we can traverse a list.
The script below shows one way which uses the “for each” block:
There is another way as shown below, which additionally gives us the “index” (location from the beginning) of each item, which may
be useful in some circumstances.
Programming practice:
5. Convert a sentence into individual words and then say it in the reverse order. For example, if the user gives “My name is
Buddy” the program should say “Buddy is name My”.
Inclusion check:
The following condition checks if the given item is present in the list:
If you know an item exists in a list, the following operator comes handy to now the item’s exact location.
Copying lists:
The following script does not create two copies of a list. It just creates two variables that point at the same list. If you change “fruits” in
some way, for example delete grapes, F will see that change too.
The “append” operator (whose main purpose is to merge 2 or more lists into a single list) can be used to create a copy of a list. Any
subsequent change in “fruits” will now have no effect on F.
Note that the trick here is not use the second input of “append”.
Programming practice:
6. Create a list of names of your friends, with at least six different names. Write a script in which welcomes each person by
name, one at a time. ("Welcome A", "Welcome B", etc.)
7. Write a custom Snap reporter called “average” that takes a list as an argument and reports the average of all the numbers in
the list. (Hint: use the operator to check if an item is a number.)
8. Write a program that implements the Tic-tac-toe game using a 9-item list to represent the entire Tic-tac-toe board. (Note: The
book “Adventures in Snap! Programming” has an entire chapter on how to write this game.)
Below the name, there are two options to select from: (1) For all sprites, and (2) For this sprite only. If you select the first option, you
create a “global” variable, and if you select the second option, you create a “local” variable.
A global variable is visible (and hence accessible) to all sprites in your project. Any sprite can set it, change it, or use it. On the other
hand, a local variable is visible only to this sprite (one in which you created it).
It is a good practice to decide the scope of each variable carefully, and make it “global” only if it is clearly going to be used by multiple
sprites. For example, the “score” variable in a “pacman” game would be needed by multiple sprites (prizes, pacman, obstacles, etc.) so it
should be “global”.
A local variable, if displayed, uses a different notation. See below:
Script variables:
A script variable is accessible only within the script (or custom block) in which it is declared. See the example below:
This custom block swaps the two inputs, i.e., X and Y exchange their contents. We need a temporary variable for this purpose. The
script variable “temp” is visible and accessible only inside this custom block. You will see no sign of it outside.
As far as possible, it is highly recommended to minimize the use of global variables. Use “script variables” as much as possible; your
next best choice is “sprite local variables” discussed earlier. Use “global variables” only if you must.
Mapping random numbers to a set of things:
Sometimes you want to pick something from a collection of things, which is not necessarily an ordered list of numbers. For example,
you want to pick a color from the set of 4 colors: green, red, blue, and yellow. How would you do that using the random operator?
Well, the first step is to realize that the collection contains 4 items. So we should use to pick from 4
numbers. Next, we can map each number to a color: so, 1 could map to red, 2 to blue, 3 to yellow, and 4 to green. Then, depending on
what pick random returned, you would know which color to pick. Here is the script to show the entire scheme of things:
If you want to check this continuously you must use a forever loop:
Note that the condition is “mouse down” and not “mouse click”.
It is possible in the “polling” method that some mouse-downs might be missed if their timing does not match with when the IF
command checks for the mouse-down. Also, polling (in a Forever loop) runs continuously taking CPU time, whereas event handlers do
not take CPU time, because they sleep and are “woken up” when the event occurs. But the advantage of polling is that the program has
full control on when to handle mouse signals. When the program stops, polling also stops, whereas event handlers would run even if the
program has stopped.
Another interesting advantage of polling is that you can combine multiple events using logic operators as shown below:
The loop continues to ask the same question until the user gives a valid answer.
Using variables as gates:
There are occasions when the user must not be allowed to start playing the game until some setup is completed. For example, let’s say
your game starts when the SPACE key pressed. But, before pressing the SPACE key the user must set a few things, for example, slider
variables. We can enforce this by using the concept of “using variables as gates”. In the example below, we will use a variable called
“setupdone” which will be False initially and True after setup is done.
Variables - as timer:
The combination of variables and the WAIT command can be used to implement a timer. See the script below:
The “time” variable is set in the beginning to whatever value you want to set for your game. The repeat loop then decrements it a
second at a time until it becomes 0.
It may be confusing to see the “time” variable getting decremented and also being used in the REPEAT command. The REPEAT
command uses its initial value (in this case 30) to decide the number of repetitions.
A more intuitive (and less confusing) way to do this might be: