Introduction to C++ with Game Development: Part 5, Conditions

by IGAD of NHTV University at Feb 24, 2010

This tutorial is about the condition commands C/C++ has which allow you to
make important decisions that can help you to control the way your program
flows. You already did some of these conditions when you did loops without
realizing it, so this is just a cool way to make those decisions more explicit.

Getting the stuff you need

As with the last couple of tutorials, we'll use the template again. But you
will need to know how to use your sprites from lesson 3 so if you have not done
lesson 3 please go back and do so now. Extract a fresh version of the template,
remove the hello world code, and let's begin.

To Draw or not to Draw

In your Game::Tick loop from the last lesson
you put a sprite on screen. Lets do that again.

Try and run this and make sure you get an image on screen at the top left
corner.

Ok?

Good lets continue. Let's move our sprite down a little bit and then move it
around using your variable skills. Above the tick routine and below the
Sprite definition add a couple of
"Global" variables.

int SpriteX = 0;
int SpriteY = 100;
bool Visible = true;

Hopefully these variable names will explain their function. Notice also that
I initialsed them when I created them, so that they will have initial values .
Of course you should make sure these variables are also set up in any initialise
routines you may write.

This looks a little different from our rule of IF – THEN – ELSE because in
C/C++ the THEN part is assumed and the else is also assumed in a simple line
like this.

But if you read it...

if (Visible == true)

Is the same as "if some value we want to test is true"

There is no THEN because it is assumed

But the next part is:

theSprite.Draw( SpriteX, SpriteY, m_Screen );

Which corresponds to

"then do something"

So where's the "else do something else."? Well it is there….only in this case
it does nothing…or more correctly it simple does the next line

Do you know now why your tank did not appear when you set
Visible to false?

This kind of condition check can be very powerful lets try a more useful
version.

Add another variable after the Visible, which you should have reset to
true.

bool Direction = true;

Now lets alter our tick a little more to allow our tank to move left and
right across the screen, we will make a coding assumption before than that if
Direction is true that we are going right, and if
Direction is false
we are
moving left.