Thursday, August 28, 2008

Conditional Expressions and if-else statements

One of the cool things about games is that the computer makes decisions based on what it happening in the game. Maybe it is a cooldown timer on a super powerful ability, or maybe it is determining if that NPC should cast a heal spell on itself. How does the computer know to do these things? The programmer used conditional expressions.

Basically a conditional expression is a formula that either produces a True (1) result, or a False (0) result. Torque has a full toolset of conditional operators that you can use to make decisions in your programming:

< Less Than
> Greater Than
<= Less Than or Equal To
>= Greater Than or Equal To
== Equal To (since = is used for assigning variable values)
!= Not Equal To
$= String Equal To
!$= String Not Equal To

Additionally, you can tie two or more conditional expressions together to product a True or False result pertaining to BOTH using:

&& AND (both expressions must be TRUE)
|| OR (either expression must be TRUE)

Lastly, There is an operator that gives you the opposite result (True becomes False and vice versa):

! NOT

So, now we have our ability to tell whether an expression is True or False. But what good is it? Well, you could use it to assign a 1 or 0 value to a variable and then use that variable in a computation. OR, you could use it to set up branches in your program using the if-else statement.

So, what is a branch? Basically you are telling the computer to do one of two things. Its kind of like deciding what you want to do for dinner. Do you have enough money to order pizza? If yes, get on the phone! If not, start making that sandwich.

Translated to if-else, this decision would look like:

if (%money > 20)
{
%dinner = "Pizza!"
}
Else
{
%dinner = "Sandwich."
}

Another cool thing about if-else statements is that you can "nest" them. You can have one inside the other. You put the most limiting expression in the first "if" statement and work your way down to the least limiting. You can also have an else statement for each additional "if".

Using nested if-else statements, we can greatly expand our dinner choices:

if (%money > 10)
{
if (%money > 15)
{
if (%money > 20)
{
%dinner = "Pizza!"
}
else
{
%dinner = "Burger!"
}
else
{
%dinner = "Sandwich."
}

Though this is a little hard to read, it is actually very efficient. If %money < 10, then the program just straight to $dinner = "Sandwich". The rest of the if-else structure is only run as needed. Only if %money > 20 does the whole thing run, and even then the "else" statements are skipped completely!

No comments: