0% found this document useful (0 votes)
24 views34 pages

Scratch Programming F

Scratch is a block-based visual programming language designed to introduce programming concepts to beginners through a drag-and-drop interface. It encompasses fundamental programming concepts such as sequencing, loops, conditionals, and variables, allowing users to create animations, games, and interactive stories. The Scratch environment includes various components like the stage, sprites, and blocks palette, facilitating an engaging learning experience.

Uploaded by

Dhruvesh Ari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views34 pages

Scratch Programming F

Scratch is a block-based visual programming language designed to introduce programming concepts to beginners through a drag-and-drop interface. It encompasses fundamental programming concepts such as sequencing, loops, conditionals, and variables, allowing users to create animations, games, and interactive stories. The Scratch environment includes various components like the stage, sprites, and blocks palette, facilitating an engaging learning experience.

Uploaded by

Dhruvesh Ari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

CS25C03 -Essentials of Computing

Module-V
SCRATCH PROGRAMMING

What is Scratch, Scratch Programming Environment, Paint Editor, Scratch Blocks,


Arithmetic Operators and Functions, Use Motion Commands, Pen Commands and
Easy Draw, Looks Palette, Sound Palette, Power of Repeat, Data Types, Variables,
Getting Input from Users.
Module :5

Scratch Programming

Introduction to Scratch

Scratch is a block-based visual programming language created by the MIT Media Lab. It is
widely used as an educational tool to introduce children and beginners to computer
programming. Unlike traditional programming languages (such as C, Python, or Java), Scratch
does not require typing code. Instead, it uses a drag-and-drop interface with colorful blocks
that snap together like puzzle pieces.

The goal of Scratch is to make learning programming concepts fun, interactive, and
intuitive. With Scratch, learners can create stories, animations, games, and music while
simultaneously developing problem-solving skills and logical thinking.

Scratch is especially powerful because:

• It eliminates syntax errors (common in text-based coding).

• It uses visuals, making it easier to grasp abstract concepts.

• It promotes creativity and collaboration through its online community.

2. Scratch Programming Concepts

Scratch introduces almost all the fundamental programming concepts found in traditional
languages, but in a visual, simplified form:

1. Sequencing – Placing blocks in order to define the flow of instructions.

o Example: Making a sprite move forward 10 steps, then say “Hello” for 2 seconds.

2. Loops (Iteration) – Repeating a set of instructions.

o Example: Making a ball bounce continuously by repeating the "move and turn"
blocks forever.

3. Conditionals (Decision-making) – Performing actions based on conditions.

o Example: If the sprite touches the edge of the stage, it turns around.

4. Variables – Storing and updating data values.

o Example: A variable “score” keeps track of points in a game.

5. Events – Triggering scripts based on user actions or other signals.

Dr.T.Premkumar
o Example: Starting the program when the green flag is clicked or when the space
key is pressed.

6. Parallelism – Running multiple scripts at the same time.

o Example: A sprite moving while also playing music.

These concepts make Scratch a gateway language to text-based programming.

3. Scratch Programming Environment

The Scratch environment is graphical and interactive, with several key components.

3.1 Stage

• The Stage is the main output screen where all animations, interactions, and games take
place.

• Size: 480 × 360 pixels by default.

• It can display backgrounds (like scenery in a story or game).

• Sprites move and interact within the stage.

Example: In a racing game, the stage could be a road image, while cars (sprites) move on top of
it.

3.2 Sprites

• Sprites are characters or objects in Scratch.

• Each sprite can have:

o Costumes – Different appearances for animations.

o Scripts – Programs that control sprite behavior.

o Sounds – Music or effects attached to the sprite.

Example: A cat sprite can have costumes to show walking or running movements.

3.3 Blocks Palette

This is the toolbox of Scratch. It contains all the programming blocks, categorized by function.

• Motion Blocks – Control movement (move, turn, go to x,y).

Dr.T.Premkumar
ASP/ME
o Example: move 10 steps, turn 15 degrees.

