LEARN · PRACTISE · DISCOVER
Variables: Keeping Score
How does a game remember your score? It uses a variable. A variable is like a labelled box that stores a piece of information, such as a number. The value inside the box can change as the game is played. In this lesson you will create a score variable and a lives variable.
Making a variable
- Click the orange Variables category.
- Click Make a Variable.
- Type a name, such as Score.
- Choose For all sprites, so every sprite can use it, and click OK.
A small display showing Score appears on the stage. You can hide it by unticking the box next to the variable.
Variable blocks
| Block | What it does |
|---|---|
set [Score] to (0) | puts an exact value in the box |
change [Score] by (1) | adds to the value (use -1 to take away) |
(Score) | the round reporter block that gives the current value |
Always reset at the start
At the start of a game, the score should be 0. Put set [Score] to (0) right under when green flag clicked. If you forget, the score will keep growing from the last game.
Adding points
Here is a simple clicker game. Each time you click the sprite, you score a point and the sprite jumps to a new place.
when green flag clicked
set [Score] to (0)
when this sprite clicked
change [Score] by (1)
go to (random position)Example: lives
Ben made a dodge game with a Lives variable. At the start, he used set [Lives] to (3). Whenever his player touched a meteor, he used change [Lives] by (-1). The game checked: if Lives = 0, it said “Game over!” and stopped.
when green flag clicked
set [Lives] to (3)
forever
if <touching (Meteor)?> then
change [Lives] by (-1)
wait (1) seconds
end
if <(Lives) = (0)> then
say (Game over!)
stop (all)
end
endThe wait (1) seconds gives the player a moment to escape, so one hit does not take away all three lives at once.
Using operators with variables
The green Operators blocks let you compare and calculate. ( ) = ( ), ( ) > ( ) and ( ) < ( ) create conditions. For example, <(Score) > (9)> checks whether the score is more than 9, which is great for a “You win!” message.
Common bug: the score jumps too fast
If the score shoots up by lots of points in one touch, the if touching check is running many times while the sprites overlap. Fix it by moving the sprite away, or adding a short wait, straight after changing the score.
Key takeaways
- A variable stores information that can change, like a score.
- Use
setto give it a starting value andchangeto add or subtract. - Reset variables when the green flag is clicked.
- Combine variables with operators to check for wins and losses.
Practice
Add a “You win!” message to the clicker game when the score reaches 10.
Answer: in the sprite’s click script, after change [Score] by (1), add if <(Score) = (10)> then, say (You win!), stop (all).