Game Development Reference
In-Depth Information
Using postfix operators to change variable values by 1
The new code assigns the three new variables their initial values:
cqaooaoNai]ejejc9-,7
cqaooaoI]`a9,7
c]iaOp]pqo97
The total number of guesses the player gets before the game ends is stored in the cqaooaoNai]ejejc
variable. You gave it an initial value of -,, but you can, of course, change it to make the game easier
or harder to play. You also want to count the number of guesses the player makes, so a cqaooaoI]`a
variable is created to store that information. When the game first starts, the player has obviously not
made any guesses, so the cqaooaoI]`a variable is set to ,. The c]iaOp]pqo variable is a string that will
be used to output this new information, and you'll see how it does this in a moment. It contains no
text initially (it is assigned a pair of empty quotation marks).
Now take a look at the first two new directives in the kjCqaoo>qppkj?he_g event handler:
cqaooaoNai]ejejc))7
cqaooaoI]`a''7
When you play the game, you'll notice that Guesses Remaining in the output text field decreases by 1,
and the Guesses Made increases by 1. That's all thanks to the two lines that use the extremely conve-
nient postfix operators .
Remember the discussion of increment and decrement operators from the previous chapter? If you
want to increase a value by 1, you can write some code that looks like this:
jqi^anR]ne]^ha'9-7
It turns out that increasing values by 1 is something programmers want their programs to do all the
time. So frequently, in fact, that AS3.0 has special shorthand for it: a double-plus sign, which is a spe-
cial kind of operator called a postfix operator. You can use it to rewrite the previous line of code like
this:
jqi^anR]ne]^ha''7
It will do exactly the same thing: add 1 to the value of the variable. You can use another postfix opera-
tor, the double-minus sign, to subtract 1 from the value of a variable in exactly the same way, like
this:
jqi^anR]ne]^ha))7
Postfix operators change the value of the variable by 1 each time the directive runs. The directives
in the kjCqaoo>qppkj?he_g event handler are run each time the Guess button is clicked, which, of
course, is each time the player makes a guess. Having the cqaooaoNai]ejejc and cqaooaoI]`a vari-
ables update with each button click is therefore a perfect way to keep track of the number of guesses
the player has made.
 
Search Nedrilad ::




Custom Search