Game Development Reference
In-Depth Information
At that point, the condition is evaluated, but it's 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 you've programmed here is integer division using the while instruction. Of course, in
this case it's easier to simply use the following single line of code that achieves the same result:
var val = 10 % 3;
If you want to draw the player's number of lives on the screen, you can use a while instruction to do
so quite efficiently:
var i = 0;
while (i < numberOfLives) {
Canvas2D.drawImage(sprites.lives,
new Vector2(i * sprites.lives.width + 15, 60));
i = i + 1;
}
In this while instruction, the body is executed as long as the variable i contains a value less
than numberOfLives (which is a variable you assume is declared and initialized to a certain value
somewhere else). Every time the body is executed, you draw the sprite on the screen, and then you
increment i by 1. The result is that you draw the sprite on the screen exactly numberOfLives times!
So, you're using the variable i here as a counter .
Note You start with i equal to zero and continue until i has reached the same value as numberOfLives .
This means the body of the while instruction is executed for the values 0, 1, 2, 3, and 4 of i . As a result,
the body is executed five times.
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.
The position at which you draw the sprites depends on the value of i . This way, you can draw
each sprite a bit further to the right, so they're nicely placed in a row. The first time you execute the
body, you draw the sprite at x-position 15, because i is 0. The next iteration, you draw the sprite at
x-position sprites.lives.width + 15 , the iteration after that at 2 * sprites.lives.width + 15 , and
so on. In this case, you use the counter not only to determine how often you 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 .
Figure 10-2 shows a screenshot of the Painter game where the number of lives is indicated at upper
left on the screen.
 
Search WWH ::




Custom Search