- Learn
- Computer Science & IT
- Computing and Coding for Ages 7 to 11
- Variables in Games
Variables, Inputs and Scores in Games
Grade 3, Grade 4, Grade 5Lesson 4 of 10 in Computing and Coding for Ages 7 to 11 Course
What you will learn
- Learn that a variable is a named store that keeps one value at a time, spot variables in everyday life and in programs, and make your own variables with clear names.
- Explain what a variable isDescribe a variable as a named store for a value that can change while a program runs, and connect it to scores, timers and lives in games you know.
- Make, name and spot variables in a programCreate a variable in a block-based tool, give it a clear name, show it on the screen, and find the variables in a program someone else wrote.
- Explain what a variable is
- Give a variable a starting value, make its value go up or down, and follow step by step how the value changes as a program runs.
- Give a variable a starting valueUse a set block to give each variable the right value at the start of a program, and explain why forgetting to do this causes bugs.
- Change a value up or downUse change blocks and plus and minus to make a value go up or down, and tell the difference between setting and changing a value.
- Trace how a variable's value changesFollow a program one block at a time, write down each variable's value in a trace table, and predict the final value before you run it.
- Give a variable a starting value
- Make programs that take in information from the player, keep it in variables, show results on the screen, and compare values to decide what happens next.
- Take input from the playerRecognize different kinds of input, ask the player a question, and store the reply in a variable so the program can use it.
- Show output to the playerRecognize different kinds of output, show a variable's value with words around it, and put output blocks in the right place.
- Compare values to make decisionsUse greater than, less than and equal to with variables in if blocks and loops, choose the right comparison, and avoid boundary mistakes.
- Take input from the player
- Put variables to work in a real game: add points, take away lives, count down the time, and end the game at the right moment.
- Keep score and count livesProgram a score and lives that change when sprites touch or the player answers, and fix the bugs that make values jump too far.
- Add timers and countdownsUse the built-in timer or your own countdown variable to limit the time in a game, and end the game when time runs out.
- Keep score and count lives
- Plan a simple game with variables, build it a little at a time, test it against what you planned, fix bugs and make it better.
- Plan a game with variablesDescribe your game idea, list its variables in a table, write the algorithm before coding, and set success criteria you can test.
- Build, test, debug and improve your gameBuild your game in small steps, test it against your success criteria, find and fix variable bugs, and improve the game using feedback.
- Plan a game with variables
Variables in Games study guide
1Meet the values a game remembers
A game needs to remember your points while you play. It also needs to find that number when something changes. You can act this out with labeled paper boxes before using blocks. Learn how names and values work together, then make variables that you and your player can recognize.
1.1 Give a changing value a name
A game can remember your score between catches. It keeps that score in a variable, a named place that stores a value.
Try a paper variable
Draw a box and label it "score". Put a small card showing 5 inside. The label is the variable's name. The number on the card is its value.
Now replace the card with one showing 8. Your variable holds 8. It holds one value at a time, so 5 has been replaced. The label still says "score".
A program does the same kind of job. It uses the name to find the value it needs. When it changes that value, the variable's name stays the same. A basketball scoreboard works like this: "Home" stays put while its score changes from 10 to 12 to 15.
Remember different things separately
A game might need your score, lives, time left, and level. Each means something different, so each needs its own variable. The value of "lives" tells you how many chances remain. The value of "timeLeft" tells you how many seconds remain.
Your current score and your best score need separate stores, too. A variable named "score" holds this game's points. Another named "highScore" remembers the best score. Replacing the current score need not erase the record. To keep any old value, copy it into another variable before replacing it.
Spot what can change
Look at the block move 10 steps. Its number 10 is typed into the block. It stays 10 each time that block runs unless you edit it. A variable is different: the program can change its stored value while running.
You can spot the same idea outside games. A step counter remembers the steps taken so far. A weather display keeps the latest temperature. A quiz remembers how many answers you got right. In each case, the name tells you what the changing value means.
Key Takeaways
- A variable stores one value at a time under a name.
- Changing a value leaves the variable's name the same.
- Use separate variables to remember separate things.
- A number typed into a block is not itself a variable.
1.2 Make variables you can find and use
Clear names help you read a program. They also help you spot a block that changes the wrong value.
Create and show a variable
In Scratch, open Variables and choose "Make a Variable". Type a name such as "score". Choose "For all sprites" when several sprites will share it.
You now have blocks to set, change, show, and hide the variable. Its round block reports its current value. You can put that round block inside another block that needs a value.
Check the box beside the variable to show its display on the stage. Scratch also calls this a monitor. A display such as "score 3" shows both the name and the current value. It updates as the value changes. The show variable and hide variable blocks control whether you see it; hiding it keeps the stored value.
Choose names that explain their job
Use names such as "lives", "timeLeft", and "playerName". A name like "thing" leaves you guessing. Keep one variable for each job. Nearly matching names, such as "score" and "score2", make mix-ups easy. Check the variable menu in each set or change block.
"For all sprites" lets several sprites change one shared value. An apple and a star can both add to the same score. "For this sprite only" makes a separate variable that only that sprite's scripts can set or change. Two sprites may each have their own "lives" variable. Those are separate stores, even though the names match.
Read a program's variables
Suppose the starting script contains set score to 0 and set lives to 3. Later, touching Apple changes score by 1. Touching Bat changes lives by -1. You can describe both variables:
| Name | What it remembers | Start | What changes it |
|---|---|---|---|
| score | Apples caught | 0 | Catching an apple |
| lives | Chances left | 3 | Touching a bat |
Look for set blocks, change blocks, round blocks, and stage displays. Some round blocks, including x position, timer, and answer, are built in. You can read their values without making them yourself.
Try use, modify, create. First run a game and find its variables. Then change starting lives from 3 to 5 and predict the result. Finally, make a small program with your own clearly named variable.
Key Takeaways
- Choose names that tell you what each value means.
- A variable display shows its current value as it changes.
- Use "For all sprites" for a value several sprites must change.
- Check the variable menu when a block changes the wrong value.
- Find what each variable stores, its starting value, and what changes it.
2Start, change, and follow values
A score needs a sensible beginning and the right changes. The order of your blocks matters, too. You will set starting values, add or subtract amounts, and follow the results on paper. A trace table helps you predict a run and find the first place where a program behaves differently.
2.1 Start each game with the right values
A new game should begin with the values you planned. Use a set block to put each starting value in place.
Give the game a clean start
The block set score to 0 replaces the previous score with 0. Giving a variable its first value is called initializing it. You can also call this setting its starting value.
Put the starting blocks directly below when green flag clicked. They belong before blocks that change or check those variables:
when green flag clicked
set score to 0
set lives to 3
set timeLeft to 30
set level to 1
Each starting value has a job. Zero means no points earned yet. Three gives the player three chances. Thirty gives a 30-second countdown, and level 1 is the first level. More starting lives make the game easier.
Scratch variables keep their values when a run stops. Their values are saved with the project, too. If your last score was 14, clicking the flag does not erase that score by itself. Your starting set block gives the next game its planned score of 0.
Keep starting blocks before repeating blocks
Put set score to 0 before the game's forever loop. Inside the loop, it would reset the score on every pass. A catch might add a point, but the next pass would wipe it away.
You can still use set blocks later for a fresh value. Reaching a new level might run set level to 2 and set timeLeft to 30. That starts level 2 with a fresh 30 seconds.
Keep the record between games
Some values must last longer than one game. Set "highScore" to 0 once when you make the game. Keep it between plays so it can remember the best score. Reset "score" at each new game, but leave "highScore" alone until you have a better result to store.
Key Takeaways
- A set block replaces whatever value was stored before.
- Set starting values before blocks that use them.
- Keep starting resets outside repeating game loops.
- Reset each new game's score, but keep the high score between games.
2.2 Add to a value or replace it
Catching a coin should add to the points you already have. A change block uses the old value to work out the new one.
Compare set and change
Suppose "score" holds 7. These blocks do different jobs:
| Block | What it does | New score |
|---|---|---|
set score to 2 | Replaces the old value | 2 |
change score by 2 | Adds 2 to the old value | 9 |
The rule for a change block is:
If "score" is 4, change score by 1 makes it 5. If you use set score to 1 for every catch, it stays at 1. Set keeps replacing the score with the same number.
Make values go down
A negative change takes something away. change lives by -1 turns 3 lives into 2. The minus sign belongs in the number slot; there is no separate decrease block in Scratch.
Changes can be bigger than 1. A gold coin can add 10 points. A silver coin can add 5. A wrong quiz answer can change score by -2.
Nothing in a change block stops a value at zero. Taking one life from 0 gives -1. Add a game-ending check where lives can change.
Use another value in a change
The amount can come from another variable. Suppose "score" is 40 and "timeLeft" is 12. The block change score by (timeLeft) adds the 12 seconds as bonus points:
The score becomes 52. "timeLeft" stays 12 because this block changes only "score".
You can use plus or minus inside a set block, too. set score to (score + 10) first reads the old score, adds 10, and stores the result. It does the same job as change score by 10. Likewise, set lives to (lives - 1) matches change lives by -1.
Count each time a block runs
Inside repeat 5, a block that changes score by 2 runs five times. It adds 10 altogether. A loop repeats the change, not just the words around it.
Position values work this way, too. change x by 10 moves a sprite right. change x by -10 moves it left. If movement goes the wrong way, check the sign.
Key Takeaways
- Set replaces a value; change adds to the value already there.
- A negative change makes a number go down.
- Each loop pass runs its change blocks again.
- Using another variable as the change amount leaves that other variable unchanged.
- A change can take a value below zero unless your program stops it.
- Plus and minus blocks can work inside set blocks.
2.3 Follow every change in a trace table
You can work out a program's result before running it. Tracing means following its blocks in order and recording changing values.
Write one row for each change
Read this sequence from top to bottom: set score to 0, change score by 10, change score by 10, change score by -5.
| Block just run | score |
|---|---|
| Set to 0 | 0 |
| Change by 10 | 10 |
| Change by 10 again | 20 |
| Change by -5 | 15 |
The last row shows the final score: 15. The earlier rows are snapshots, not extra points. Adding the column would count those snapshots together.
Open up a loop on paper
Start "coins" at 5. Then repeat change coins by 3 four times. Record 5 first. The four changes give 8, 11, 14, and 17. You need a row for each pass. Counting only one change would give 8 and miss three passes.
A condition decides whether a change runs. In a quiz, start score at 0. Ask "What is 6 × 7?" and add 1 for 42. Then ask "What is 9 + 8?" and add 1 for 17. Replies of 42 and 16 produce scores of 0, 1, and 1. The wrong second reply adds nothing.
Keep variables in separate columns
Start with score 0 and lives 3. A star adds 5 points. A bat takes one life. After star, bat, star, your table looks like this:
| Event | score | lives |
|---|---|---|
| Start | 0 | 3 |
| Star | 5 | 3 |
| Bat | 5 | 2 |
| Star | 10 | 2 |
Carry forward a value when that event leaves it unchanged. The bat changes lives, so the score stays 5 on that row.
A countdown can be traced the same way. Start "timeLeft" at 3. Repeat a one-second wait and a change of -1 until it equals 0. The values are 3, 2, 1, 0: three passes and about three seconds.
Compare your prediction with a run
Show the variable displays and run the program. Add short waits while testing if the changes happen too fast. If the screen and table disagree, find their first difference. Inspect the block at that point and check the condition or loop around it.
Key Takeaways
- Trace blocks in the order they run.
- The last row gives the final value; do not total the column.
- Record every loop pass and check whether each condition is true.
- Use a separate column for each variable.
- The first difference between a trace and a run helps locate a bug.
3Let the player talk to your program
Pressing a key can move a character. Typing a reply can change a quiz score. You will connect these player actions to the work your program does and the results it shows. Save replies you need later, show values clearly, and check comparisons at the points where decisions change.
3.1 Take in and save player input
A program needs information from outside itself. That information is input. You give input when you press a key, click a sprite, move a mouse, or type a reply. A microphone or a button on a small computer board can provide input, too.
Connect input to actions
An event can start a script. For example:
when right arrow key pressed
change x by 10
Each press starts the movement. To keep moving while a key is held, check it inside a loop:
forever
if key left arrow pressed? then
change x by -10
The loop checks the key again on each pass. When it is held, the change runs again.
Ask a question and wait
The ask [What is your name?] and wait block shows a question and a reply box. The script pauses there until the player presses Enter or clicks the check mark. Blocks below that ask block wait for the reply.
The built-in answer block holds what the player typed. It keeps the most recent reply. Another question replaces it.
Save a reply straight after asking if you need it later:
ask [What is your name?] and wait
set playerName to (answer)
ask [What is your favorite color?] and wait
After the second reply, answer holds the color. "playerName" still holds the name because you copied it before asking again. Asking both questions before saving the name would lose that reply from answer.
Let input affect the game
You can ask, "How many lives do you want: 3 or 5?" Then set lives to (answer) stores the choice. Test unexpected replies, too. A player might type 0, leave the box empty, or enter a word. A clear question helps, but it does not force the player to type one of the suggested numbers.
In a quiz, the reply feeds a comparison. The program checks whether answer matches the correct answer. It adds a point when the check is true.
Key Takeaways
- Input enters a program through actions such as keys, clicks, and typed replies.
- An ask-and-wait block pauses its script until the player submits a reply.
- The built-in answer keeps only the latest reply.
- Copy a reply into your own variable before asking another question.
3.2 Show the player what happened
Your program needs to show its results. Output is information people see or hear from a program. It includes movement, speech bubbles, sounds, costumes, backdrops, variable displays, and device lights.
Follow input, processing, output
When you press the right arrow, the key press is input. The program runs change x by 10: that is processing, the work it does. Seeing the cat move right is output.
A quiz follows the same path. You type 42 as input. The program checks the reply and adds 1 to "score". That is processing. A score display showing 1 and a "Correct!" speech bubble are output.
Show a number or a message
A variable display is useful for scores, lives, and countdowns. Once shown, it updates whenever the variable changes.
A speech bubble can show a value, too. Drag the round score block into a say block:
say (score) for 2 seconds
This shows the stored number. Typing the word "score" into the say block shows that word instead. The round block tells the program to look up the value.
The join block puts words and a value together:
say (join [Your score is ] (score))
With score 15, the message reads "Your score is 15". Keep a space after "is" inside the first slot. Without it, the result is "Your score is15".
Stored input can appear in a message, too. If "playerName" holds "Mia", joining "Good luck, " with that variable gives "Good luck, Mia".
Show the value after changing it
Block order affects a speech bubble. With score 4, saying the score and then changing it by 1 shows 4. To show the new score of 5, put the change first and the say block next. A shown variable display updates itself, but a say block reads the value when it runs.
Output can celebrate a result. A score check can trigger a cheer sound or a "You win!" backdrop when the target is reached.
Key Takeaways
- Output is what people see or hear from a program.
- Processing is the work between input and output.
- Use a round variable block to say its value.
- Use join to combine words and values, including needed spaces.
- Put a say block after a change to report the new value.
3.3 Check values to choose what happens
A game needs to decide when you win or run out of lives. A comparison checks two values. Its result is either true or false.
Read the three comparison blocks
The symbols >, <, and = mean greater than, less than, and equal to. Comparison blocks fit into an if block or a repeat-until loop.
When score is 10:
| Check | Result |
|---|---|
score > 9 | True |
score > 10 | False |
score = 10 | True |
score < 10 | False |
Greater than leaves out equality. If whole-number scores of 10 or more should win, use score > 9. A check of score > 10 would miss exactly 10. The value where a decision changes is called a boundary.
An if-then-else block picks between two actions. For a quiz reply of 42, add a point and say "Correct!". Otherwise, say "The answer is 42". Only the chosen branch runs.
Check while the game changes
A single check at the beginning sees only the starting lives. Put the check in a running game loop so it keeps checking as lives change:
forever
if lives = 0 then
say [Game over]
stop all
A repeat-until loop checks its condition before each pass. When the check is false, the inside blocks run once. When it becomes true at the next check, the script continues below the loop. It does not stop an inside pass halfway through.
Watch for a skipped value
Suppose "timeLeft" starts at 25 and drops by 2 each pass. It reaches 3, then 1, then -1. It never equals 0. A loop waiting for timeLeft = 0 keeps going. A check of timeLeft < 1 catches zero and lower values.
You can compare two variables, too. At the end of a game, use if score > highScore then set highScore to (score). If the record is 12 and you score 15, the record becomes 15. A later score of 9 leaves it at 15.
Key Takeaways
- A comparison gives true or false.
- Greater than and less than leave out equality.
- Keep checking an ending condition as the game runs.
- Repeat until checks before a pass, not halfway through it.
- Use a less-than check when a countdown can skip past zero.
- Update a high score only when the new score beats it.
4Make points, chances, and time work together
A useful game score changes exactly once for each catch. Lives give the player a few chances, and a clock adds a time limit. You will build these parts with variables and checks. You will also fix repeated hits and compare a countdown with a timer that measures time passing.
4.1 Count catches and hits once
Decide what each game event should do. Catching an apple can add 1 point. Touching a bat can take away 1 life. Put each change inside the matching condition.
Build the falling apple
Make "score" and "lives" for all sprites. In the cat's starting script, set score to 0 and lives to 3. The apple needs a repeating script:
when green flag clicked
go to x: (pick random -200 to 200) y: 170
forever
change y by -5
if touching Cat? then
change score by 1
go to x: (pick random -200 to 200) y: 170
if y position < -170 then
go to x: (pick random -200 to 200) y: 170
The negative y change moves the apple down. Catching it adds a point and sends it back up. The last check also returns a missed apple. The stage's bottom edge is at y = -180, so this check returns it near the bottom. Without that check, a missed apple can get stuck there.
Stop one catch counting many times
A forever loop can run many times while two sprites touch. If it only adds a point, one apple may give many points. Moving it away straight after scoring ends that touch. You can also wait until the sprites stop touching before allowing another point.
Hiding the caught object also stops touch scoring while it is hidden. Show it again when you return it for the next catch.
Use the same idea for lives. After a bat hit, run change lives by -1 and move the bat away. Then check whether lives have run out and end the game. Otherwise, the repeated contact can use every life in a moment.
Choose the rules for points and speed
A wrong quiz answer might subtract 2 points. If your rules say scores cannot go below 0, follow the penalty with if score < 0 then set score to 0.
Variables can change the game's movement, too. Use change y by (fallStep) and start "fallStep" at -5. Setting it to -8 at level 2 makes the apple fall 8 steps on each pass.
For a five-question quiz, a final message can join "You got ", the score, and " out of 5". A score of 4 then reads "You got 4 out of 5". If several sprites award points, they must change the same shared score.
Key Takeaways
- Put each score or life change inside the matching event check.
- End a touch before it can award another point or take another life.
- Return missed falling objects so they can appear again.
- Check for the game ending when lives change.
- Use a shared score when several sprites change it.
- A variable can control movement as well as count points.
4.2 Count down or measure passing time
Some games ask you to finish before time runs out. Races ask how long you took.
Measure time going up
Scratch has a built-in timer. It counts up in seconds and can show decimals, such as 12.4. Use reset timer at the start to measure from your game's beginning.
To end a game after 60 seconds, use wait until timer > 60, then stop all. For a race, say the timer value when the player finishes. round (timer) turns 12.4 into the nearest whole number, 12. The timer keeps running, so store the finish value when you need to keep it.
Build a clock going down
Make your own "timeLeft" variable and show it. Put this countdown in a separate script:
when green flag clicked
set timeLeft to 30
repeat until timeLeft < 1
wait 1 seconds
change timeLeft by -1
say [Time's up!]
stop all
Each pass waits, then takes away one second. The values go 30, 29, 28, and on down to 0. There are 30 passes, lasting about 30 seconds. The wait gives each displayed value time to stay on screen.
Keep both the wait and the change inside the loop. Without the wait, the clock races down almost at once. With the change after the loop, the clock never changes while the loop waits for it to run out.
Let the clock and player run together
One script finishes its loop before reaching the blocks below it. A movement loop placed below the countdown would start too late. Give movement its own green-flag script. Then the player can move while the countdown runs.
A game can end when lives run out or time runs out. Keep checking both so either ending can stop play. In a game that rewards finishing early, add the leftover time to the score as a bonus.
Keep the fastest race time
A smaller race time is better. After the first finished race, set "bestTime" to that finish time. For later races, replace it only when the new finish time is smaller. Starting the record at 0 would fail: a real race cannot beat zero seconds. Keep "bestTime" between races.
Use a five-second countdown while testing a longer game. Once it works, restore the planned time limit.
Key Takeaways
- The built-in timer counts up; your countdown variable counts down.
- Put a one-second wait and the decrease inside the countdown loop.
- Run movement and the countdown in separate scripts.
- Save a race's finish time when you need to keep it.
- Start the best-time record with the first finished race, then keep smaller results.
- Test a long countdown with a shorter starting time.
5Turn your game idea into a working game
Choose a small game you would enjoy making. A plan connects the player's actions to the values your program remembers. You will list those values, sketch the steps, and decide how to check the result. Build a few blocks at a time, then use tests and player feedback to guide changes.
5.1 Plan the player actions and variables
Before choosing blocks, explain your game in a few sentences. Say what the player does, what counts as winning, and what can end the game.
Start with a small idea
For "Apple Catch", move a cat with the arrow keys. Catch apples for points and avoid bats that take lives. Aim for 10 points within 30 seconds. The controls are input. The moving sprites, visible values, sounds, and ending messages are output.
List only the variables your game needs. A small first version can use one falling apple and a score. Add lives, a timer, or levels after the first part works.
Make a variable plan
For each variable, write its name, meaning, starting value, and changes. Include the amount of each change.
| Name | Stores | Starts at | Changes when | Amount |
|---|---|---|---|---|
| score | Apples caught | 0 | An apple is caught | +1 |
| lives | Chances left | 3 | A bat hits the cat | -1 |
| timeLeft | Seconds left | 30 | One second passes | -1 |
This plan helps you choose the right variable in each block. It also shows which values need a starting set block.
Sketch the steps before building
An algorithm is a set of steps for doing a job. Write plain steps or draw a flowchart. Show events, loops, choices, and changes to variables.
For the apple, your plan might say: start at the top; keep falling; after a catch, add a point and return to the top; after a miss, return to the top. For the clock, show a repeated wait and decrease. Include checks for winning and losing.
Decide how you will know it works
Write success criteria you can test by playing. "The game is good" is hard to check. These give you clear tests:
- "Every new game starts with score 0."
- "One caught apple adds exactly 1 point."
- "The game ends when lives reach 0."
Think about the player, too. Show a short instruction such as "Use the arrow keys to catch apples". Keep score, lives, and time visible. Starting with more lives or more time makes play easier.
Key Takeaways
- Plan the goal, controls, and ways to win or lose.
- List each variable's job, start, trigger, and change amount.
- Sketch the algorithm before assembling blocks.
- Write success criteria you can check by playing.
- Build a small first version before adding more features.
5.2 Test a result and fix its cause
Add a few blocks, run them, and check the result. Building in small steps helps you find a new bug near the blocks you just added.
Compare expected and actual results
Testing means checking what happens against what you expected. Record the action, expected result, and actual result.
| What you do | Expected | Actual | Result |
|---|---|---|---|
| Catch one apple | Score rises by 1 | Rises by 1 | Pass |
| Keep touching an apple | Only 1 point for that catch | Rises by 27 | Fail |
A failed test gives you a clue. The second row points to repeated scoring during one touch.
Test the edges as well as ordinary play. Try exactly the winning score, the last life, and the moment time runs out. Play a second game to check the starting values. For typed replies, try a correct answer, a wrong answer, an empty reply, and words such as "forty-two".
Look for the first wrong change
Show the variable displays. Slow changes down with short waits and trace the blocks by hand. Check the first place where the actual value differs from your prediction.
These checks help with common variable bugs:
- Wrong starting value: add or fix the starting set block.
- Score stuck at 1: check whether set should be change.
- Lives rising after a hit: check the sign of the change.
- Points rising without a catch: check whether the change is inside the if block.
- Ending check never happens: make it run as the game continues.
- Countdown passes zero: check the comparison.
- Another sprite cannot change the score: check how the variable is shared.
Repair, then retest
Suppose one bat touch sends lives from 3 to -40. The loop keeps subtracting while the sprites touch. It also lacks a working ending check. Move the bat away after a hit, and check lives < 1 to say "Game over" and stop all.
Change one thing at a time and repeat the failed test. Then check nearby behavior, such as another separate hit. This helps you see which change solved each problem.
Once the game works, ask a friend to play. Find out what felt fun or confusing. Use that feedback to choose one improvement, such as clearer instructions, a level, a sound, or a high score. Test the changed part again.
Key Takeaways
- Compare expected and actual results in a test.
- Test boundaries, unexpected replies, and a second game.
- Use displays and tracing to find the first wrong change.
- Change one thing, then repeat the failed test.
- Use player feedback to choose useful improvements.
- Retest the parts affected by an improvement.
Variables in Games examples
1Find what your game remembers
10 steps
- 1IntroductionGive your game a memory
A game remembers more than the picture on screen. It needs values it can find again after each action. A variable is a named store that holds one value, so the game can find it again and change it as play goes on.
You will act out a changing store, then make two stores for a small game. Start with a scrap of paper and two small number cards.
- 2AnalogyA labeled box and its contents
Draw a box labeled "stars" and place a card showing 2 inside. Think of the label as a variable's name and the card as its value.
The label tells you which store to use. The card tells you what is stored there right now.
- 3ExampleReplace the card
Your player finds another star, so replace the card with 3. The name is still "stars". The current value is now 3.
The variable holds one value at a time. To keep the old 2 as well, copy it into another store before replacing it.
- 4ConnectionRemember two different things
Your player also has a room number. That needs its own store: "room". Changing rooms must not wipe out the stars collected.
A second variable lets you keep both values. A current score and a high-score record need separate stores for the same reason.
- 5ChallengeKeep both player values
A game stores "gems" as 4. It must also remember that you are in room 6. How should it store both values?
---reveal---
Keep 4 in "gems" and use a separate "room" variable holding 6. Replacing gems with 6 would lose the gem count.
- 6ExplanationMake a clear name
In Scratch, open Variables and choose "Make a Variable". Type "stars". This name explains the stored value better than "thing".
The variable gets a round block that reports its value. It also gets blocks to set, change, show, and hide it.
- 7ExampleLet two sprites share points
Suppose both Star and Moon award points. Make one "score" variable and choose "For all sprites". Both sprites can then change that same total.
A "For this sprite only" variable is a separate store. Only that sprite's scripts can set or change it.
- 8TipWatch the store on the stage
Check the box beside score to show its variable display. It shows the name and current value. It updates as score changes.
When reading a game, find the set and change blocks. Check which variable each block selects in its menu.
- 9ChallengeRead two named stores
A game's blocks set "shells" to 0 and "chances" to 5. Pearl and Shell both need to add to shells. What does each store mean, and how should shells be shared?
---reveal---
"shells" keeps the collected total; "chances" keeps the chances remaining. Create shells "For all sprites" so both sprites change one total.
- 10RecapRead the label, then the value
A variable gives one current value a name you can find again. Separate jobs need separate stores.
When you open a game, find each store's name, what it remembers, where it starts, and what changes it.
2Trace a changing robot score
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionPredict a score before running
- 2ExplanationChoose a fresh start
- 3ChallengeFind the missing reset
- 4ExampleReplace or add
- 5ExampleUse a minus sign
- 6ConnectionRead one store to change another
- 7ChallengeApply the right kind of update
- 8ExplanationStart the trace
- 9ExampleOpen up the three passes
- 10ExampleCheck the next condition
- 11TipKeep each snapshot separate
- 12ChallengeTrace a fresh loop
- 13ChallengeRepair a trace after a reset
- 14RecapFollow the running order
3Save replies and choose the right response
15 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionMake a program answer back
- 2ExplanationInput starts the exchange
- 3ExampleAsk for the team name
- 4ExampleKeep the name through another reply
- 5ChallengeKeep a reply you will need
- 6ExplanationShow what the program did
- 7ExampleBuild the team greeting
- 8TipReport a change after it happens
- 9ChallengeChoose the order for a new total
- 10ExampleInclude the exact winning score
- 11ExplanationCheck before another pass
- 12ExampleCatch a value that skips zero
- 13ConnectionCompare with an earlier record
- 14ChallengeSave and announce a new record
- 15RecapFollow information through the program
4Build a timed collecting game
15 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionGive each game event one effect
- 2ExampleSet points and chances
- 3ExplanationOne touch can last many passes
- 4TipMove the object out of contact
- 5ChallengeMake a hit count once
- 6ConnectionChange how fast objects fall
- 7ExampleChoose a short countdown
- 8ExampleFollow one clock tick
- 9ExampleReach the end of the clock
- 10ExplanationLet movement run beside the clock
- 11ChallengeFind a clock that runs too fast
- 12ExampleKeep a fastest race time
- 13ConnectionReward finishing early
- 14ChallengeApply the bonus to a finished game
- 15RecapCheck contacts and clock passes
5Plan and test a small rescue game
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionChoose a small first build
- 2ExampleDescribe the player's job
- 3ExampleList the two changing stores
- 4ExplanationSketch what the blocks should do
- 5ExampleMake the rules checkable
- 6ChallengePlan a different reward
- 7TipBuild and check a few blocks
- 8ExampleRecord a failed test
- 9ExplanationTry the values near a decision
- 10ExampleChange one thing and repeat
- 11ChallengeTest an improvement against its plan
- 12RecapUse your plan to judge the game
Variables in Games practice questions
Set 1: Find and follow game values10 Practice Questions
Question 1 of 10
Show answerHide answer
Question 2 of 10
Show answerHide answer
Question 3 of 10
Show answerHide answer
Question 4 of 10
change score by -3 once. What is your new score?Show answerHide answer
Question 5 of 10
What is the final value of "gems" after this script?
set gems to 1
repeat 3
change gems by 2
if gems > 4 then
change gems by -1
Show answerHide answer
Question 6 of 10
set teamName to (answer) go?Show answerHide answer
Question 7 of 10
Show answerHide answer
Question 8 of 10
Show answerHide answer
Question 9 of 10
Show answerHide answer
Question 10 of 10
Show answerHide answer
Set 2: Make the blocks match the rules10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
change score by (bonus) runs once. What are the two values afterward?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
What are "points" and "chances" after this script?
set points to 0
set chances to 2
repeat 3
change points by 3
if points > 5 then
change chances by -1
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
ask [Choose a pet] and wait. The player has typed "otter" but has not submitted it. What must happen before the blocks below ask can run?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 3: Trace choices and check game endings10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
What is the final value of "tokens"?
set tokens to 2
repeat 3
change tokens by 3
if tokens > 6 then
set tokens to 1
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
join [Keys: ] (keys). What message appears?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
What does the sprite say at the end?
set stones to 0
repeat until stones > 4
change stones by 3
change stones by -1
say (stones)
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
change y by (fallStep). Its fall step changes from -4 to -7 at the next level. How does its movement change on each pass?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
if score = 12 then stop all never ends play. What change fixes this ending rule?Show answerHide answer
Save this lesson to see this answer.
Set 4: Solve new game problems10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
The player replies "Comet", "green", and "Orbit" to these three questions, in order. What do badgeName and badgeColor hold at the end, and what change keeps the original badge name?
ask [Badge name?] and wait
set badgeName to (answer)
ask [Badge color?] and wait
set badgeColor to (answer)
ask [Team name?] and wait
set badgeName to (answer)
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
join [Coins: ] (coins) and then adds 2 to coins. Coins started at 7. Why does its bubble say "Coins: 7" when the display now shows 9?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
repeat until timeLeft = 0, and what comparison should replace it?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
score > 8 after each rescue. A test reaches exactly 8 but gives no winning message. What repair and retest check the boundary?Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Actual result
Algorithm
Answer block
Ask-and-wait block
B
Best time
Boundary
Bug
Built-in timer
Built-in value
C
Change amount
Change block
Comparison
lives = 0 becomes true when no lives remain."Condition
Countdown
D
Debugging
E
Equal to
Event
Expected result
F
Fall step
Final value
Fixed number
Flowchart
G
Greater than
score > 10 is false."H
High score
I
Initializing
Input
J
Join block
L
Less than
Lives
Loop pass
N
Negative change
O
Operator block
Output
P
Player feedback
Processing
R
Reporter block
Reset
Reset timer block
Round block
S
Say block
Score
Set block
Shared variable
Sprite-only variable
Starting value
Success criterion
T
Test case
Testing
Touching check
Trace table
Tracing
V
Value
Variable
Variable display
Variable name
Variable plan
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.