En este laboratorio, tú vas a usar variables locales y globales para almacenar información.
En esta página, tú vas a empezar a desarrollar un juego para adivinar un número que usa variables locales para llevar el registro del número secreto.
Number guessing game
that will contain the code for the game. Leave the Block Editor open.
In a number-guessing game, the player tries to guess the computer's secret number. The computer needs a way to store the secret number in a variable so that it can compare it to the player's guesses.
A variable is like a box that can hold one value at a time, such as one word, one costume, or one list (which can contain many things). You can look at what's inside as many times as you want.
script variables
block into the Scripting Area. You can find it in the Variables palette.script variables
block (the way you drag an input) and placing it where you need it in your code.
set
menu lets you select which variable to set. set
block only when you snap it somewhere after the script variables
block.secretNumber ← 7or
secretWord ← "supercalifragilisticexpialidocious"allocates memory for "supercalifragilisticexpialidocious" again; the word was already stored in the code statement, and now a copy is stored in the variable
secretWord. This is not the case in Snap! and most other languages, where there is only one copy that the variable and the code share, which is a more efficient way for programming languages to operate.
list
with constant items, that's when we don't make a copy. This is too hairy for me to fix tonight.
Script variables are a kind of local variable; they work only within the script where they're created. If you drag one into a different script, it won't work. You've seen two kinds of local variables before: inputs to blocks and for
counters.
Show me examples I've seen before.
You have created variables as inputs to blocks that you made:
You have used the counter variable that the for
block gave you:
A local variable can be set or used only in the environment in which it is defined. This term includes inputs to procedures and variables created by the for
or script variables
block.
In algebra, a variable is sometimes used for something whose value you don't know yet, and the goal is to find out its value. In programming you decide the values of variables.
a ← a * 2means something. (Suppose a = 8. First compute the value of
a * 2, namely 16, and then replace the old value of a with 16). Up to now, the only variables you've used are input variables, and you never assign a value to an input because the value is given by the code that calls it. But a script variable won't have a value until you give it one with
set
.a ← 3 b ← a a ← 4 DISPLAY(b)
b ← ais done).
b ← ais done); b doesn't remember that the 3 came from a so it doesn't change when a is changed.
set
command sets the value of the variable k to the value k – m, not m – k.