• Looks Blocks – Control appearance.

o Example: say "Hello!" for 2 seconds, change color effect.

• Sound Blocks – Add sound effects or music.

o Example: play sound "meow" until done.

• Events Blocks – Start actions based on triggers.

o Example: when green flag clicked, when space key pressed.

• Control Blocks – Add loops and conditions.

o Example: repeat 10, if...then.

• Sensing Blocks – Detect interactions.

o Example: touching mouse-pointer?, ask "What is your name?".

• Operators Blocks – Perform math and logic operations.

o Example: pick random 1 to 10, (x > y).

• Variables & My Blocks – Store values and create custom blocks.

o Example: set score to 0, change score by 1.

3.4 Scripts Area

• The workspace where blocks are dragged and snapped together to form scripts.

• Programs are built visually like stacking puzzle pieces.

Example:
To make a sprite move when the green flag is clicked:

when green flag clicked

move 10 steps

say "Hello!" for 2 seconds

3.5 Toolbar and Menus

• Options for saving and loading projects.

• Access to tutorials and Scratch community.


Dr.T.Premkumar
ASP/ME
• Language settings.

4. Example Programs in Scratch

Example 1: Simple Animation

Goal: Make a cat sprite walk and say “Hello!”

Script:

when green flag clicked

move 10 steps

say "Hello!" for 2 seconds

SCRATCH PAINT EDITOR

The Paint Editor in Scratch is a tool used to create, modify, and customize costumes and
backdrops for sprites and stages. Costumes define how a sprite looks, and multiple costumes
can be used to create animations.

Features of Paint Editor

• Vector and Bitmap Modes

o Vector: Shapes and images that can be scaled without losing quality.

o Bitmap: Pixel-based editing for detailed pixel art.

• Drawing Tools

o Brush – Draw freehand lines.

o Line Tool – Draw straight lines.

o Rectangle/Ellipse Tool – Draw shapes.

o Fill Tool (Bucket) – Fill an area with color.

o Text Tool – Add text to a costume.

o Eraser Tool – Remove parts of the image.

o Select Tool – Select, resize, or rotate objects.

• Color Palette

o Provides fill and outline colors, including transparency.


Dr.T.Premkumar
ASP/ME
• Layering

o Objects can be arranged in layers (front, back).

Example

Suppose you want to animate a walking cat:

• Costume 1: Cat standing.

• Costume 2: Cat with left leg forward.

• Costume 3: Cat with right leg forward.


By switching costumes in a loop, you simulate walking.

2. Scratch Blocks

Scratch programs are built using blocks. These blocks are color-coded and shaped to fit
together like puzzle pieces. Each category of blocks represents a type of action or control.

Categories of Scratch Blocks

Category Block Examples Purpose


Color

Motion Blue move 10 steps, go to x: y: Move sprites around the stage.

Looks Purple say "Hello!", change color effect Control appearance and
speech.

Sound Pink play sound "meow", stop all Play sounds or music.
sounds

Events Yellow when green flag clicked, when Start actions on triggers.
key pressed

Control Orange repeat 10, if then, forever Loops, waits, conditions.

Sensing Light Blue touching sprite?, mouse x Detect interactions with


stage/sprites.

Operators Green +, -, pick random 1 to 10 Arithmetic and logic


operations.

Variables Dark set score to 0, change lives by -1 Store and change data.
Orange

Dr.T.Premkumar
ASP/ME
My Red define jump Custom reusable blocks.
Blocks

3. Arithmetic Operators in Scratch

Arithmetic operators are found in the Operators Block category (Green). They are used to
perform mathematical calculations and logical operations.

Types of Arithmetic Operators

Operator Block Example Meaning Example in Use

Addition (+) (5 + 3) Adds two numbers say (score + 10) →


displays score+10

Subtraction (-) (10 - 4) Subtracts second number set lives to (lives - 1)


from first

Multiplication (6 * 2) Multiplies two numbers change score by (2 * level)


