Game Development Reference
In-Depth Information
this
.Add(cloud);
Let us look at the complete code one more time:
foreach
(GameObject obj
in
gameObjects)
{
SpriteGameObject c = obj
as
SpriteGameObject;
if
(
/
∗
∗
c is outside of the screen
/
)
{
this
.Remove(c);
SpriteGameObject cloud =
new
SpriteGameObject(...);
// calculate cloud position and velocity
// ...
this
.Add(cloud);
}
}
If you look closely at the code inside the loop, you see that we are removing and
adding objects to a list while we are traversing it with a
foreach
-instruction. If we ran
the program like this, we would get a
System.InvalidOperationException
at some point.
We are allowed to modify the list (adding or removing elements) inside a
foreach
-
instruction, but we can no longer continue traversing the list afterwards, since the
list has changed. Therefore, we need to
break
out of the loop using either a
break
or
a
return
call. As a result, there is a chance that, if two clouds move out of the screen,
one of the two is still outside of the screen after this
foreach
-instruction. However,
in this case it is not a problem, since that cloud will be taken care of in the next
iteration of the game loop.
30.4 Finalizing the Level Progression
To complete the game, we still need to add the game states for dealing with the
event that the player has lost, or that the player has won a level. We approach this
in a fashion similar to how we handled it in the
Penguin Pairs
game, except that
here we have an explicit 'game over' game state, next to the 'level finished' game
state. These states are coded in a fairly straightforward way, similar to how we did
it in previous games. You can find the complete code in the
GameOverState
and
LevelFinished
state classes in the
TickTick5
example belonging to this chapter.
For determining if the player has finished a level, we add a property
Completed
to
the
Level
class that checks for two things:
•
has the player collected all the water drops?
•
has the player reached the end sign?
Both of these things are fairly easy to check. For checking if the player reached the
end sign, we can see if their bounding boxes are intersecting. Checking if the player
has collected all the water drops can be done by verifying that all water drops are
invisible. This is the complete property: