Open-source libraries used

1 libraries are bundled into this tool's code.

Scratch Cheatsheet โ€” Quick Reference

Scratch 3 block-based programming cheatsheet: variables, lists, clones, broadcasts and the nine block categories โ€” covers beginners' games, animations and storytelling.

S3

Scratch Scratch 3.0 (online editor)

Scratch 3 (block-based) ยท Event-driven ยท visual ยท cooperatively single-threaded ยท Dynamic (weakly typed variables)

Recommended Learning Path

Build your first program: green flag + Say block โ†’ learn variables, lists and control flow (if / repeat) โ†’ use sensing to read keyboard and mouse, broadcast to make sprites talk โ†’ organize code with custom blocks, do multi-sprite scenes with clones โ†’ finish by skimming the FAQ to dodge pitfalls, and learn the timer for timing and cloud variables for shared high scores.

1.Hello World and the Starting Point

Your first program from the green flag: making a sprite speak, switching costumes and backdrops, and getting to know the nine block categories.

Minimal program

Click the green flag to make the sprite speak โ€” the starting point of every Scratch project. A minimal program only needs Events and Looks blocks.

1
2
when green flag clicked
say (Hello, world!) for (2) seconds

Starting with the green flag

The green-flag block is the project's start switch. Clicking the green flag above the stage runs every green-flagged script at once; clicking the red stop button halts them all.

1
2
3
4
5
when green flag clicked
forever
move (10) steps
if on edge, bounce
end

Sprite speaks

The Say and Think blocks make a sprite display text in a speech bubble โ€” the most direct form of output. With a duration they disappear after the seconds elapse; without one they stay.