(*)

Division (/) (20 / 5) Divides first number by set speed to (distance /


second time)

Random (pick random 1 Generates random go to x:(pick random -200


to 10) number in range to 200)

Example Program

• Game Dice Simulation

when green flag clicked

set dice to (pick random 1 to 6)

say dice for 2 seconds

Here, the random operator simulates rolling a dice.

Table: Comparison of Operators in Scratch vs. Traditional Programming

Operation Scratch Representation Python Equivalent

Addition (a + b) a+b

Subtraction (a - b) a-b

Dr.T.Premkumar
ASP/ME
Multiplication (a * b) a*b

Division (a / b) a/b

Random pick random 1 to 10 random.randint(1,10)

4. Functions in Scratch (My Blocks)

Functions in Scratch are represented using “My Blocks”. These are custom-defined blocks that
allow users to create reusable sets of instructions.

Steps to Create a Function (My Block)

1. Go to the My Blocks category.

2. Click “Make a Block”.

3. Give it a name (e.g., “jump”).

4. Add parameters (optional, such as size, speed).

5. Define what the block does in the script area.

Example 1: Jump Function

define jump

change y by 50

wait 0.2 seconds

change y by -50

• Any sprite that calls jump will move up and then come down.

Example 2: Function with Parameter

define move steps (n)

repeat (n)

move 10 steps

end

• Calling move steps (5) makes the sprite move 50 steps.

Advantages of Functions (My Blocks)

Dr.T.Premkumar
ASP/ME
• Code reusability (no repeating scripts).

• Readability (programs are easier to understand).

• Modularity (breaking a big program into smaller functions).

MOTION COMMANDS IN SCRATCH

Motion commands are part of the Motion Block category (blue blocks) in Scratch. They
control how a sprite moves and rotates on the stage. Motion commands work with x and y
coordinates of the stage.

• The Stage is a 2D plane:

o X-axis: -240 (left) to +240 (right)

o Y-axis: -180 (bottom) to +180 (top)

o Center: (0,0)

Common Motion Commands

Command Function Example

move (10) steps Moves the sprite forward by given Cat moves 10 steps
steps in current direction. forward.

turn clockwise (15) Rotates sprite clockwise. Cat rotates right 15°.
degrees

turn counter-clockwise Rotates sprite left. Cat rotates left 15°.


(15) degrees

go to x: (0) y: (0) Moves sprite to specific position. Teleports sprite to


center of stage.

glide (1) secs to x: (50) y: Smoothly moves sprite to position in Cat glides to (50,50) in
(50) given seconds. 1 second.

point in direction (90) Makes sprite face specific direction. Cat faces right.

if on edge, bounce Makes sprite bounce off stage edges. Used in ball games.

Example 1: Sprite Moves in a Square

when green flag clicked


Dr.T.Premkumar
ASP/ME
repeat 4

move 100 steps

turn clockwise 90 degrees

end

➡ The sprite draws a square path by moving forward and turning right 90° four times.

2. Pen Commands in Scratch

Pen commands are available through the Pen Extension. They allow a sprite to draw on the
stage as it moves, similar to “turtle graphics” in Logo programming.

Main Pen Commands

Command Function Example

pen down Lowers the pen, sprite draws as it Sprite leaves a trail when
moves. moving.

pen up Lifts the pen, sprite moves without Sprite moves invisibly.
drawing.

set pen color to [ ] Sets pen color. Change pen to red or blue.

change pen color by Shifts pen color. Creates rainbow effect.


(10)

set pen size to (5) Sets line thickness. Draw thick or thin lines.

change pen size by Increases/decreases line thickness. Line gradually becomes


(1) thicker.

clear Erases all drawings from stage. Reset canvas.

Example 2: Drawing a Triangle

when green flag clicked

clear

pen down

repeat 3

Dr.T.Premkumar
ASP/ME
move 100 steps

turn clockwise 120 degrees

end

pen up

