Mimir:Draft5 Chapter6

From Openitware
Revision as of 20:33, 26 January 2018 by Mcy59 (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Back to Table of Contents


Chapter 6: Visual Programming

"I look forward to the invention of faster-than-light travel. What I'm not looking forward to is the long wait in the dark once I arrive at my destination." - Marc Beland

The Visual Paradigm

In computing, a visual programming language (VPL) is any programming language that lets users create programs by manipulating program elements graphically rather than by specifying them textually. A VPL allows programming with visual expressions, spatial arrangements of text and graphic symbols, used either as elements of syntax or secondary notation. For example, many VPLs (known as dataflow or diagrammatic programming) are based on the idea of "boxes and arrows", where boxes or other screen objects are treated as entities, connected by arrows, lines or arcs which represent relations. Visual programming languages focus on Graphic User Interfaces (GUIs) in order to create code and applications. "Scratch" and "App Inventor" are the most commonly known visual programming languages.

These languages are much more geared towards educational purposes for beginner programmers, but they can still make useful programs.

Visual programming scratch.png

As you can see with the image above, each block does a certain action when clicked. You don’t necessarily write code, you just drag blocks that are predetermined to do something. These blocks are linked and will do them in the order they should be done according to the languages flow control.

Visual language has a few types, such as icon-based languages, diagramming languages and form-based language. Visual languages should not be confused with GUI-based programming language as they only provide graphical program authoring services. However, their code/context is completely textual. In computing, a visual programming language is any programming language that lets users create programs by manipulating program elements graphically rather than by specifying them textually. A Visual Programming language allows programming with visual expressions, spatial arrangements of text and graphic symbols, used either as elements of syntax or secondary notation. In other words, Visual programming language enables the development of software programs by eliminating textual software code with a series of visual graphics elements. Visual Programming Languages incorporates these graphical elements as the primary context of the language arranged in a systematic order. The graphics or icons included within a visual program serve as input, activities, connections and/or output of the program.

App Inventor

App Inventor is an open-source web application originally designed by Google and now maintained by the Massachusetts Institute of Technology (MIT). It uses a graphical interface and the StarLogo TNG user interface, which allows users to drag-and-drop visual objects to create an application that can run on Android devices.

It allows newcomers to computer programming to create software applications for the Android operating system (OS). It uses a graphical interface, very similar to Scratch and the StarLogo TNG user interface, which allows users to drag-and-drop visual objects to create an application that can run on Android devices. In creating App Inventor, Google drew upon significant prior research in educational computing, as well as work done within Google on online development environments.

App Inventor and the projects on which it is based are informed by constructionist learning theories, which emphasizes that programming can be a vehicle for engaging powerful ideas through active learning. As such, it is part of an ongoing movement in computers and education that began with the work of Seymour Papert and the MIT Logo Group in the 1960s and has also manifested itself with Mitchel Resnick's work on Lego Mindstorms and StarLogo.

The App Inventor Environment

The App Inventor programming environment has three key parts:

  • The Component Designer is used it to select components for your app and specify their properties.
  • The Blocks Editor is used it to specify how the components will behave (e.g., what happens when a user clicks a button).
  • An Android device with which you can actually run and test your app as you are developing it. If you don’t have an Android device handy, you can test the

apps you build by using the Android emulator that comes with the system.


There are two main types of components in an app: visible and non-visible.

  • The app’s visible components are those that you can see when the app is launched—buttons, text boxes, and labels. These are often referred to as the app’s user interface.
  • Non-visible components are those that you can’t see, so they’re not part of the user interface.Instead, they provide access to the built-in functionality of the device;for example, the Texting component sends and processes SMS texts, the LocationSensor component determines the device’s location, and the TextToSpeech component talks.

The non-visible components are the technology within the device—little worker bees that do jobs for your app.

Both visible and non-visible components are defined by a set of properties. Properties are memory slots for storing information about the component. Visible components like buttons and labels have properties such as Width, Height, and Alignment, which together define how the component looks.

Component properties are like spreadsheet cells: you modify them in the Component Designer to define the initial appearance of a component. You can also change the values with blocks.


App components are generally straightforward and easy to understand: a text box is for entering information, a button is for clicking, and so on. An app’s behavior, on the other hand, is conceptually difficult and often complex. The behavior defines how the app should respond to events, both user initiated (e.g., a button click) and external (e.g., an SMS text arriving to the phone). The difficulty of specifying such interactive behavior is why programming is so challenging.

Fortunately, App Inventor provides a high-level blocks-based language for specifying behaviors. The blocks make programming behaviors more like plugging puzzle pieces together, as opposed to traditional text-based programming languages, which involve learning and typing vast amounts of code. And App Inventor is designed to make specifying event-response behaviors especially easy. The following sections provide a model for understanding app behavior and how to specify it in App Inventor.

Event Handlers

Most modern software doesn’t perform a bunch of instructions in a predetermined order; instead, it reacts to events—most commonly, events initiated by the app’s end user. For example, if the user taps a button, the app responds by performing some operation (e.g., sending a text message). For touchscreen phones and devices, the act of dragging your finger across the screen is another event. The app might respond to that event by drawing a line from the point at which your finger first contacts the screen to the point where you lifted it. Modern apps are better conceptualized as event-response machines.

As events occur, the app reacts by calling a sequence of functions. Functions are things you can do to, or with, a component; these can be operations such as sending an SMS text, or property-changing operations such as changing the text in a label of the user interface. To call or invoke a function means to carry out the function—to make it happen. We call an event and the set of functions performed in response to it an event handler.

One reason why App Inventor programming is so intuitive is that it’s based directly on this event-response paradigm; event handlers are primitives in the language (in many languages, this is not the case). You begin defining a behavior by dragging out an event block, which has the form, “When <event> do.” For example, consider an app, SpeakIt, that responds to button clicks by speaking aloud the text the user has typed in a textbox.

Event Types


User-initiated events are the most common type of event. With input forms, it is typically the user tapping a button that triggers a response from the app. More graphical apps respond to touches and drags.


Sometimes, your app needs to perform certain functions immediately upon startup, not in response to any end-user activity or other event. How does this ft into the event-handling paradigm?

Event-handling languages such as App Inventor consider the app’s launch as an event. If you want specific functions to be performed as the app opens, you drag out a Screen1.Initialize event block and place the pertinent function call blocks within it.


Some activity in an app is triggered by the passing of time. You can think of an animation as an object that moves when triggered by a timer event. App Inventor has a Clock component that you can use to trigger timer events.


Activity involving graphical objects (sprites) within canvases will trigger events. So you can program games and other interactive animations by specifying what should occur on events such as an object reaching the edge of the canvas or two objects colliding.


When your phone receives location information from GPS satellites, an event is triggered. Likewise, when your phone receives a text, an event is triggered Such external inputs to the device are considered events, no different than the user clicking a button.

Thus, every app you create will be a set of event handlers: one to initialize things, some to respond to the end user’s input, some triggered by time, and some triggered by external events. Your job is to conceptualize your app in this way and then design the response to each event handler.


Defining Variables

Like properties, variables are named memory slots, but they are not associated with a particular component. You define a variable when your app needs to remember something that is not being stored within a component property. For example, a game app might need to remember what level the user has attained. If the level number were going to appear in a Label component, you might not need a variable, because you could just store the level in the Text property of the Label component. But if the level number is not something the user will see, you’d define a variable in which to store it.

Here are the steps you’d follow to create a variable called score with an initial value of 0:

  1. In Built-in blocks, open the Variables drawer and drag out the initialize global block.
  2. Change the name of the variable by clicking the text “name” and typing “score”.
  3. From the Math drawer, drag out a number block and plug it into the open socket of the variable definition to set the initial value.

When you define a variable, you instruct the app to set up a named memory slot for storing a value. These memory slots, as with properties, are not visible to the user when the app runs.

The number block you plug in specifies the value that should be placed in the slot when the app begins. Besides initializing with numbers or text, you can also initialize the variable with a make a list or create empty list block. This informs the app that the variable will store a list of memory slots instead of a single value.

Setting a Variable to an Expression

As you’ve seen, you can put simple values such as 5 into a variable, but often you’ll set the variable to a more complex expression (expression is the computer-science term for a formula). For example, when the user clicks Next to get to the next question in a quiz app, you’ll need to set the currentQuestion variable to one more than its current value. When someone loses ten points in a game app, you need to modify the score variable to 10 less than its current value.

Displaying Variables

When you modify a component property, as in the preceding example, the user interface is directly affected. This is not true for variables; changing a variable has no direct effect on the app’s appearance. If you just incremented a variable score but didn’t modify the user interface in some other way, the user would never know there was a change. It’s like the proverbial tree falling in the forest: if nobody was there to hear it, did it really happen?

Sometimes, you do not want to immediately manifest a change to the user interface when a variable changes. For instance, in a game you might track statistics (e.g., missed shots) that will only appear when the game ends.This is one of the advantages of storing data in a variable as opposed to a component property: you can show just the data you want when you want to show it.

You can also separate the computational part of your app from the user interface, making it easier to change that user interface later. For example, with a game, you could store the score directly in a Label or in a variable. If you store it in a Label, you’d increment the Label’s Text property when points were scored, and the user would see the change directly. If you stored the score in a variable and incremented the variable when points were scored, you’d need to include blocks to also move the value of the variable into a label. However, if you decided to change the app to display the score in a different manner, perhaps with a slider, the variable solution would be easier to change. You wouldn’t need to modify all the places that change the score; you’d only need to modify the blocks that display the score.

Local Variable

If the variable is only needed in one place, it is a good idea to define it as a local. By doing so, you limit the dependencies in your app and ensure that you won’t mistakenly modify a variable. Think of a local variable like the private memory in your brain—you certainly don’t want other brains to have access to it!


What Is Scratch?

Scratch is an imperative, event-driven language. Being heavily graphic in terms of an executed end-product, much of the code is based around waiting for specific events to occur (user input, contact between sprites, variable thresholds), which trigger additional pieces of code. The code, for the most part, is dedicated to altering the state of the presented visuals.

Scratch was originally released in 2006 at MIT. Designed by Mitchell Resnick in 2003, the language itself is simple to use, underscoring the fact that it was originally put together as an introductory language for children. It introduces basic programming concepts in a format that lets the learner worry less about syntax and more about construction, and produces results very quickly.

What Can Scratch Teach Us?

Scratch is primarily visual; every component used to give functionality to the pieces of a Scratch program has a visible "physical" component that will need to be added. Rather than typing out commands though, the commands are shown visually as geometric objects that interact with other objects in very specific ways. These objects' shapes are designed in such a way that they act as a pre-execution syntax check. It is impossible to incorrectly construct a statement in Scratch, because the objects won't allow themselves to be assembled incorrectly.

Although Scratch may seem to be simplistic, it is a rather powerful tool that demonstrates many higher level concepts to children such as Message Passing. Message Passing is what happens when an actor or object calls a process, function, or subroutine via an intermediary structure without calling them directly. These functions or processes that are listening for the message are then activated and perform their own code based on what was broadcast.

Flow Control


Scratch also demonstrates how Flow Control functions within a program. Flow Control is how different possibilities are managed within a program. Without control flow, a program is essentially an ordered list of instructions to be followed one after another, and not repeated until the program is run again. Control flow gives us the ability to repeat tasks, or pull information out of order, or choose from multiple functions from the same program.

There are several main aspects to Flow Control. The first would be Loops. Loops are repeated sets of instructions. Depending on the design of the loop it may have a fixed number of repetitions, dependent on input, or it might be designed to repeat until a break is called or detected. The main idea of a loop is to continue to do a set task repeatedly, but there can be many ways to interrupt or modify it.

The second aspect of Flow Control is Conditional Flow. Conditional flow works with branching paths and possibilities. Many programmers recognize this as if-then-else statements. Operators that provide conditional flow look for certain terms to be filled. For example, "If a child receives ice cream, then they are happy." As long as these terms are met, the associated code runs. Otherwise if the terms are not met there can be code that activates in that scenario, or simply nothing at all. It is a powerful tool that is used in most programming languages today.

The final part we will cover are Sub-Routine Calls. Sub-Routine Calls have a host of different names, such as functions or methods. The one thing they all have in common is that they refer to another part of the same program that provides additional functionality to the program. Essentially, when a program reaches a subroutine call, it leaps directly to the portion of the program holding that subroutine, executes the instructions it finds there, then returns to wherever it was in the program. Depending on the sub-routine, it may also return results back to the calling function. This may be a string, it may be numeric, it may be absolutely nothing at all.

Scratch block types

Blocks are used to create code in Scratch. The blocks connect to each other like a jigsaw puzzle which prevents syntax errors. There are six block shapes: Hat, Stack, C, Cap, Boolean and Reporter. There are eight categories of blocks:

  • Motion
  • Looks
  • Control
  • Sound
  • Sensing
  • Pen
  • Operators
  • Variables

We discussed there are 8 categories of Blocks Types. Let's discuss their functionality.

1- Motion blocks

Loop motion.png

Motion blocks deal with the movement of sprites. They relate mainly to the x and y position and direction of the sprite, as almost all the blocks correspond to them. The Stage does not contain any Motion blocks since it is a still object.They are color-coded medium-blue. They are available only for sprites. There are 17 blocks under the motion category in Scratch.

  • Move () Steps — Moves the sprite forward the amount of steps in the direction the sprite is facing.
  • Turn () Degrees (Clockwise) — Turns the sprite (clockwise) the specified amount.
  • Turn () Degrees (Counter-clockwise) — Turns the sprite (counter-clockwise) the specified amount.
  • Point in Direction () — Points the sprite in the direction.
  • Point Towards () — Points the sprite towards the mouse-pointer or another sprite.
  • Go to X: () Y: () — Moves the sprite to the specified X and Y position.
  • Go to () — Moves the sprite to the mouse-pointer or another sprite.
  • Glide () Secs to X: () Y: () — Glides the sprite to the location, taking as long as the specified amount of time.
  • Change X by () — Changes the sprite's X position by the amount.
  • Set X to () — Sets the sprite's X position to the amount.
  • Change Y by () — Changes the sprite's Y position by the amount.
  • Set Y to () — Sets the sprite's Y position to the amount.
  • If on Edge, Bounce — If touching the edge of the screen, the sprite's direction flips over.
  • Set Rotation Style () — This sets the rotation style of a sprite.

Scratch has the following three Motion Reporter blocks:

  • X Position — The X position of the sprite.
  • Y Position — The Y position of the sprite.
  • Direction — The direction of the sprite.

2- Looks blocks

Loop looks.png

Looks blocks are related to the appearance of sprites and the stage. Some of the functionalities are changing costumes and applying graphic effects. Looks blocks are the blocks that control a sprite's look. They are color-coded purple, and are used to control a sprite's appearance. There are currently 22 Looks blocks: 18 Stack blocks and 4 Reporter blocks. 14 are only for sprites, and 4 are only for the Stage.

  • Say () for () Secs — A speech bubble appears over the sprite and stays for the specified amount of time.
  • Say () — A speech bubble appears over the sprite and will not go away over time.
  • Think () for () Secs — A thought bubble appears over the sprite and stays for the specified amount of time.
  • Think () — A thought bubble appears over the sprite and will not go away over time.
  • Show — Shows the sprite.
  • Hide — Hides the sprite.
  • Switch Costume to ()/Switch Backdrop to () — Changes the sprite's/Stage's costume/backdrop to the specified one.
  • Switch Backdrop to () and wait — Like the Switch to Backdrop () block, though it waits until all of the hat blocks triggered by this have completed. (Stage only)
  • Next Costume/Next Backdrop — Changes the sprite's/Stage's costume/backdrop to the next one in the costume list.
  • Change () Effect by () — Changes the specified effect by the amount.
  • Set () Effect to () — Sets the specified effect to the amount.
  • Clear Graphic Effects — Clears all graphic effects on the sprite.
  • Change Size by () — Changes the sprite's size by the amount.
  • Set Size to ()% — Sets the sprite's size to the amount.
  • Go to Front — Puts a sprite in the front.
  • Go Back () Layers — Changes the sprite's layer value by the amount.

Scratch has the following three Looks Reporter blocks:

  • Costume # (for sprites) / Backdrop # (for the Stage) — The number of the sprite/Stage's current costume/backdrop in the list.
  • Backdrop Name — Reports the name of the current backdrop.
  • Size — The sprite's size.

3- Control Block

Loop control.png

Control blocks are the blocks that control scripts. In other words, Control blocks run the basic flow of a project in a desired fashion, whether it be organized or unexpected. They provide functions for looping various blocks and scripts. They "control" the project and enhance its running. They are color-coded gold. There are currently 11 Control blocks: 1 Hat block, 5 C blocks, 3 Stack blocks and 2 Cap blocks.

Scratch has the following one Control Hat block:

  • When I Start as a Clone (sprites only) — This hat block is triggered whenever a clone is created, and will only be run by that clone.

Scratch has the following three Control Stack blocks:

  • Wait () Secs — Pauses the script for the amount of time.
  • Wait Until () — Pauses the script until the condition is true.
  • Create Clone of () — Creates the specified clone.

Scratch has the following five Control C blocks:

  • Repeat () — A loop that repeats the specified amount of times.
  • Forever — A loop that will never end.
  • If () Then — Checks the condition so that if the condition is true, the blocks inside it will activate.
  • If () Then, Else — Checks the condition so that if the condition is true, the blocks inside the first C will activate and if the condition is false, the blocks inside the second C will activate.
  • Repeat Until () — A loop that will stop once the condition is true.

Scratch has the following two Control Cap blocks:

  • Stop () — Stops the scripts chosen through the drop-down menu. Can also be a stack block when "other scripts in this sprite" is chosen.
  • Delete This Clone (sprites only) — Deletes a clone.

4- Sound Blocks

Loop sound.png

Sound blocks are related to playing various sounds, whether they be MIDI notes or saved sounds. They are color-coded pink. There are 13 Sound blocks in Scratch: 11 Stack blocks and 2 Reporter blocks. Scratch has the following eleven Sound Stack blocks:

  • Play Sound () — Plays a sound without pausing the script.
  • Play Sound () Until Done — Plays a sound and pauses the script until it finishes.
  • Stop All Sounds — Stops all playing sounds.
  • Play Drum () for () Beats — Plays the specified drum for the amount of beats.
  • Rest for () Beats — Pauses the script for the amount of time.
  • Play Note () for () Beats — Plays the note for the amount of beats.
  • Set Instrument to () — Sets the instrument to the specified one.
  • Change Volume by () — Changes the volume by the amount.
  • Set Volume to () % — Sets the volume to the amount.
  • Change Tempo by () — Changes the tempo by the amount.
  • Set Tempo to () bpm — Sets the tempo to the amount.

Scratch has the following two Sound Reporter blocks:

  • Volume — The volume.
  • Tempo — The tempo.

5- Sensing Blocks

Loop sensing.png

Sensing blocks associate with sprites and the stage detecting conditions. For example, sensing blocks can be used to detect when one sprite touches another. They consist of many booleans and can work with Control blocks to stabilize a project's a flow. They are color-coded light-blue. There are currently 20 Sensing blocks: 4 Stack blocks, 5 Boolean blocks and 11 Reporter blocks.

Scratch has the following four Sensing Stack blocks:

  • Ask () and Wait — An input box appears — you type the value in and it stores the value in the answer variable.
  • Reset Timer — Resets the timer.
  • Turn Video () — Turns the video on.
  • Set Video Transparency to ()% — Sets the transparency of the video.

Scratch has the following five Sensing Boolean blocks:

  • Touching ()? — The condition for checking if the sprite is touching the mouse-pointer or another sprite.
  • Touching Color ()? — The condition for checking if the sprite is touching a specific color.
  • Color () is Touching ()? — The condition for checking if a color on the sprite is touching a specific color.
  • Key () Pressed? — The condition for checking if the specified key is being pressed.
  • Mouse Down? — The condition for checking if the mouse is down.

Scratch has the following eleven Sensing Reporter blocks:

  • Distance to () — The distance from the sprite to the mouse-pointer or another sprite.
  • Answer — The most recent input with the Ask () And Wait block.
  • Mouse X — The mouse-pointer's X position.
  • Mouse Y — The mouse-pointer's Y position.
  • Loudness — How loud the noise is that the microphone is sensing.
  • Timer — How much time has passed since the Scratch program was opened or the timer reset.
  • Video () on () — The video motion or direction of video motion on an object.
  • () of () — The X position, Y position, direction, costume, size or volume of the Stage or a sprite.
  • Current () — The specified time unit selected.
  • Days Since 2000 — The number of days since 2000.
  • Username — The username of a user.

6- Pen Blocks

Loop pen.png

Pen blocks are related to a sprite's pen, which is a feature that allows a line to be to be drawn in accordance with a sprite's location (the line or "pen" is always at the costume center of the sprite it is in). The blocks are associated with turning the pen on and off, stamping a sprite's image onto the stage, and adjusting the various appearance values of the pen. They are color-coded dark-green, and are used to control the pen aspect of the Scratch Program. There are 11 Stack blocks in this category.

Scratch has the following eleven Pen Stack blocks:

  • Clear — Removes all pen marks put on the screen.
  • Stamp — Pens the sprite's image on the screen. Can be removed using clear.
  • Pen Down — Puts the sprite's pen down.
  • Pen Up — Puts the sprite's pen up.
  • Set Pen Color to () (color-picker) — Sets the pen color to the specified color shown on the picture.
  • Change Pen Color by () — Changes the pen color by the amount.
  • Set Pen Color to () (number) — Sets the pen color to the amount.
  • Change Pen Shade by () — Changes the pen shade by the amount.
  • Set Pen Shade to () — Sets the pen shade to the amount.
  • Change Pen Size by () — Changes the pen size by the amount.
  • Set Pen Size to () — Sets the pen size to the amount.

7- Operators Blocks

Loop operators.png

Scratch Operators blocks, originally called "Numbers" blocks, deal with many mathematical functions within a project. They are a green color and provide the capabilities of simple to complex mathematical operations. "Operators" also contains blocks for modifying strings and implementing them into various uses. There are some boolean blocks, too, in which some are related to mathematical outputs, while others are used for adjoining other booleans into one or a different output condition. There are 17 Operators blocks in Scratch.

Scratch has the following six Operators Boolean blocks:

  • () < () — The condition for checking if a value is less than the other.
  • () = () — The condition for checking if two values are equal.
  • () > () — The condition for checking if a value is greater than the other.
  • () and () — Joins two conditions.
  • () or () — Joins two conditions, but they function separately.
  • Not () — Makes the condition checked if it is false, not true.

Scratch has the following eleven Operators Reporter blocks:

  • () + () — The value of the addition.
  • () - () — The value of the subtraction.
  • () * () — The value of the multiplication.
  • () / () — The value of the division.
  • Pick Random () to () — Picks a random number between the two limits.
  • Join ()() — The two values put right next to each other.
  • Letter () of () — The specified character of the value.
  • Length of () — The length of the value.
  • () Mod () — The remainder of the division.
  • Round () — Rounds the value to the nearest whole number.
  • () of () — The absolute value (abs), square root (sqrt), sine (sin), cosine (cos), tangent (tan), asine (asin), acosine (acos), atangent (atan), natural logarithm (ln), logarithm (log), exponential function (e^), or base 10 exponential function (10^) of a specified value.

8- Data Blocks

Loop variables.png
Loop lists.png

Data blocks include two subcategories, Variables and Lists, but both are related to storing and accessing data. Data blocks are used for storing information, such as a score in a project, and using it in scripting and other beneficial purposes. The variable blocks are color-coded orange, and the list blocks are color-coded dark red. There are currently 15 Data blocks: 10 Stack blocks, 4 Reporter blocks, and 1 Boolean block. There are 5 variable blocks and 10 list blocks.

Variables Blocks

Variables blocks are the blocks that hold values and strings. There are 5 Variables blocks in Scratch.

Scratch has the following four Variables Stack blocks:

  • Set () to () — Sets the specified variable to the amount.
  • Change () by () — Changes the specified variable by the amount.
  • Show Variable () — Shows the variable's Stage Monitor.
  • Hide Variable () — Hides the variable's Stage Monitor.

Scratch has the following Variables Reporter block:

  • () — The variable's value.

List Blocks

List blocks are the blocks that manage lists. The blocks become visible once a list is created. They are stored in the Data category. There are 10 List blocks in Scratch.

Scratch has the following six List Stack blocks:

  • Add () to () — Adds an item to the list (the item goes at the bottom of the list of items) with the specified content in it.
  • Delete () of () — Deletes the item of the list.
  • Insert () at () of () — Adds an item to the list (the item goes where you specify in the list of items) with the specified content in it.
  • Replace Item () of () with () — Replaces the item's content with the specified content.
  • Show List () — Shows a list.
  • Hide List () — Hides a list.

Scratch has the following 3 List Reporter blocks:

  • () — The list's value.
  • Item () of () — The item's value.
  • Length of () — How many items there are in the specified list.

Scratch has the following List Boolean block:

  • () Contains () — The condition for checking if an item's content is the specified text.

Scratch data types

Scratch has three first-class data types:

  • Boolean
  • Number
  • String

These are the only data types that can be used in expressions, stored in variables, or returned by built in functions.

Race condition in Scratch

A race condition or race hazard is the behavior of an electronic, software, or other system where the output is dependent on the sequence or timing of other uncontrollable events. It becomes a bug when events do not happen in the order the programmer intended. A race condition in scratch occur when two different Sprites ask the same question and get different answers. Race condition happens when two different bits of the program "race" to do something at the same time, and the programmer doesn't have control over which "wins".

Strategies to avoid a race condition

  • Avoid having more 'green flag' or other hat scripts (with rounded tops) than you need. If you can combine them without causing any problems, it's best to do that. This enables you to determine the order the blocks run in.
  • If you have a bug that might be caused by a race condition, try adding wait blocks to delay some of your scripts so they execute in an order that you can influence. This can be valuable for finding bugs when you're testing your program.
  • Use Scratch broadcasts to synchronize between sprites where necessary. For example, you could have a green flag script that sets up your variables and gets everything else ready, and then sends a broadcast to start scripts on other sprites. That avoids a clash where the other sprites might be trying to use variables you haven't set up yet (for example).
  • Use the broadcast and/or wait blocks where they makes sense. This stops your script from steaming ahead before getting the results it needs from other scripts.

Sprites: The scratch object model

Sprites are objects: they encapsulate state and behavior. Commands operate only on the sprite in which they appear; one sprite cannot invoke a command such as "move" on another sprite. Every sprite has an independent set of scripts. The scripts in a given sprite tell the entire story about the sprite's behavior.


A quick summary of the chapter should go here

Key Terms

A list of key terms should go here. This should be created using some sort of glossary type plugin.

Problem Sets

Make Your Own Game

Try making your own game! Give it a starting screen, instructions, and several playable levels!

Top of Page - Prev Chapter - Next Chapter