1
2
3
4
when green flag clicked
say (Hello, I'm the cat!) for (2) seconds
think (What to do next...) for (2) seconds
say (Click me to start!)

Switch costume

Each sprite can have multiple costumes; switching between them creates walking, blinking, etc. The Next Costume block cycles through them in order.

1
2
3
4
5
when green flag clicked
forever
next costume
wait (0.2) seconds
end

Switch backdrop

Stage backdrops are scenes and can change with the story. Combine with the "when backdrop switches to" block to run different scripts per backdrop.

1
2
3
4
when green flag clicked
switch backdrop to (Forest)
wait (3) seconds
switch backdrop to (Castle)

Nine block categories

Blocks split into nine colored categories: Motion (blue), Looks (purple), Sound (pink), Events (yellow), Control (orange), Sensing (cyan), Operators (green), Variables (orange), My Blocks.

1
2
3
4
5
// Events (yellow) Control (orange) Motion (blue) Looks (purple) Sound (pink)
// Sensing (cyan) Operators (green) Variables (orange) My Blocks (purple)
// Drag blocks from the left panel into the middle script area to assemble them
when green flag clicked
say (Welcome to Scratch!)

Scripts run top to bottom

Inside a single script blocks run top to bottom โ€” each finishes before the next starts, so order dictates the sequence of actions.

1
2
3
4
5
when green flag clicked
move (100) steps
turn right (90) degrees
move (100) steps
// Move forward, then turn right, then move forward again

Save and share

Once you sign in, projects auto-save to the cloud. Use the File menu to download to your computer, or click "Share" in the top-right to publish online for anyone to play.

1
2
3
4
// In the File menu you can "Save to your computer" or "Load from your computer"
// Once you sign in, projects auto-save to the cloud
// Click "Share" in the top right to publish to the Scratch website
// Others run your project online, no download needed

2.Variables and Constants

Create variables, set and change values, show and hide them, plus cloud variables and local variables.

Create a variable

In the Variables category click "Make a Variable" and type a name (e.g. score). A variable is like a box that can hold numbers, text or booleans.

1
2
3
4
// Variables category > Make a Variable > Enter name: score
set [score v] to (0)
set [name v] to (Cat)
set [win v] to (false)

Set and change

"Set" assigns a value to a variable; "Change" adds or subtracts from the current value. Scores and HP are updated with the Change block.

1
2
3
4
set [score v] to (0)
change [score v] by (10) // score becomes 10
change [score v] by (-5) // score becomes 5
set [score v] to (100) // set directly to 100

Show and hide

Variables show by default in the top-left of the stage and you can drag them around. Use the Hide Variable block to clear the screen of ones you don't need.

1
2
3
4
set [score v] to (0)
show variable [score v]
wait (2) seconds
hide variable [score v]

List variable

A list is a variable that holds many items, like a row of boxes. You can add, delete and read elements at a given index.

1
2
3
4
5
6
add (apple) to [fruits v]
add (banana) to [fruits v]
add (watermelon) to [fruits v]
// fruits = [apple, banana, watermelon]
item (2) of [fruits v] // banana
length of [fruits v] // 3

Constants and fixed values

Numbers or text you type directly into a block are constants โ€” they don't change at runtime. Use a variable only when the value needs to vary.

1
2
3
4
move (10) steps // 10 is a constant
wait (1) seconds // 1 is a constant
say (Fixed hint text) // text constant
set [speed v] to (10) // store the constant in a variable

Cloud variable

Cloud variables store data on the server, shared by everyone who opens the project โ€” perfect for leaderboards, but only numbers are supported.

1
2
3
4
5
// When creating a variable, tick "Cloud variable" (login required, numbers only)
set [highscore v] to (score)
if <(score) > (highscore)> then
set [highscore v] to (score)
end

Local variable

By default variables are shared project-wide. Checking "For this sprite only" makes the variable private to the sprite; each clone then gets its own copy.

1
2
3
// When creating a variable, choose "For this sprite only"
when green flag clicked
set [private v] to (0)

Slider variable

Right-click a variable display on the stage to make it a slider โ€” drag with the mouse to change the value live, handy for volume, speed and other tunable parameters.

1
2
3
4
// Right-click the variable watcher > slider
// Set the range (min/max), then drag
set [volume v] to (slider value)
set volume to (volume) %

3.Data Forms

Scratch data comes in three forms โ€” numbers, strings and booleans โ€” and variables auto-infer the type.

Number

Numbers go straight into a block's round white slot โ€” positive, negative or decimal. The four arithmetic operators all return numbers.

1
2
3
4
5
set [score v] to (100)
set [step v] to (0.5)
(10) + (5) // 15
(7) * (8) // 56
((score) / (2)) // 50

String

Text (strings) fit in the round or oval white slots. Say, Think and list items can all be strings.

1
2
3
set [name v] to (Cat)
say (Hello, my name is Cat)
join (apple) (banana) // applebanana

Boolean

Comparison and logic blocks return true or false and only fit into the hexagonal slots used for conditionals.

1
2
3
4
<(score) > (99)> // true or false
<(score) = (100)>
<<(a) > (0)> and <(b) > (0)>> // true only if both are true
<not <(score) < (0)>>

List element

List elements can be numbers or text โ€” read element n by index. Element types are untyped, so you can mix them.

1
2
3
4
add (100) to [data v]
add (Cat) to [data v]
item (1) of [data v] // 100
item (2) of [data v] // Cat

Automatic type inference

Scratch doesn't require declared types: a variable is whatever you last stored, and you can switch types freely. Numbers and strings auto-convert during operations.

1
2
3
set [x v] to (10) // number
set [x v] to (text) // switch to a string
set [x v] to (<(1) > (0)>) // boolean

Input format

The Ask block lets the user type; the Answer block returns it as a string. Use an operator block to convert it to a number when needed.

1
2
3
4
5
ask (How old are you?) and wait
set [age v] to (answer)
if <(age) > (6)> then
say (You can play more complex games)
end

Output format

Say and Think turn data into visible text. Operator results and list elements can be dropped straight into an output block.

1
2
3
say (join (Score:) (score))
say (join (item (1) of [ranking v]) ( took first place))
set volume to (volume) %

Number and text conversion

round rounds to nearest integer; mod gives the remainder. Numbers automatically become text when concatenated.

1
2
3
4
5
round (3.7) // 4
round (3.2) // 3
((10) mod (3)) // 1
// Numbers concatenated into text are converted automatically
say (join (Score:) (score))

4.Variables and Data Storage

Store data with variables and lists, and pass data between sprites via clones, broadcasts and cloud variables.

Variable storage

A variable is data's "home": set a value before reading it. Scripts share data by reading and writing the same variable, but mind the timing.

1
2
3
4
when green flag clicked
set [coins v] to (0)
when this sprite clicked
change [coins v] by (1)

List for multiple items

Lists hold many items at once, like arrays. Read and write by index โ€” great for logging every score in a round, every enemy's coordinates, etc.

1
2
3
4
5
delete (all) of [scores v]
repeat (5)
add (pick random (0) to (100)) to [scores v]
end
item (1) of [scores v]

Clones carry data

A clone copies the sprite's entire scripts and variables. Each clone's "For this sprite only" variables are independent โ€” use an ID to tell clones apart.

1
2
3
4
5
when green flag clicked
create clone of (myself)
create clone of (myself)
when I start as a clone
go to x: (pick random (-200) to (200)) y: (pick random (-150) to (150))

Private variable

A "For this sprite only" variable lives independently inside each clone, so changing one doesn't affect the others โ€” the key to telling clones apart.

1
2
3
4
5
6
7
8
when green flag clicked
set [id v] to (0)
repeat (3)
change [id v] by (1)
create clone of (myself)
end
when I start as a clone
say (join (I am clone ) (id))

Cloud variable

Cloud variables sync numbers to the server so every player shares the same data โ€” ideal for leaderboards and online battles, but values are numeric only.

1
2
3
// When creating a variable, tick "Cloud variable"
when green flag clicked
set [online v] to (0)

Broadcast passes data

Broadcasts carry only a message name; to pass data, write the value into a global variable first, then broadcast and let the receiver read it.

1
2
3
4
5
when green flag clicked
set [score v] to (100)
broadcast (gameover)
when I receive (gameover)
say (join (Final score:) (score))

Global vs local variables

By default variables are visible project-wide โ€” any sprite can read or write them. Choosing "For this sprite only" scopes the variable to that sprite or one of its clones.

1
2
3
4
// Global variable: shared by all sprites
set [total v] to (100)
// Local variable: visible only to the current sprite
set [myspeed v] to (5)

Data persistence

Variables only live while the project runs โ€” refreshing the page or closing the project clears them. Use cloud variables or copy data out for long-term storage.

1
2
3
4
5
6
// Cloud variables: signed-in users' data lives on the server, kept long-term
// Export data: copy formatted list contents into a text file
ask (Load your previous record?) and wait
if <(answer) = (yes)> then
say (Read cloud high score)
end

5.Control Flow

Control script flow with conditionals and loops: if, repeat, repeat-until, wait and stop.

If conditional

"If ... then" only runs the inner blocks when the condition holds. The condition fits in a hexagonal slot โ€” drop in a comparison or logic block.

1
2
3
if <(score) > (99)> then
say (Perfect!)
end

If-else

"If ... then ... else" is a two-way branch: when true run the first arm, when false run the second. Great for win/lose or on/off states.

1
2
3
4
5
if <key (space v) pressed?> then
say (Jump)
else
say (Crouch)
end

Repeat N times

"Repeat N" loops the inner blocks N times โ€” handy for step-by-step motion, repeated drawing and playing a sound several times.

1
2
3
4
repeat (10)
move (5) steps
end
// 10 moves ร— 5 steps = 50 steps total

Forever loop

"Forever" never stops on its own; combine with the Stop block or a condition to exit. Sprite patrols and scrolling backgrounds belong inside it.

1
2
3
4
forever
move (10) steps
if on edge, bounce
end

Repeat until

"Repeat until ..." runs the body first, then tests the condition; once true it stops. Handy for waiting on a key press or for a target score.

1
2
3
4
repeat until <key (space v) pressed?>
wait (0.1) seconds
end
say (Finally pressed space!)

Wait

"Wait 1 second" pauses the current script; "Wait until" pauses until the condition holds. Note: waits only block the current script โ€” others keep running.

1
2
3
4
5
when green flag clicked
say (Ready)
wait (1) seconds
say (Go!)
wait until <(timer) > (10)>

Stop a script

"Stop all" ends every script; "Stop this script" stops only the current one; "Stop other scripts in sprite" keeps this script running but halts the rest of the sprite.

1
2
3
4
5
6
when green flag clicked
forever
if <(hp) < (1)> then
stop (all)
end
end

Combined logic

And, Or and Not combine conditions into one. And needs every piece true, Or needs at least one true, Not flips the result.

1
2
3
4
5
6
if <<key (w v) pressed?> or <key (up v) pressed?>> then
change y by (10)
end
if <<(score) > (0)> and <(score) < (100)>> then
say (Score is in range)
end

6.Custom Blocks (Functions)

Custom blocks wrap repeated code into reusable pieces with parameters and return values โ€” they are functions.

Make a block

In My Blocks click "Make a new block", give it a name and add parameters โ€” a Define block appears in the script area for you to fill in the logic.

1
2
3
4
define jump
change y by (50)
wait (0.2) seconds
change y by (-50)

With parameters

Add number or text inputs when defining a block; supply different values at each call site. Parameters are local variables โ€” they exist only inside the block.

1
2
3
4
5
6
7
define draw square (size)
repeat (4)
move (size) steps
turn right (90) degrees
end
draw square (50)
draw square (100)

Return a value

Custom blocks return nothing by default. To get a value back, store it in a variable and read the variable after the call.

1
2
3
4
define square (n)
set [result v] to ((n) * (n))
square (7)
say (join (Square of 7 is ) (result))

Call a custom block

Once defined, drop the call block wherever you need it โ€” each call runs the block's script once.

1
2
3
4
5
define greet (name)
say (join (Hello, ) (name))
when green flag clicked
greet (Cat)
greet (Dog)

Recursion

A custom block can call itself โ€” that's recursion. Scratch has a stack depth limit, so avoid very deep recursion and prefer loops.

1
2
3
4
5
6
define count (n)
if <(n) > (0)> then
say (n)
count ((n) - (1))
end
count (3)

Run without screen refresh

Check "Run without screen refresh" when editing a custom block and it executes in one shot โ€” perfect for bulk list math and fast calculations.

1
2
3
// Edit the define block > tick "Run without screen refresh"
define batch
// Heavy computation in the loop no longer redraws frame by frame

Parameter locality

Custom block parameters stay local, but variables created inside the block are global by default โ€” be careful not to collide with an outside variable of the same name.

1
2
3
define addScore (amount)
change [score v] by (amount) // modify the global variable
addScore (10)

Reuse and split

After lifting a chunk of logic into a custom block, you can reuse it across events โ€” scripts become cleaner and easier to debug.

1
2
3
4
5
6
7
define restart
set [score v] to (0)
switch backdrop to (menu)
when green flag clicked
restart
when I receive (lose)
restart

7.Strings

String operations: join, letter-of, length, contains โ€” supports simple text processing.

Join text

The Join block concatenates two pieces of text into one string โ€” handy for composing prompts and coordinates.

1
2
3
join (Hello, ) (Cat) // Hello, Cat
join (X=) (x position) // splice a number into text
say (join (Score:) (score))

Letter of

"Letter N of ..." returns the character at position N. Chinese characters each count as one, and so do spaces.

1
2
3
letter (1) of (Scratch) // S
letter (2) of (Scratch) // c
length of (Hello) // 5

Length of

"Length of ..." returns the character count โ€” English letters, Chinese characters and spaces each count as one. Useful for empty checks and input length caps.

1
2
3
4
5
length of (Scratch) // 7
length of (Hello world) // 11
if <(length of (answer)) > (10)> then
say (Too long!)
end

Contains check

"Contains" checks whether one string contains another and returns a boolean โ€” use it for keyword detection.

1
2
3
4
<(Scratch is fun) contains (fun)?> // true
if <(answer) contains (cat)> then
say (You like cats)
end

Find position

Combine "Letter N of" and "Length of" to manually search: walk character by character and return the position when matched.

1
2
3
4
5
6
7
set [pos v] to (0)
repeat (length of (text))
change [pos v] by (1)
if <(letter (pos) of (text)) = (target)> then
say (join (Found at: ) (pos))
end
end

Split into a list

Push each character of a string into a list to handle text character by character. Pair with Repeat for iteration.

1
2
3
4
5
6
delete (all) of [chars v]
set [i v] to (1)
repeat (length of (text))
add (letter (i) of (text)) to [chars v]
change [i v] by (1)
end

Empty string check

"Length = 0" means empty. When the user leaves the input box blank, the answer is an empty string โ€” check before using it.

1
2
3
4
5
6
ask (Enter your name) and wait
if <(length of (answer)) = (0)> then
say (Name cannot be empty)
else
say (join (Hello, ) (answer))
end

Concatenate long text

Scratch's text blocks are single-line; for long output stack several Join blocks. Commas and spaces are preserved as written.

1
say (join (Line 1, ) (join (Line 2, ) (Line 3)))

8.Lists and Data Structures

Lists are Scratch's core data structure โ€” add, delete, read, modify, traverse and simulate two-dimensional data.

Create a list

In the Variables category click "Make a List" โ€” it appears in the script pane like a variable. Lists on stage can be shown or hidden.

1
2
3
// Variables category > Make a List > Enter name: backpack
add (apple) to [backpack v]
show list [backpack v]

Add and delete

Add appends a new element to the end. Delete removes an entry by index (or delete all). After deletion the trailing indices shift down.

1
2
3
4
5
add (apple) to [backpack v]
add (shield) to [backpack v]
delete (1) of [backpack v]
// backpack = [shield]
delete (all) of [backpack v]

Read an element

"Item N of ..." reads by index starting at 1. Out-of-range indices don't error but return an empty result.

1
2
3
4
5
add (gold) to [chest v]
add (silver) to [chest v]
item (1) of [chest v] // gold
item (2) of [chest v] // silver
item (5) of [chest v] // empty

Replace an element

"Replace item N with ..." overwrites the value at that index; length is unchanged โ€” ideal for updating a single slot.

1
2
3
add (old potion) to [backpack v]
replace item (1) of [backpack v] with (new potion)
item (1) of [backpack v] // new potion

Insert an element

"Insert ... at N" places a new element at that position; subsequent elements shift right automatically.

1
2
3
4
add (apple) to [backpack v]
add (pear) to [backpack v]
insert (watermelon) at (2) of [backpack v]
// backpack = [apple, watermelon, pear]

Find an element

"... contains ..." tells you whether the list has that element and returns a boolean. Check first to avoid reading empties.

1
2
3
4
5
if <[backpack v] contains (key)> then
say (You have a key)
else
say (No key, go find one)
end

Iterate a list

Use "Repeat until" with an index variable to walk the list โ€” the typical pattern for simulating iteration.

1
2
3
4
5
set [i v] to (1)
repeat until <(i) > (length of [backpack v])>
say (item (i) of [backpack v])
change [i v] by (1)
end

Simulate 2D data

Lists are one-dimensional, but you can simulate a 2D grid by treating index = row * cols + col โ€” useful for maps and boards.

1
2
3
4
// 4 rows ร— 3 cols grid, cell IDs 1-12
set [id v] to (((row) * (3)) + (col))
add (cell value) to [map v]
item (id) of [map v]

9.Project and Resource Management

Manage sprite count, list size and clone limit; optimize performance to avoid lag.

Clone limit

Each project allows at most 300 clones at the same time. Surpassing the limit silently deletes the oldest clones.

1
2
3
4
5
6
// Clone limit is 300 โ€” avoid infinite cloning
when green flag clicked
set [count v] to (0)
repeat (10)
create clone of (myself)
end

List size control

Unbounded lists slow the project down. Delete old data in time, or cap the list at a maximum length.

1
2
3
4
add (new score) to [scores v]
if <(length of [scores v]) > (100)> then
delete (1) of [scores v]
end

Sprite count

More sprites mean more work per frame. For many objects of the same kind, prefer clones over duplicate sprites.

1
2
3
4
5
// 50 enemies: 1 sprite + clone 50 times โ€” faster than 50 separate sprites
when green flag clicked
repeat (50)
create clone of (enemy)
end

Broadcast storm

Broadcasting often (e.g. every frame) restarts every receiver every frame and tanks performance. Only broadcast when something actually changes.

1
2
3
4
5
// Don't spam broadcasts inside forever
// Only broadcast when the position actually changes
if <not <(x position) = (lastx)>> then
broadcast (position)
end

Variable caching

Store the result of repeated calculations in a variable so you don't recompute it. Pre-compute values used in many places.

1
2
3
4
5
// Compute once, reuse many times
set [dist v] to ((x position) - (targetx))
if <(dist) < (50)> then
say (Almost there)
end

Sprite list management

The sprite list in the bottom-right of the stage lists every sprite. Drag to reorder; right-click to duplicate, export or delete.

1
2
// Right-click a sprite thumbnail > duplicate / export / delete
// Duplicated sprites carry the same scripts โ€” change the costume to make a new one

Performance tuning

Reduce per-frame redraws, avoid massive list math, cap clones and particles โ€” your project becomes smoother.

1
2
3
4
5
6
7
// Reduce flicker: hide the sprite, move in bulk, then show
hide
repeat (20)
change x by (5)
end
show
// Put heavy computation in a custom block with "Run without screen refresh"

Costume and sound assets

Every costume and sound is an asset โ€” the more you have, the bigger and slower to load. Drop unused ones and compress images before importing.

1
2
// Delete unused costumes and sounds to shrink the .sb3 file
// Compress images before importing to reduce load time

10.Sprites as Objects

Each sprite is an object: it carries its own variables and scripts, and clones are instances of it.

Sprite is an object

A sprite packages costumes, variables and scripts โ€” it is a small object. The stage acts as a global container.

1
2
3
4
// Sprite "cat": variable name + script
when green flag clicked
set [name v] to (Cat)
say (join (Hello, ) (name))

Clone is an instance

Clones are copy-instances of the sprite. They share costumes and any non-sprite-only scripts, but each has its own position, size and private variables.

1
2
3
4
5
6
when green flag clicked
repeat (3)
create clone of (myself)
end
when I start as a clone
go to x: (pick random (-200) to (200)) y: (0)

Broadcast is a method call

A broadcast is a message sent to other "objects"; the receiver block handles it โ€” much like a method call in OOP.

1
2
3
4
5
when this sprite clicked
broadcast (hurt)
when I receive (hurt)
say (Ouch!)
change [hp v] by (-1)

Private attribute

A "For this sprite only" variable is a private field of the object. Each clone has its own copy, independent of the others.

1
2
3
4
5
6
when green flag clicked
set [id v] to (1)
create clone of (myself)
when I start as a clone
set [id v] to (2) // only this clone is changed
say (id)

Clone reuse

Cloning a sprite gives you the same "template"; tweak the script or variables to derive instances with different behavior โ€” much like inheritance.

1
2
3
4
5
6
7
// Clone the enemy template โ†’ give each a different speed
when I start as a clone
set [speed v] to (pick random (1) to (5))
forever
move (speed) steps
if on edge, bounce
end

State and behavior

Object state lives in variables; behavior lives in scripts. Branch on a state variable to switch between behaviors.

1
2
3
4
5
6
7
8
9
if <(state) = (patrol)> then
move (5) steps
if on edge, bounce
else
if <(state) = (chase)> then
point towards (player)
move (8) steps
end
end

Event-driven model

Scratch is event-driven: the green flag, keys, clicks and messages each trigger scripts. There's no main function โ€” execution begins with events.

1
2
3
4
5
6
7
8
when green flag clicked
startGame
when this sprite clicked
playSfx
when key (space v) pressed
jump
when I receive (levelup)
nextLevel

Message passing

Sprites don't access each other's variables directly; they cooperate via broadcasts plus shared variables โ€” keeps coupling loose.

1
2
3
4
5
6
7
// Player scores โ†’ broadcast to the scoreboard sprite
when this sprite clicked
change [score v] by (1)
broadcast (scoreFX)
// Scoreboard sprite receives
when I receive (scoreFX)
set [display v] to (score)

11.Debugging and Error Handling

Scratch has no exception mechanism โ€” find bugs by watching variables, using the Say block, and bounds checks.

No exception mechanism

Scratch doesn't throw โ€” buggy code just silently misbehaves. Pre-check data and defend against bad values.

1
2
3
// No errors are thrown โ€” only strange results
// Out-of-bounds list reads return empty, comparisons may always be false
// Validating data up front is the only defense

Watch a variable

Right-click a variable display on the stage to choose normal read-out, large read-out, slider or hide โ€” useful for watching values live.

1
2
3
4
// Right-click the variable watcher on the stage:
// normal / large readout / slider / hide
set [score v] to (0)
change [score v] by (1)

Debug with the Say block

Drop a "say (some variable)" block at a suspicious spot to print intermediate values while you debug โ€” remove it afterwards.

1
2
3
define computeScore
set [total v] to ((a) + (b))
say (total) // temporary debug output

Bounds check

Before reading a list item, check the index is in range to avoid empties. Valid range is 1 to length.

1
2
3
4
5
if <<(i) > (0)> and <(i) <= (length of [backpack v])>> then
say (item (i) of [backpack v])
else
say (Index out of range)
end

Empty check

When the answer or a list slot is empty, test first before using it โ€” otherwise you'll get odd results from arithmetic.

1
2
3
4
5
if <(length of [backpack v]) = (0)> then
say (Backpack is empty)
else
say (item (1) of [backpack v])
end

List out of bounds

List indices start at 1, and after deletion the indices shift. Using "length" as the upper bound keeps you in range.

1
2
3
4
5
delete (1) of [backpack v]
// After deletion the old index 2 becomes index 1
if <(i) > (length of [backpack v])> then
set [i v] to (length of [backpack v])
end

Step-by-step debugging

Break a large script into smaller ones and test each piece, or use Wait blocks to slow it down and watch each step.

1
2
3
4
5
6
when green flag clicked
init
wait (0.5) seconds // slow down to observe
computeScore
wait (0.5) seconds
showResult

Common error checklist

Most bugs come from uninitialized variables, reversed conditions, out-of-range indices or unmatched broadcasts. Walk through the checklist.

1
2
3
4
5
// Check that variables are set before being read
// Check that comparisons face the right direction
// Check that list indices are within range
// Check that broadcast and receive names match exactly
// Check that clone count has not exceeded the limit

12.Input and Output

Read keyboard, mouse and Q&A with sensing blocks; output with say, costumes and backdrops; persist data with cloud variables.

Keyboard input

"Key ... pressed?" detects whether a key is held down. Pair with a loop for continuous motion; pair with a one-shot check for jumping.

1
2
3
4
5
6
7
8
forever
if <key (right v) pressed?> then
change x by (5)
end
if <key (left v) pressed?> then
change x by (-5)
end
end

Mouse input

Read the mouse pointer position and click state so a sprite can follow the mouse or respond to clicks.

1
2
3
4
5
6
7
8
forever
go to (mouse-pointer)
if <mouse down?> then
set size to (120) %
else
set size to (100) %
end
end

Ask and answer

"Ask ... and wait" pops up an input box; the user's response lands in the Answer block โ€” always a string.

1
2
3
4
ask (What's your name?) and wait
say (join (Hello, ) (answer))
ask (How old are you?) and wait
set [age v] to (answer)

Touch sensing

Detect whether the sprite is touching the mouse pointer, another sprite or a color โ€” used for collision and pickup logic.

1
2
3
4
5
6
7
8
forever
if <touching (enemy v)?> then
change [hp v] by (-1)
end
if <touching (mouse-pointer v)?> then
say (You got me)
end
end

Sensing value output

x position, y position, direction, loudness, timer โ€” all readable as sensing values that you can drop straight into operators.

1
2
3
say (join (x=) (x position))
say (join (y=) (y position))
say (loudness) // microphone loudness 0-100

Broadcast output

Broadcasts synchronize actions between sprites โ€” they're the main inter-sprite output channel, and receivers react.

1
2
3
4
5
when this sprite clicked
broadcast (opendoor)
when I receive (opendoor)
switch costume to (door-open)
play sound (click v)

Cloud variable storage

Cloud variables store numbers on the server so every player shares them โ€” ideal for high scores and online stats.

1
2
3
4
when green flag clicked
if <(score) > (โ˜ highscore)> then
set [โ˜ highscore v] to (score)
end

On-screen output

Say/Think show text, costume switches show images, play sound outputs audio โ€” combine them for feedback.

1
2
3
4
5
6
when this sprite clicked
say (Roar!) for (1) seconds
play sound (growl v)
switch costume to (mouth-open)
wait (0.3) seconds
switch costume to (mouth-closed)

13.Common Pitfalls

The eight pitfalls beginners hit most often โ€” BAD shows the wrong way, GOOD shows the right way.

Forever loop stuck

Putting a Wait inside a Forever with an unsatisfiable condition freezes the script. Make sure the loop body actually advances the condition.

1
2
3
4
5
6
7
8
// BAD: waiting for a condition that can never become true
forever
wait until <(x position) > (1000)>
end
// GOOD: advance the condition inside the loop, or let it exit
repeat until <(x position) > (240)>
change x by (5)
end

Broadcast timing

Broadcasts are async โ€” the sender keeps going immediately while receivers start in parallel. Use "Broadcast and wait" when you need strict ordering.

1
2
3
4
5
6
// BAD: reading the receiver's value right after broadcasting โ€” not updated yet
broadcast (startAnim)
say (anim done)
// GOOD: use "broadcast and wait" so the receiver finishes first
broadcast (startAnim) and wait
say (anim done)

Clone variable mix-up

Global variables are shared across clones, so changing one changes them all. To tell clones apart, use "For this sprite only" privates.

1
2
3
4
5
6
7
8
9
// BAD: using a global counter โ€” every clone reads the same value
set [id v] to (0)
repeat (3)
change [id v] by (1)
create clone of (myself)
end
// GOOD: private variables are copied to each clone at clone time
when I start as a clone
say (id)

Wait never satisfied

When "wait until" depends on a condition set by another script, that other script may not be running. Make sure something flips the condition.

1
2
3
4
5
// BAD: the condition can only be changed by a stopped script
wait until <(loaded) = (1)>
// GOOD: wait for an event instead of polling a variable
when I receive (loaded)
say (Loaded)

Empty value in calculation

An empty answer or list element participates in comparisons and math as false or weird values. Check length first.

1
2
3
4
5
6
7
8
9
10
11
ask (Enter a number) and wait
// BAD: empty input compared as number is always false
if <(answer) > (10)> then
say (>10)
end
// GOOD: check for empty first
if <(length of (answer)) > (0)> then
say (join (You entered ) (answer))
else
say (You didn't enter anything)
end

List index out of range

List indices start at 1 and max out at length. Using 0 or a too-large index gives nothing and is a common source of bugs.

1
2
3
4
5
6
7
add (apple) to [backpack v]
// BAD: index 0 or an index way past the length
say (item (0) of [backpack v])
say (item (9) of [backpack v])
// GOOD: use an index within 1..length
say (item (1) of [backpack v])
say (item (length of [backpack v]) of [backpack v])

Costume name mismatch

When switching costumes the name must match the costume panel exactly โ€” an extra space or missing character and the switch silently fails.

1
2
3
4
// BAD: extra space in the costume name โ€” switch has no effect
switch costume to (costume2 )
// GOOD: costume name must match the panel exactly
switch costume to (costume2)

Recursion too deep

Scratch caps recursion depth โ€” go too deep and the program silently halts or misbehaves. Prefer loops to deep recursion.

1
2
3
4
5
6
7
8
9
// BAD: deep recursion can blow past Scratch's stack limit
define countTo (n)
countTo ((n) + (1))
countTo (0)
// GOOD: count with a loop โ€” no depth limit
set [n v] to (0)
repeat (10000)
change [n v] by (1)
end

14.Multiple Scripts and Concurrency

Multiple event-driven scripts run in parallel; coordinate their order with broadcasts and waits.

Parallel scripts

A single sprite can have several independent scripts that each start from their own event and run in parallel without waiting.

1
2
3
4
5
6
7
8
9
10
when green flag clicked
forever
move (5) steps
if on edge, bounce
end
when green flag clicked
forever
play sound (beat v)
wait (1) seconds
end

Events are threads

Each event โ€” green flag, key, click, message โ€” starts a dedicated script, equivalent to a thread.

1
2
3
4
5
6
when green flag clicked
say (Started)
when key (space v) pressed
say (Space pressed)
when this sprite clicked
say (Clicked)

Shared variable

All scripts share global variables. When several scripts write the same variable concurrently, updates can clobber each other.

1
2
3
4
5
6
7
when green flag clicked
forever
change [score v] by (1)
wait (0.1) seconds
end
when this sprite clicked
change [score v] by (10)

Race condition

Two scripts doing read-modify-write on the same variable can drop updates. Keep critical update sequences inside a single script.

1
2
3
// Two scripts changing the same variable at once
// The read โ†’ add โ†’ write sequence can interleave
// Fix: keep critical counters in a single script

Broadcast sync order

"Broadcast and wait" blocks the sender until every receiver finishes โ€” useful for sequencing animated acts.

1
2
3
broadcast (act1) and wait
broadcast (act2) and wait
broadcast (act3) and wait

Stop a thread

The Stop block ends targeted scripts: all, this script, or other scripts in this sprite โ€” handy for reset.

1
2
3
4
5
when green flag clicked
broadcast (restart)
when I receive (restart)
stop (other scripts in sprite)
set [score v] to (0)

Coordinating sprites

When many sprites move in parallel, use a shared variable plus waits to march them in step or in order.

1
2
3
4
5
6
7
when green flag clicked
set [signal v] to (0)
when I receive (go)
set [signal v] to (1)
when green flag clicked
wait until <(signal) = (1)>
say (Start moving)

Single-thread cooperation

Even with parallel scripts, each script still runs blocks one at a time in order. A long loop blocks other scripts of the same sprite.

1
2
3
4
5
// A long loop in one script blocks the sprite's other scripts
// Use broadcasts to split work across separate events
repeat (100)
heavyCompute
end

15.Networking and Extensions

Cloud variables share project data across the network, and extensions add online features like translation and TTS.

Cloud variable networking

Cloud variables sync numbers to the server in real time, so users running the same project share data โ€” great for leaderboards and simple battles.

1
2
3
4
5
// When creating a variable, tick "Cloud variable" (numbers only)
when green flag clicked
if <(score) > (โ˜ highscore)> then
set [โ˜ highscore v] to (score)
end

Translate extension

The Translate extension calls an online translation service and returns the translated string.

1
2
3
// Add extension > Translate
say (translate (Hello) to (English v))
say (translate (Hello) to (Chinese v))

Text to speech

The Text-to-Speech extension reads text aloud with selectable languages and voices โ€” it needs an online voice service.

1
2
3
// Add extension > Text to Speech
speak (Welcome to my game)
set voice to (Kitten v)

Video sensing

The Video Sensing extension uses the webcam to detect motion, so players can control sprites by waving. The first use prompts for camera permission.

1
2
3
// Add extension > Video Sensing
when video motion > (50)
say (Motion detected!)

Share to the website

Click "Share" in the top-right to publish your project to the Scratch site โ€” anyone can play, like and comment on it.

1
2
// Sign in โ†’ click "Share" in the top right
// Once published, copy the link to share with friends

Remix

Use the "Remix" button on a project to copy someone else's work and tweak it โ€” the original author is credited.

1
2
// Open someone's project โ†’ click "See inside" then Remix
// After remixing, edit scripts and share โ€” it becomes your work

Cloud variable limits

Cloud variables are limited: each project gets only so many, values are numeric and short, and rapid updates may be throttled.

1
2
3
4
// Each project has a limit on cloud variables
// Cloud variables hold numbers only, no text
// Frequent updates are throttled by the server
// Sign in is required before using cloud variables

Online safety and privacy

Online projects are publicly shared. Don't put your real name, address, phone number or other personal info into them.

1
2
3
// Don't reveal real identity info in your projects
// Don't download or run suspicious files from strangers
// Use a pseudonym to protect your privacy

16.Time and Timing

Use the timer, wait blocks and days-since-2000 for countdowns, stopwatches and timed levels.

Timer

"Timer" starts counting when the project starts, returns seconds (with decimals) โ€” the heart of stopwatch and countdowns.

1
2
3
4
5
when green flag clicked
say (Timer)
forever
say (join (Elapsed: ) (timer))
end

Reset timer

"Reset timer" zeroes the timer โ€” start a new timing run.

1
2
3
4
when green flag clicked
reset timer
wait (5) seconds
say (join (Took: ) (timer))

Days since 2000

"Days since 2000" returns the number of days since 2000-01-01 โ€” useful for cross-day timing or recording "last opened".

1
2
say (days since 2000)
// Returns days with decimals, e.g. 9678.5 means half a day

Wait seconds

"Wait N seconds" pauses the current script for N seconds โ€” used for timing, delays and animation frame pacing.

1
2
3
4
5
when green flag clicked
say (3) for (1) seconds
say (2) for (1) seconds
say (1) for (1) seconds
say (Liftoff!)

Countdown

Use the timer plus subtraction for a countdown; broadcast the end event when it hits zero.

1
2
3
4
5
6
7
8
9
10
when green flag clicked
set [remaining v] to (30)
forever
set [remaining v] to ((30) - (timer))
if <(remaining) < (0)> then
set [remaining v] to (0)
broadcast (timeup)
stop (this script)
end
end

Stopwatch

Measure an operation's duration with the difference between two timer reads โ€” great for reaction-time games.

1
2
3
4
5
when green flag clicked
wait until <key (space v) pressed?>
reset timer
wait until <key (space v) pressed?>
say (join (Your reaction: ) (join (timer) ( s)))

Timed level

Complete the level within a fixed time, or fail. Combine the countdown with the win condition.

1
2
3
4
5
6
7
8
9
10
11
when green flag clicked
set [countdown v] to (10)
repeat until <(countdown) < (1)>
wait (1) seconds
change [countdown v] by (-1)
if <(passed) = (1)> then
say (Cleared!)
stop (this script)
end
end
say (Time's up!)

Timer-based animation

Drive animations from the timer instead of the frame rate โ€” so speed stays consistent across machines.

1
2
3
4
forever
go to x: ((timer) * (100)) y: (0)
end
// Sprite moves at constant speed by time, independent of machine speed

17.Script Lifecycle

Scripts are Scratch's smallest execution unit โ€” understanding how they start, run and stop is understanding the whole project.

Script as a procedure

A script that starts at an event block and ends at its tail is a small procedure. Many scripts together form the whole program.

1
2
3
when green flag clicked // entry point
say (Step one)
say (Step two) // runs in order

Green-flag start

The green flag is the canonical entry point โ€” clicking it starts every green-flagged script at once, like a main function.

1
2
3
when green flag clicked
initAllVariables
showStartScreen

Event handler

An event block is the script's "hat" โ€” it only runs when triggered. With no hat, a script never starts on its own.

1
2
3
4
5
6
when key (space v) pressed
jump
when this sprite clicked
greet
when I receive (pass)
next backdrop

Atomic execution

With "Run without screen refresh" checked, a custom block executes to completion in one go without rendering โ€” perfect for batch computation.

1
2
3
define heavyCompute
// Tick "Run without screen refresh"
// Finishes in one frame โ€” no per-block redraws

Parallel lifecycle

Each script starts and stops on its own. The Stop block gives you fine-grained control: all, this script or other scripts in this sprite.

1
2
3
4
5
6
when green flag clicked
mainLoop
when I receive (pause)
stop (other scripts in sprite)
when I receive (resume)
mainLoop

Scope of stop

"Stop this script" affects only the current one; "Stop other scripts in sprite" halts the rest of this sprite's scripts; "Stop all" clears the stage.

1
2
3
stop (this script)
stop (other scripts in sprite)
stop (all)

State-machine procedure

Use a variable to record the current state and have the script branch on it โ€” implement menus, gameplay, end screens and the transitions between them.

1
2
3
4
5
6
7
if <(scene) = (menu)> then
switch backdrop to (menu-bg)
else
if <(scene) = (playing)> then
switch backdrop to (game-bg)
end
end

Project lifecycle

A project goes from asset loading, through a green-flag start, through runtime, to the red stop button, and then save/share โ€” the full lifecycle.

1
2
3
4
5
// Load: read costumes, sounds, variables
// Start: click the green flag, scripts begin
// Run: events and loops keep firing
// Stop: click the red stop button to halt everything
// Save: auto-save or download the .sb3 manually

18.Text Pattern Matching

Scratch has no regex โ€” use contains, character checks and list splits for simple pattern matching.

No regex

Scratch has no regex blocks. Complex text matching must be hand-built with operator blocks or offloaded to an extension.

1
2
// Scratch has no regex
// Implement with "contains", "letter N of", and similar blocks

Contains match

The "contains" check is the simplest substring match โ€” does the text contain a given word?

1
2
3
if <(line) contains (danger)> then
say (Danger word found!)
end

Starts-with check

Read the first character and test it to do a starts-with check โ€” basic prefix detection.

1
2
3
if <(letter (1) of (cmd)) = (j)> then
say (Run jump command)
end

Ends-with check

Read the last character (index = length) to test the ending โ€” basic suffix detection.

1
2
3
if <(letter (length of (cmd)) of (cmd)) = (!)> then
say (Strong tone)
end

Character class

To check whether a single character is a digit or letter, make a digit table and query it with "contains".

1
2
3
4
// digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
if <[digits v] contains (letter (i) of (text))> then
say (It's a digit)
end

Pattern search

Scan the text character by character in a loop to find matches โ€” e.g. extract a run of digits.

1
2
3
4
5
6
7
set [i v] to (1)
repeat (length of (text))
if <[digits v] contains (letter (i) of (text))> then
say (join (Found digit ) (letter (i) of (text)))
end
change [i v] by (1)
end

Split and parse

Split a text by delimiter into a list and process each piece โ€” a simple parser.

1
2
3
4
5
6
7
8
9
10
11
set [i v] to (1)
repeat (length of (text))
if <(letter (i) of (text)) = (,)> then
add (current) to [parts v]
set [current v] to ()
else
set [current v] to (join (current) (letter (i) of (text)))
end
change [i v] by (1)
end
add (current) to [parts v]

Wildcard simulation

Combine "contains" with multiple OR branches to simulate wildcards โ€” e.g. match against a list of keywords.

1
2
3
if <<(text) contains (begin)> or <(text) contains (end)>> then
say (Keyword matched)
end

19.Saving, Publishing and Debugging

Save, export, share projects and debug them โ€” make your creations smoother and more playable.

Save project

When you're signed in, projects auto-save to the cloud. Use File โ†’ Save to your computer to download a backup.

1
2
3
4
// Auto-saves to the cloud once you're signed in
// File > Save to your computer to back up the .sb3
when green flag clicked
say (Don't worry, already auto-saved)

.sb3 file format

Project files end in .sb3 โ€” they're a zip containing project.json plus costume, sound and other assets, and they open offline.

1
2
3
// .sb3 is a zip archive
// Inside are project.json and asset files
// Double-click an .sb3 to open the project offline

Share and publish

Click "Share" in the top-right to publish โ€” set a title, instructions and tags to help people find it.

1
2
3
// Pick a fun project title
// Write clear instructions and add relevant tags
// Click "Share" to publish, then copy the link for friends

Remix and rebuild

Remixing someone else's project is a great learning starting point โ€” tweak scripts and add levels, then publish your own version.

1
2
3
// Open the project โ†’ click "Remix"
// Edit scripts and costumes, then share
// Credit the original author and follow community rules

Debug tools

Locate bugs with variable watchers, the Say block, and slowed-down waits โ€” verify scripts segment by segment.

1
2
3
// Watch suspicious variables to see live values
// Temporarily add say blocks to print intermediate results
// Add wait blocks to slow down and observe each step

Backup and versions

Download .sb3 files locally for backups and rename to keep multiple versions โ€” if you break something, roll back.

1
2
// Periodically download .sb3 backups for important projects
// Use "Save as" to keep multiple versions

Pre-publish checklist

Before publishing, test every entry point โ€” green flag, keys, sprite clicks, broadcasts โ€” and confirm no infinite loops, no out-of-range errors and smooth rendering.

1
2
3
// Test: green flag, space key, sprite click, receiving broadcast
// Check: loops can exit, list indices stay in range
// Check: clones stay under the limit, animation is smooth

Keep learning

Learn more from the official tutorials, the Scratch Wiki and community projects โ€” keep iterating on your work.

1
2
3
// Official tutorials: "Ideas" section on scratch.mit.edu
// Scratch Wiki: en.scratch-wiki.info
// Explore the community's great projects โ€” learn by playing

Official Links

Direct links to the official docs and resources.

About this Cheatsheet

Scratch is a free visual programming language developed by MIT's Media Lab, designed for learners aged 5โ€“16. It replaces typed code with snap-together blocks: drag Motion, Looks, Sound, Events, Control, Sensing, Operators, Variables and My Blocks into the script area to make sprite animations, interactive games and creative stories. This page is a self-contained Scratch 3 cheatsheet covering roughly 80% of what beginners meet when building games, animations and stories. The 19 chapters each focus on a single topic โ€” your first program (hello), variables and data storage (vars / types / pointers), control flow (control), custom blocks (funcs), strings and lists (strings / collections), project and asset management (mem), the sprite object model (oop), debugging and common pitfalls (errors / faq), I/O and concurrent scripts (io / threads), cloud variables and extensions (net), time and timing (time), script lifecycle (proc), text pattern matching (regex) and saving/publishing/debugging (build). Each section splits into 8 topics with snippets of 5โ€“20 lines each, easy to read and copy. Unlike other programming languages, Scratch has no textual syntax โ€” here the blocks are shown in their readable text form, convenient for offline reference and recall. Everything is rendered locally in your browser โ€” nothing is uploaded or tracked, and your privacy is safe. This page is part of GuruToolkit's free developer toolset; the snippets here are free to use, with no warranty.

Version 2.1.0