➡ The sprite draws an equilateral triangle.

3. Easy Drawing in Scratch

By combining Motion Commands and Pen Commands, Scratch can be used to draw
geometric shapes, patterns, and art designs.

Example 3: Drawing a Circle

(Simulated by small repeated steps and turns)

when green flag clicked

clear

pen down

repeat 360

move 2 steps

turn clockwise 1 degree

end

pen up

➡ The sprite moves in tiny steps while turning, forming a circle.

Example 4: Spiral Pattern

when green flag clicked

clear

pen down

set pen color to blue

Dr.T.Premkumar
ASP/ME
set pen size to 2

repeat 50

move (5 * repeat count) steps

turn clockwise 20 degrees

end

➡ Creates a colorful spiral pattern.

Example 5: House Drawing (Square + Triangle Roof)

when green flag clicked

clear

pen down

repeat 4 // Draw square

move 100 steps

turn clockwise 90 degrees

end

move 100 steps

turn clockwise 30 degrees

repeat 3 // Draw triangle roof

move 100 steps

turn clockwise 120 degrees

end

pen up

➡ Draws a house structure using square and triangle.

Table: Motion + Pen Commands for Drawing

Shape Steps

Line pen down → move N steps → pen up

Square repeat 4 {move N steps, turn 90°}

Dr.T.Premkumar
ASP/ME
Triangle repeat 3 {move N steps, turn 120°}

Circle repeat 360 {move small step, turn 1°}

Star repeat 5 {move N steps, turn 144°}

LOOKS PALETTE IN SCRATCH

The Looks Palette in Scratch contains purple blocks that control a sprite’s appearance,
speech, thought bubbles, and costume changes. These blocks are essential for creating
animations, dialogues, and visual effects.

Categories of Looks Blocks

Block Type Block Examples Purpose / Usage

Speech/Thought say "Hello!" for 2 seconds, Make sprites talk or think on stage.
Bubbles think "Hmm.."

Costume Switching switch costume to [ ], next Change sprite’s appearance (for


costume animation).

Backdrop Control switch backdrop to [ ], next Change the stage background.


backdrop

Graphic Effects set color effect to 25, change Apply visual effects like color,
size by 10 brightness, ghost.

Size/Visibility set size to 150%, hide, show Resize, hide, or display sprites.

Example 1: Talking Animation

when green flag clicked

say "Hello! Welcome to Scratch." for 2 seconds

think "What should I do next?" for 2 seconds

Example 2: Walking Animation

when green flag clicked

repeat 10

next costume

move 10 steps
Dr.T.Premkumar
ASP/ME
end

➡ The sprite switches costumes and moves, creating the effect of walking.

2. Sound Palette in Scratch

The Sound Palette (pink blocks) allows sprites to play sounds, music, and voice recordings.
Scratch includes a sound library, but users can also record or upload custom sounds.

Main Sound Blocks

Block Function Example Use

play sound [meow] Plays a sound completely before Cat meows when clicked.
until done moving to next block

start sound [drum] Plays a sound but continues running Background music starts while
next blocks sprite moves.

stop all sounds Stops all currently playing sounds Useful for ending a game with
silence.

change volume by - Decreases sound volume Gradually fades music out.


10

set volume to 100% Sets volume to a specific level Starts music at full volume.

change pitch effect Increases pitch effect Voice sounds higher.


by 10

clear sound effects Resets sound modifications Removes pitch or echo effects.

Example 3: Background Music with Action

when green flag clicked

start sound [dance music]

repeat 10

next costume

move 10 steps

Dr.T.Premkumar
ASP/ME
end

stop all sounds

➡ The sprite dances while music plays.

Example 4: Game Over Sound

when sprite clicked

play sound [laser] until done

say "Game Over!"

stop all sounds

3. Power of Repeat

The Repeat command is part of the Control Blocks (orange blocks). It allows Scratch
programs to loop instructions, reducing repetition and making programs efficient.

Types of Repeats in Scratch

