//Steve Rhoades //Sample Code //Art Institute of Seattle //SimpleMath package{ import flash.display.*; public class SimpleMath extends MovieClip{ public function SimpleMath(){ var x:int = 9; var y:int = -2; var z:int = 7; var answer:int; /** *We can perform basic math functions in Actionscript. *Since we want to print out the solutions, we can do it right within the trace call. */ trace(x + y); //addition trace(x - z); //subtraction trace(z * y); //multiplication /** *Division works differently when programming than newbs might expect. Actionscript has it work *differently than many people coming from other languages might expect as well */ //here, despite the fact that we are dividing using integers, we don't do integer math //so the result includes the fractional value trace(x / z); //but HERE, we are saving the result to an integer. So we use integer math. That is, any //fractional information is competely discarded when it is stored in the answer variable answer = x / z; trace(answer); //side note, that of course if you use Numbers, you can't do integer division //the modulus operator here is the final part of the division puzzle. When performing integer math //there is the concept of the "remainder". The math equation below (x modulus z) works like this: //when dividing x by z, what is the remainder? trace(x % z) /** *The Math functions * *Actionscript also features a number of built in Math functions. I know, we haven't really *discussed functions yet, but bear with me. Some examples of the most useful are below. */ trace("starting the functions"); var chance:Number; //sets chance to a (pseudo)random Number between 0 and 1 chance = Math.random(); trace(chance); //rounds off the fractional part of the number, creating an integer chance = Math.floor(chance); trace(chance) //Math.ceil works like floor, but goes up. Math.round follows normal rounding rules //I leave it as an exercise for you to use them. //This all becomes quite useful if you want to generate a random number, as you often do in games //here's code to generate a random INTEGER between 3 and 18 (where did that range come from?) chance = Math.floor(Math.random() * 16) + 3; //here's how the above works: //Math.floor(Math.random() * RANGE) + OFFSET //range represents the difference between the largest possible number and the smallest //offset represents the difference between the smallest possible number and 0 //What's the equation for a random integer [1, 20] //[-100, 100] //[2, 12] trace(chance); } } }