Monday, September 29, 2008

Switch Statements

So its been a while since my last blog entry. Sorry about that, as usually happens, life sucks. So we move on.

Last time we talked about If Statements and nested If Statements. As you could tell, nesting if's can get really confusing. Switch statements can help a lot with that.

Here is the syntax for a Switch statment:

switch (selection variable)
{
case label1: statement1;
case label2: statement2;
case labelx: statementx;
default: default statement;
}

The selection variable may be either a number, a string, or a variable that is equal to either a number or string. The switch statement then selects the correct case where the label = the selection variable. If no case is found that matches, then the default is used.

Here is an example

switch (%spellnumber)
{
case 1: %spellname = "Fire Ball";
case 2: %spellname = "Poison Cloud";
case 3: %spellname = "Sleep";
case default: %spellname = "Magic Missle";
}

The equivalent if statement would look like this:

if %spellnumber == 1
%spellname = "Fire Ball";
elseif %spellnumber == 2
%spellname = "Poison Cloud";
elseif %spellnumber == 3
%spellname = "Sleep";
else
%spellname = "Magic Missle";

As you can see, for ever 1 line of a switch statement, the if statement requires 2. It might not seem that bad with only 4 selections to choose from, but imagine if there were 50, or 100! And remember, we are looking to make a game here. The more choices for the player the more likely the are to keep playing.

No comments: