Game Development Reference
In-Depth Information
int
val = 10;
while
(val >= 3)
val = val
−
3;
The second instruction is called a
while
-loop. This instruction consists of a kind of
header (
while
(val >= 3)
) and a body (
val = val
−
3;
). The header consists of the word
while
followed by a
condition
between parentheses. The body itself is an instruction.
In this case, the instruction subtracts 3 from a variable. However, it could just as well
have been another kind of instruction such as a method call or accessing a property.
This is the syntax diagram of the
while
-instruction:
When the
while
-instruction is executed, the body is executed multiple times. In
fact, as long as the
condition
in the header yields
true
, the body will be executed.
In this example, the condition is the
val
variable contains a value that is at least 3 or
higher. In the beginning, the variable contains the value 10, so it is certainly higher
than 3. Therefore, the body of the
while
-instruction is executed, and the variable
val
then contains the value 7. The condition is then evaluated again. The variable still
is higher than 3, so the body is executed once more, after which the variable
val
contains the value 4. Again, the value is higher than 3, so the body is executed again
and
val
will contain the value 1. At that point, the condition is evaluated, but it is
no longer
true
. Therefore, the repeating instruction comes to an end. So, after this
piece of code is executed, the variable
val
contains the value 1. In fact what we have
programmed here is the integer division operator using the
while
-instruction.
Of course, it is easier to simply use the division operator in this case, but if we
want to draw the number of lives of the player on the screen, we can use a
while
-
instruction to do this quite efficiently:
int
i=0;
while
(i < lives)
{
∗
spriteBatch.Draw(livesSprite,
new
Vector2(i
livesSprite.Width + 15, 20),
Color.White);
i=i+1;
}
In this
while
-instruction, the body is executed as long as the variable
i
contains a
value smaller than
numberOfLives
. Every time the body is executed, we draw the
sprite on the screen, and then we increment
i
by 1. The result of this is that we
draw the sprite on the screen exactly
numberOfLives
times! So in fact, we are using
the variable
i
here as a
counter
. As you can see, the body of a
while
-instruction
may contain more than a single instruction. If the body contains more than one
instruction, the instructions need to be placed between braces, just like with the
if
-instruction.