In this lab, you will use two kinds of variables to store information:
On this page, you will develop a number guessing game that uses a script variable to keep track of a secret number.
You have created variables as inputs to blocks that you made:
You have also used the variable that the for
block gave you:
Input variables and for
variables are kinds of local variables; they work only within the script in which they're created. If you drag one into a different script, it won't work. Sometimes you need to create more variables to hold information temporarily while your script is running. The script variables
block lets you do that.
For example, imagine a number-guessing game in which the player tries to guess the computer's secret number. The computer needs to store the secret number so that it can compare the player's guesses to it, but once the game is over, the secret number is no longer needed. If you play the game again, you want a new secret number.
A variable that can be set or used only in the environment in which it is defined. This is the usual computer science term for variables that are defined as inputs to procedures or (in Snap! and some other languages) created by for
or script variables
.
Number guessing game
.script variables
block into the Scripting Area. You can find it in the Variables palette.script variables
block, the way you drag an input variable, and placing it where you need it in your code.
Setting the initial value of a variable is known as initializing the variable.
set
to set the initial value of the variable. The down triangle lets you select the variable you want. Create code that sets secret number to a number randomly chosen from 1 through 10. set
block only when you snap it into the same script that has the script variables
block.You'll want the computer to ask players to guess again and again until they get it right. To do that, you will use the repeat until
block. Repeat until
is a loop (just like repeat
, forever
, and for
) that repeats until a certain condition is met. In this case, the code should repeat until the player's answer equals the secret number.
Repeat until
is a conditional block (like if
). Conditionals make choices based on a condition in the form of a Boolean value (either or
). The condition is checked by a predicate, a true/false question such as
. Predicates always report Boolean values. And they fit into hexagonal input slots, such as in
and
. Predicates help conditionals decide when to do something.
and
, or
, and not
).repeat until
to ask
the player to guess the secret number until their answer
equals the secret number.script variables
block to use it.ask
to ask a question, the user's answer will be reported by answer
.join
to merge the text "You guessed it! My secret number was" with the value of the secret number variable.