Programming · Grade 6 · Chapter 5
Scratch: Variables & Game Design
Giving programs computer memory, managing score state, timer loops, and broadcast signaling.
Lesson Overview
Learning Objectives
- Understand Memory Containers: Define variables as named slots in computer RAM that store dynamic data.
- State Management: Master initialization with
set variable to vs updating with change variable by.
- Broadcast Messaging: Use
broadcast [message] to trigger events across multiple sprites simultaneously.
- Complete Game Architecture: Build a fully playable arcade game with Score, Timer, and Game Over states.
Evolution of Game Code
Adding Memory to Interactive Projects
Stateless Project (Ch 3-4)
Sprites move, collide, and play sounds, but forget everything the instant the interaction finishes.
Stateful Game (Ch 5)
Computer tracks player score, health points, remaining time, high score records, and game levels over time.
Debugging Case Study
The Game That Forgot to Reset
Hassan created an awesome space shooter game! Player 1 scored 50 points and lost all lives. Player 2 clicked the Green Flag to start a fresh game — but started with 50 points and 0 lives, causing an instant Game Over!
Smartboard Challenge: What step did Hassan forget to include under when green flag clicked?
Core Concept #1
What Is a Variable?
A variable is a labeled box in computer memory that stores a single piece of changing data.
NAME
Variable Label
e.g. Score, PlayerLives, TimeRemaining.
VALUE
Stored Data
e.g. 0, 100, "Victory!".
SCOPE
Global vs Local
Shared across all sprites or private to one sprite.
Variable Operators
set [var] to vs change [var] by
set [Score] to [0]
Assignment / Reset: Overwrites the variable with an exact new value. Used during game startup initialization.
change [Score] by [1]
Increment / Decrement: Adds or subtracts from the current stored value. (e.g. by -1 reduces lives).
Game Architecture
Building a 30-Second Countdown Timer
when green flag clicked
set [Timer] to 30
repeat until <Timer = 0> {
wait 1 secs
change [Timer] by -1
}
broadcast [Game Over]
System Architecture
Game Execution Lifecycle
PHASE 1
Initialization
Score = 0, Lives = 3, Position = (0,-120).
PHASE 2
Main Loop
Sensing controls, moving objects, score updates.
PHASE 3
Check Win/Loss
If Lives = 0 or Timer = 0, break loop.
PHASE 4
Game Over Signal
Broadcast signal & display final high score screen.
Core Concept #2
Inter-Sprite Communication (Broadcasting)
Sprites cannot directly touch each other's code — they communicate by sending global radio messages!
SENDER
broadcast [Victory]
Dispatches an invisible event signal to every sprite on the stage.
RECEIVER
when I receive [Victory]
A hat block that starts executing specific celebratory scripts when the signal is heard.
Full Code Walkthrough
Fruit Catcher Game Script
// Falling Fruit Sprite Script
when green flag clicked
hide
forever {
go to x: pick random -200 to 200 y: 180
show
repeat until <<touching [Basket]> or <y position < -170>> {
change y by -8
}
if <touching [Basket]> then {
change [Score] by 10
}
}
Syntax Comparison
Global vs Local Variables
🌐 Global ("For all sprites")
Used for shared game state: Score, GameTimer, CurrentLevel. Accessible anywhere.
🔒 Local ("For this sprite only")
Used for sprite-specific physics: y_velocity, clone_id. Keeps individual clone properties distinct.
Myth Buster
Trap 1: The Rapid-Fire Increment Bug
❌ Missing Delay / Reset
Placing if touching basket then change score by 1 inside a forever loop without hiding or moving the sprite causes score to add +60 per second while touching!
✅ Immediate Response
Instantly reset fruit position or hide sprite upon collision so the score only increments ONCE per catch.
Myth Buster
Trap 2: Forgotten Initialization
❌ Uninitialized Start
Game begins immediately with whatever score was left from the last test run.
✅ Explicit Initialization
Always place set Score to 0 at the very top of your Green Flag setup script!
Smartboard Challenge
Trace the Variable Values
1. set [Coins] to 10
2. change [Coins] by 5
3. repeat 3 { change [Coins] by -2 }
4. set [Coins] to [Coins] * 2
Solve on smartboard: What is the final value stored inside the Coins variable?
Smartboard Challenge
Broadcast Event Mapping
Match the broadcast event to what each sprite should do when received:
Event: broadcast [Game Over]
Player Sprite: Hide & disable controls
Backdrop: Switch to Game Over backdrop & play defeat sound
Group Discussion: What should enemy sprites do when they receive [Game Over]?
Advanced Techniques
Introducing Sprite Clones
Instead of making 20 duplicate coin sprites, use clones to spawn unlimited objects efficiently!
when green flag clicked
repeat 10 {
create clone of [myself]
wait 0.5 secs
}
when I start as a clone
go to random position
show
Coding Activity
Building a Scorekeeper & Victory Checker
when green flag clicked
set [Score] to 0
forever {
if <Score >= 100> then {
broadcast [YOU WIN!]
stop all
}
}
Spot The Bug
Why does the timer count negative?
when green flag clicked
set [Timer] to 10
forever {
wait 1 secs
change [Timer] by -1
}
Debug Prompt: Why does Timer keep going to -1, -2, -3 instead of stopping at 0?
Game Design Blueprint
3-Variable Game Architecture
Design a health system with 3 variables: Score, PlayerHealth, and SpeedMultiplier.
• Every coin collected adds +10 to Score and +1 to SpeedMultiplier.
• Every obstacle hit subtracts -25 from PlayerHealth.
• If PlayerHealth <= 0, broadcast [Defeat].
Interactive Quiz · Question 1
Which block should be used at game startup to set a score to 0?
Achange [Score] by (0)
Bset [Score] to (0)
Cshow variable [Score]
Dbroadcast [Score]
Click to reveal answer
Interactive Quiz · Question 2
What is the primary function of a Broadcast message block?
ATo change the background color instantly
BTo display a text speech bubble over a sprite
CTo trigger scripts across multiple sprites simultaneously
DTo reset all variables back to zero
Click to reveal answer
Interactive Quiz · Question 3
If a player starts with 3 lives and code executes change [Lives] by -1, what is the new value?
Click to reveal answer
Lesson Recap
Summary of Key Takeaways
- Variables: Named RAM slots for storing dynamic values like Score, Health, Time.
- Set vs Change:
set assigns exact values; change adds/subtracts relative offsets.
- Initialization: Always reset variables under
when green flag clicked.
- Broadcasting: Decouple game logic by dispatches global signal events.
Exit Ticket
Before You Leave
Write down in your notebook:
1. The difference between set Score to 10 and change Score by 10.
2. Give 2 examples of game events that should trigger a broadcast [Game Over].
Next Chapter: AI Basics Recap & Machine Learning Fundamentals!