Repeat Type Block Example Purpose

Fixed Repeat repeat 10 { move 10 steps } Loops instructions a fixed number of


times.

Forever Repeat forever { move 10 steps } Loops instructions endlessly until


stopped.

Repeat Until repeat until <touching Loops until a condition becomes true.
Condition edge?>

Advantages of Repeat

• Makes code shorter and readable.

• Reduces errors by avoiding duplication.

• Enables creation of patterns, animations, and continuous behaviors.

Example 5: Drawing a Square with Repeat

Dr.T.Premkumar
ASP/ME
when green flag clicked

pen down

repeat 4

move 100 steps

turn clockwise 90 degrees

end

pen up

➡ Draws a square with just 5 blocks instead of 8.

Example 6: Continuous Bouncing Ball

when green flag clicked

forever

move 10 steps

if on edge, bounce

end

➡ The ball keeps bouncing forever.

Example 7: Repeat Until Condition

when green flag clicked

repeat until <touching edge?>

move 10 steps

end

say "I reached the edge!"

➡ Sprite moves until it touches the edge.

Table: Without Repeat vs With Repeat

Task Without Repeat With Repeat

Dr.T.Premkumar
ASP/ME
Draw Square move-turn, move-turn, move-turn, repeat 4 {move-turn} (5 blocks)
move-turn (8 blocks)

Animate Walking move 10 steps, next costume repeat 10 {move 10 steps, next
10 steps repeated 10 times (20 blocks) costume} (3 blocks)

Bounce Forever Manual repeat of move-bounce forever {move, bounce}


sequence

DATA TYPES IN SCRATCH

Unlike text-based languages (like Python, C, or Java), Scratch does not have strict data types.
Instead, values are dynamically handled depending on their use. Every variable or block input
can hold numbers, strings (text), or Boolean values.

Data Types in Scratch

Data Description Example


Type

Number Whole numbers or decimals, used for score = 100, speed = 3.5
calculations.

String Sequence of characters (text). "Hello", "Player1"

Boolean Logical values true or false. <touching edge?>, <score >


10>

Examples

Number Example:

1. set score to 50

2. change score by 10

→ Score now becomes 60.

String Example:

3. say "Hello, World!"

→ Sprite displays a message.

Boolean Example:

4. if <touching edge?> then

Dr.T.Premkumar
ASP/ME
5. say "I hit the edge!"

6. end

→ Executes only if condition is true.

2. Variables in Scratch

A variable is like a storage box that holds values such as numbers or text. Variables make
programs dynamic, allowing data to change during execution.

In Scratch, variables are created using the Variables Palette (dark orange blocks).

Creating a Variable

1. Go to Variables Palette.

2. Click Make a Variable.

3. Give it a name (e.g., score, time, playerName).

4. Choose For all sprites (global) or For this sprite only (local).

Variable Blocks

Block Function Example

set [variable] to (value) Assigns a value to a variable. set score to 0

change [variable] by Increases/decreases variable change score by 1


(value) value.

[variable] Reports current value of Displays score in bubble or


variable. condition.

show variable [ ] Displays variable value on stage. Shows “score: 10” on screen.

hide variable [ ] Hides variable display. Removes variable display from


screen.

Example 1: Score in a Game

when green flag clicked

set score to 0

forever

if <touching Apple?> then

Dr.T.Premkumar
ASP/ME
change score by 1

end

end

➡ The score increases whenever the sprite touches an apple.

Example 2: Timer

when green flag clicked

set time to 60

forever

wait 1 second

change time by -1

if <time = 0> then

say "Time Up!"

stop all

end

end

➡ A countdown timer for 60 seconds.

3. Getting Input from Users

Scratch allows programs to interact with users through the Sensing Palette (light blue
blocks). The most common way is by asking questions and storing responses.

Input Blocks

Block Function Example

