Game Development Reference
In-Depth Information
Alright, maybe that is not the right way to do it. Here, we can use again the power
of iteration instructions, such as
while
and
for
.Usinga
while
-loop, we can easily add
500 snowflakes, as follows:
List<Snowflake> snowflakes =
new
List<Snowflake>();
while
(snowflakes.Count < 500)
snowflakes.Add(
new
Snowflake(sprite));
Another place where loops are very useful is for iterating through a list and per-
forming some operation on each element in the list. Look at the following example:
int
i=0;
while
(i < snowflakes.Count)
{
snowflakes[i].Draw(gameTime, spriteBatch);
i++;
}
With the
while
-instruction, we have many ways of controlling how the loop runs.
The following example only draws the items with an even index:
int
i=0;
while
(i < snowflakes.Count)
{
snowflakes[i].Draw(gameTime, spriteBatch);
i=i+2;
}
Or instead of drawing the first item in the list first, we can also walk through the list
backwards:
−
1;
int
i = snowflakes.Count
while
(i >= 0)
{
snowflakes[i].Draw(gameTime, spriteBatch);
i=i
−
1;
}
Or when using a
for
-loop:
−
1; i >= 0; i
−−
)
snowflakes[i].Draw(gameTime, spriteBatch);
for
(
int
i = snowflakes.Count
Check for yourself what happens when these varieties of
while
-instructions are ex-
ecuted. Can you modify the last
for
-instruction so that it draws the items with even
indices only? Or that it only draws items with indices divisible by 5?