Game Development Reference
In-Depth Information
A Number of Different Alternatives
When there are multiple categories of values, you can find out with
if
instructions which case you're
dealing with. The second test is placed after the
else
of the first
if
instruction so that the second
test is executed only when the first test fails. A third test could be placed after the
else
of the
second
if
instruction, and so forth.
The following fragment determines within which age segment a player falls, so that you can draw
different player sprites:
if (age < 4)
Canvas2D.drawImage(sprites.babyPlayer, playerPosition, 0,
{ x : 0, y : 0 });
else if (age < 12)
Canvas2D.drawImage(sprites.youngPlayer, playerPosition, 0,
{ x : 0, y : 0 });
else if (age < 65)
Canvas2D.drawImage(sprites.adultPlayer, playerPosition, 0,
{ x : 0, y : 0 });
else
Canvas2D.drawImage(sprites.oldPlayer, playerPosition, 0,
{ x : 0, y : 0 });
After every
else
(except the last one) is another
if
instruction. For babies, the
babyPlayer
sprite is
drawn and the rest of the instructions are ignored (they're after the
else
, after all). Old players, on the
other hand, go through all the tests (younger than 4? younger than 12? younger than 65?) before you
conclude that you have to draw the
oldPlayer
sprite.
I used indentation in this program to indicate which
else
belongs to which
if
. When there are many
different categories, the text of the program becomes less and less readable. Therefore, as an
exception to the usual rule that instructions after the
else
should be indented, you can use a simpler
layout with such complicated
if
instructions:
if (age < 4)
Canvas2D.drawImage(sprites.babyPlayer, playerPosition, 0,
{ x : 0, y : 0 });
else if (age < 12)
Canvas2D.drawImage(sprites.youngPlayer, playerPosition, 0,
{ x : 0, y : 0 });
else if (age < 65)
Canvas2D.drawImage(sprites.adultPlayer, playerPosition, 0,
{ x : 0, y : 0 });
else
Canvas2D.drawImage(sprites.oldPlayer, playerPosition, 0, { x : 0, y : 0 });
Search WWH ::
Custom Search