Random Numbers: Math.Random()

The built-in Math class includes a function called Math.random() This function will return a number that is greater or equal to zero and less than 1.

For example, trace(Math.random()); might show 0.05449842009693384 or 0.6588504211977124

If we write the statement n=Math.random(); n could have a value from 0.00000 up to .9999 (with a few more decimal places.)
If we multiply that value by 6, we will get values from 0.0000 to 5.9999 (with more decimal places, but still less than 6.)
If we take the integer portion of that number we will have values from 0 to 5.
If we then add 1 to that value we will have a value from 1 to 6, exactly what we need to roll dice! We can put this all together into 1 statement:
var n: int= Math.random()*6+1;
In general, the formula is Math.random()*number of values+first value;

For example if we want random values from 10 to 12 there are 3 possible values (10, 11, and 12) and the first value is 10. Our statement would be

n=Math.random()*3+10

In this lesson we will create a movie that rolls dice. Get Adobe Flash player

  1. Start a new ActionScript3 movie.
  2. Add a button and name it btnRoll.
  3. Create a movie clip called Die with the frames as show below, 1 dot in frame 1, 2 dots in frame 2. etc.
    dice
  4. It will be easier if you make a layer with the square, lock it, and then add another layer with the dots.
  5. Add two die to the movie and name them die1 and die2.
  6. Write the code as shown below:
die1.stop(); //to keep it from playing all of the frames
die2.stop();

btnRoll.addEventListener(MouseEvent.CLICK,rolldice);
function rolldice(e:MouseEvent): void { 
  var n=int(Math.random()*6+1);  //random number from 1 to 6
  die1.gotoAndStop(n);  //stop at that frame
  n=int(Math.random()*6+1); //get a new random frame for the 2nd die
  die2.gotoAndStop(n);
}//rolldice
Download the movie to experiment.

NEXT: Debugging the Dice movie