Game Development Reference
In-Depth Information
The position at which we draw the sprites depends on the value of
i
. This way,
we can draw each sprite a bit further to the right, so that they are nicely placed
in a row. The first time we execute the body, we draw the sprite at
x
-position 15,
because
i
is 0. The next iteration, we draw the sprite at
x
position
livesSprite.Width
+
15, the iteration after that at
2
livesSprite.Width
+ 15, and so on. In this case, we use
the counter not only to determine how often we will execute instructions, but also
to
change what the instructions do
. This is a very powerful feature of an iteration
instruction such as
while
. Because of the looping behavior, a
while
-instruction is also
called a
while
-
loop
.
∗
9.3.1 A Shorter Notation for Incrementing Counters
Many
while
-instructions, especially those that use a counter, have a body that con-
tains an instruction for incrementing a variable. This can be done with the instruc-
tion:
i=i+1;
(As a side note, especially because of these kinds of instructions, it is unwise to
pronounce the assignment as 'is'. The value of
i
can of course never be the same as
i+1
, but the value of
i
becomes
the old value of
i
, plus 1.) These kinds of instructions
are very common in programs, therefore a special, shorter notation exists that does
exactly the same thing:
i++;
The '++' can be pronounced as 'is incremented'. Because this operator is placed
after the variable that it operates on, the '++' operator is called a
postfix operator
.
For incrementing a variable with more than 1, there is another notation:
i+=2;
which means the same as
i=i+2;
9.4 The
for
-Instruction: A Compact Version of
while
Many
while
-instructions use a counting variable, and therefore have the following
structure: