//Steve Rhoades //Sample Code //Art Institute of Seattle //IfElse package{ import flash.display.*; public class IfElse extends MovieClip{ //constants are a great way to keep your code manageable //they cannot be changed, and allow you to define commonly used values in an easy to find place const VERY_HIGH:String = "Excellent"; const HIGH:String = "Great"; const PRETTY_HIGH:String = "Good"; const NORMAL:String = "Average"; const PRETTY_LOW:String = "Sub-Par"; const LOW:String = "Poor"; const VERY_LOW:String = "Abysmal"; public function IfElse(){ /** *The if/else statement is one of the core tools in the programmer's toolbelt *it takes the following form * *if(condition){ * //stuff to do if the condition is true *}else if(condition2){ * //stuff to do if condition2 is true *}else{ * //stuff to do in any other case *} * * *We'll build an interesting example here. Let's take a look at a bit of code that might be used *to obscure confusing stats and make a D&D based RPG more casual friendly */ var stat:uint; var statDescription:String; //look you can declare multiple variables in one line var die1:uint, die2:uint, die3:uint; /** * This is how we generate a random number. * Math.random() will, at runtime, give you a random real number between 0 and 1 * (remember, there's a lot of those :) ) * Math.floor will take whatever is in the parentheses attached to it, and remove everything fractional. * So Math.floor(3.1417) turns into 3 * So, what we have here: * Math.floor(Math.random() * 6) + 1. * starting at the center (Math.random() * 6), generates a random number, and multiplies it by six, giving * us some sort of real number between 0 and 6. * When we do Math.floor() to that, we get a WHOLE number that's 0-5 (we didn't round up, we just cut off * the fraction). * So we add one to that, and we get a random integer, 1-6 as our final result. */ die1 = Math.floor(Math.random() * 6) + 1; die2 = Math.floor(Math.random() * 6) + 1; die3 = Math.floor(Math.random() * 6) + 1; stat = die1 + die2 + die3; //now let's look at the if else statement if(stat >= 17){ statDescription = VERY_HIGH; }else if(stat >= 15){ statDescription = HIGH; }else if(stat >= 13){ statDescription = PRETTY_HIGH; }else if(stat >= 9){ statDescription = NORMAL; }else if(stat >= 7){ statDescription = PRETTY_LOW; }else if(stat >= 5){ statDescription = LOW; }else{ statDescription = VERY_LOW; } trace("Your stat of " + stat + " is " + statDescription); } } }