ask [What's your name?] Displays a question and waits for Program asks for player’s
and wait user input. name.

answer Stores the user’s last input. Used after the ask block.

key [space] pressed? Returns true if a key is pressed. Controls sprite movement.

Dr.T.Premkumar
ASP/ME
mouse down? / mouse x, Detects mouse actions and Used in drawing or games.
mouse y position.

Example 3: Asking for Player’s Name

when green flag clicked

ask "What is your name?" and wait

say (join "Hello " answer)

➡ If user types John, sprite says “Hello John”.

Example 4: Simple Quiz Game

when green flag clicked

set score to 0

ask "What is 5 + 3?" and wait

if <answer = 8> then

change score by 1

say "Correct!"

else

say "Wrong!"

end

➡ Checks user input and updates score.

Example 5: Controlling Sprite with Keyboard

when green flag clicked

forever

if <key [right arrow] pressed?> then

change x by 10

end

Dr.T.Premkumar
ASP/ME
if <key [left arrow] pressed?> then

change x by -10

end

end

➡ Sprite moves left and right using arrow keys.

MAKING DECISIONS IN SCRATCH

In Scratch, programs often need to make decisions just like humans do.
For example:

• If the sprite touches an apple, then increase score.

• If time is up, then stop the game.

These decisions are made using control blocks such as if and if-else.

Decision Example

if <touching edge?> then

say "Oops! Hit the wall!"

end

➡ The sprite only reacts if it is touching the edge.

2. Comparison Operators

Scratch uses comparison operators (found in the Operators Palette, green blocks) to
compare numbers, variables, or text.
They always return a Boolean (true/false).

Operator Block Meaning Example Result

<[]=[]> Checks if values are equal. 5 = 5 True

<[]>[]> Checks if left is greater. 7>3 True

<[]<[]> Checks if left is smaller. 2<1 False

Example: Quiz Question

ask "What is 10 - 3?" and wait


Dr.T.Premkumar
ASP/ME
if <answer = 7> then

say "Correct!"

else

say "Wrong!"

end

➡ The decision depends on the comparison operator <answer = 7>.

3. Decision Structures

Decision structures allow a program to execute different paths depending on conditions.

Types of Decision Structures in Scratch

Single Condition (if)

1. if <score > 10> then

2. say "You win!"

3. end

Two-way Decision (if-else)

1. if <score > 10> then

2. say "Winner!"

3. else

4. say "Try again!"

5. end

Nested Decisions

1. if <score > 50> then

2. say "Gold Medal"

3. else

4. if <score > 30> then

5. say "Silver Medal"

6. else

Dr.T.Premkumar
ASP/ME
7. say "Bronze Medal"

8. end

9. end

4. Logical Operators

Logical operators combine or modify conditions. These are also found in the Operators Palette.

Operator Function Example

and Both conditions must be true. <score > 10> and <time > 0>

or At least one condition must be <key [up] pressed?> or <key [down]


true. pressed?>

not Reverses the condition (true → not <touching edge?> → true if sprite is not
false). touching

Example: Game Boundary Check

if <<x position > 200> or <x position < -200>> then

say "Out of bounds!"

end

➡ Uses or to check if sprite moves out of screen limits.

Example: Double Condition with and

if <<score > 10> and <lives > 0>> then

say "Keep Playing!"

end

➡ Both conditions must be true to continue.

5. Repetition (Loops)

Repetition allows actions to be done multiple times without writing the same code repeatedly.

In Scratch, loops are in the Control Palette (yellow blocks).

Dr.T.Premkumar
ASP/ME
Types of Loops

Loop Block Description Example

forever Repeats actions endlessly until program Moving a sprite


stops. continuously.

repeat (n) Repeats a set of actions a fixed number Repeat a dance move 10
of times. times.

repeat until Repeats until a condition becomes true. Loop until time = 0.
<condition>

Example 1: Forever Loop

when green flag clicked

forever

move 10 steps

if <touching edge?> then

turn 180 degrees

end

end

➡ Sprite keeps moving and bouncing forever.

Example 2: Repeat (n) Loop

repeat 4

move 100 steps

turn 90 degrees

end

➡ Sprite draws a square.

Example 3: Repeat Until

repeat until <score = 10>

ask "What is 2+2?" and wait


Dr.T.Premkumar
ASP/ME
if <answer = 4> then

change score by 1

end

end

say "You reached 10 points!"

➡ Loop continues until score reaches 10.

LOOP BLOCKS IN SCRATCH

Loops are essential for repeating actions. Scratch offers several loop control blocks in the
Control Palette.

Loop Block Description Example Use Case

forever Runs instructions endlessly until program is Continuous


stopped. animation.

repeat (n) Runs instructions a fixed number of times. Drawing polygons.

repeat until Repeats until a condition is true. Play until time runs
<condition> out.

Example: Forever Loop

when green flag clicked

forever

move 10 steps

if <touching edge?> then

turn 180 degrees

end

end

➡ Keeps sprite moving endlessly.

2. Stop Commands

Scratch provides commands to end a script, all scripts, or a specific sprite’s scripts.

Dr.T.Premkumar
ASP/ME
Stop Block Action

stop [this script] Stops only the current script.

stop [all] Stops the entire project.

stop [other scripts in sprite] Stops other running scripts of the same sprite.

Example: Game Over

if <lives = 0> then

say "Game Over"

stop [all v]

end

➡ Ends the game when lives run out.

3. Counters in Scratch

A counter is usually implemented with a variable that keeps track of how many times
something happens.

Example: Counting Steps

set [counter v] to 0

repeat 10

change [counter v] by 1

move 10 steps

end

say (join "Steps taken: " (counter))

➡ After loop ends, counter = 10.

Table: Common Counter Uses

Counter Variable Purpose

Steps Track sprite movement

Score Track points in game

Dr.T.Premkumar
ASP/ME
Time Count seconds elapsed

4. Nested Loops

Nested loops mean a loop inside another loop. They are useful for complex patterns.

Example: Drawing a Grid

repeat 5

repeat 5

move 20 steps

stamp

end

change y by -20

go to x:0 y:(y position)

end

➡ Draws a 5×5 grid using nested loops.

5. Recursion in Scratch

Scratch does not have traditional recursion, but custom blocks (My Blocks) can be designed to
call themselves.

Example: Recursive Spiral

define drawSpiral (size)

if <size > 0> then

move (size) steps

turn 15 degrees

drawSpiral (size - 2)

end

➡ Recursively draws a spiral until size becomes 0.

6. String Processing in Scratch

Dr.T.Premkumar
ASP/ME
Strings are sequences of characters (letters, digits, symbols). Scratch has operators for string
handling.

String Block Function Example

join [a] [b] Concatenates two strings. join "Hello" "World" →


“HelloWorld”

letter (n) of [string] Extracts nth letter of a string. letter 3 of "Scratch" → “r”

length of [string] Finds total length of string. length of "Scratch" → 7

<string> contains Checks if a string has a "Hello" contains "He" → true


<substring> substring.

Example: Password Check

ask "Enter password:" and wait

if <answer = "Scratch123"> then

say "Access Granted"

else

say "Access Denied"

end

7. String Manipulation Examples

a. Concatenation

set [greeting v] to (join "Hello, " (username))

say (greeting)

➡ Combines two strings.

b. Extracting Letters

set [firstLetter v] to (letter 1 of (answer))

say (firstLetter)

➡ Shows only the first character of input.

c. Counting Characters
Dr.T.Premkumar
ASP/ME
set [count v] to (length of (answer))

say (join "You typed " (count))

8. Bringing It All Together: Mini Project Example

Project: Secret Word Guessing Game

set [tries v] to 0

repeat until <answer = "robot">

ask "Guess the secret word:" and wait

change [tries v] by 1

end

say (join "You guessed it in " (tries))

stop [all v]

➡ Demonstrates loops, counters, decision, and string comparison.

WHAT ARE LISTS IN SCRATCH?

A list in Scratch is like a container that can hold multiple items (numbers, words, or both). It is
similar to an array in other programming languages.

• Found in the Variables Palette → “Make a List”.

• Displays as a block with operations like add, delete, insert, replace, item of, length of,
contains.

2. Operations on Lists

Block Function Example

add [thing] to [list] Adds an item at the add "Apple" to Fruits


end.

delete (index) of [list] Deletes item at given delete 2 of Fruits → removes


index. Mango

insert [thing] at (index) of [list] Inserts at specific insert "Grapes" at 3 of Fruits


index.

Dr.T.Premkumar
ASP/ME
replace item (index) of [list] with Updates value at Replace Banana with Guava.
[thing] position.

item (index) of [list] Gets specific item. item 1 of Fruits → Apple

length of [list] Number of items. length of Fruits → 4

[list] contains [thing] Checks if list has an Fruits contains "Mango" →


item. True

3. Dynamic Lists

Dynamic lists allow items to be added, removed, or modified during runtime.

Example: Building a To-Do List

when green flag clicked

delete all of [ToDo v]

repeat 3

ask "Enter a task:" and wait

add (answer) to [ToDo v]

end

say (join "Your tasks: " (ToDo))

➡ The list grows as the user inputs tasks.

→ Input "Exercise" → List = [Buy Milk, Read Book, Exercise]

4. Numerical Lists

Lists can also store numbers, useful in games, calculations, and data analysis.

Example: Storing Scores

set [Scores v] to []

add 85 to [Scores v]

add 92 to [Scores v]

add 76 to [Scores v]

Table: Numerical List Example

Dr.T.Premkumar
ASP/ME
Index Scores

1 85

2 92

3 76

➡ Can be used to calculate averages, maximum, or minimum.

Example: Average of Scores

set [sum v] to 0

repeat (length of [Scores v])

change [sum v] by (item (repeat counter) of [Scores v])

end

set [average v] to (sum / length of [Scores v])

say (join "Average Score = " (average))

5. Searching in Lists

Scratch does not have built-in search, but we can create it using loops and conditions.

a. Linear Search

Checks each item one by one.

Example: Find a Name

set [found v] to 0

ask "Enter name to search:" and wait

repeat (length of [Names v])

if <(item (repeat counter) of [Names v]) = (answer)> then

set [found v] to 1

end

end

if <found = 1> then

Dr.T.Premkumar
ASP/ME
say "Name Found"

else

say "Not Found"

end

6. Sorting Lists

Sorting helps arrange list items in order (ascending or descending).

a. Bubble Sort Example (Numerical List)

set [swapped v] to 1

repeat until <(swapped) = 0>

set [swapped v] to 0

repeat ((length of [Scores v]) - 1)

if <(item (repeat counter) of [Scores v]) > (item ((repeat counter) + 1) of [Scores v])>
then

set [temp v] to (item (repeat counter) of [Scores v])

replace item (repeat counter) of [Scores v] with (item ((repeat counter) + 1) of


[Scores v])

replace item ((repeat counter) + 1) of [Scores v] with (temp)

set [swapped v] to 1

end

end

end

say (join "Sorted Scores: " (Scores))

➡ This sorts the list in ascending order.

7. Mini Project Example

Project: Student Marks Management

when green flag clicked


Dr.T.Premkumar
ASP/ME
delete all of [Marks v]

repeat 5

ask "Enter mark:" and wait

add (answer) to [Marks v]

end

say (join "Marks: " (Marks))

-- Find Highest Mark

set [max v] to (item 1 of [Marks v])

repeat (length of [Marks v])

if <(item (repeat counter) of [Marks v]) > (max)> then

set [max v] to (item (repeat counter) of [Marks v])

end

end

say (join "Highest mark = " (max))

➡ Demonstrates dynamic lists, numerical lists, searching, and maximum


calculation.

Dr.T.Premkumar
ASP/ME

You might also like