Recipe 5.9 Simulating Dice

5.9.1 Problem

You want to mimic rolling dice.

5.9.2 Solution

Use the randRange( ) method to generate random numbers in the desired range.

5.9.3 Discussion

You can use the randRange( ) method from Recipe 5.7 to generate random integer values to simulate rolling a die or dice in your Flash movies. Mimicking the rolling of dice is an important feature in many games you might create using ActionScript, and the randRange( ) method makes your job easy.

```// Include Math.as to have access to Math.randRange(  ).
#include "Math.as"

// Calling Math.randRange(  ) with min = 1 and max = 6 generates
// a random number as though you are rolling a six-sided die.
die1 = Math.randRange(1, 6);

// Add the results of two "rolls" together to simulate a pair of six-sided dice.
dice = Math.randRange(1, 6) + Math.randRange(1, 6);``` Math.randRange(1, 12) does not correctly simulate a pair of six-sided dice because the results must be between 2 and 12, not 1 and 12. Does Math.randRange(2, 12) give the correct result? No, it does not! Math.randRange(2, 12) results in a smooth distribution of numbers from 2 to 12, whereas in games played with two dice, 7 is much more common than 2 or 12. Therefore, you must simulate each die separately and then add the results together. Furthermore, in many games, such as backgammon, game play depends on the individual value of each die, not simply the total of both dice, so you'll want to keep these results separate.

It is not uncommon to want to generate a random number and then store it for later use. If you want to reuse an existing random number, be sure to save the result rather than generating a new random number, as per the warning in Recipe 5.8. Note the difference in the following two scenarios. In the first scenario, dice will always be the sum of die1 plus die2:

```die1 = Math.randRange(1, 6);
die2 = Math.randRange(1, 6);
dice = die1 + die2;```

In the second scenario, there is no relation between the value of dice and the earlier random values stored in die1 and die2. In other words, even if die1 and die2 add up to 7, dice stores a completely different value between 2 and 12:

```die1 = Math.randRange(1, 6);
die2 = Math.randRange(1, 6);
dice = Math.randRange(1, 6) + Math.randRange(1, 6);```

You can call Math.randRange( ) with any range to simulate a multisided die. Here, we call it with a range from 1 to 15 to generate a random number as though the user is rolling a 15-sided die, as might be found in a role-playing game such as Dungeons and Dragons:

`myRoll = Math.randRange(1, 15);`

Here is an example that uses the drawing methods to simulate a single 15-sided die. It uses the randRange( ) method to generate random values when the user clicks on the die_mc movie clip.

```// Include both Math.as and DrawingMethods.as (from Chapter 4) to access the methods
// used in this example.
#include "Math.as"
#include "DrawingMethods.as"

// Create a die_mc clip on _root. Within that clip, create a shape_mc clip and draw a
// filled (white fill, black outline) square using drawRectangle(  ).
_root.createEmptyMovieClip("die_mc", 1);
die_mc.createEmptyMovieClip("shape_mc", 1);
die_mc.shape_mc.lineStyle(1, 0x000000, 100);
die_mc.shape_mc.beginFill(0xFFFFFF, 100);
die_mc.shape_mc.drawRectangle(50, 50);

// Create a text field within die_mc and set the font size to 24.
die_mc.createTextField("num", 2, 0, 0, 0, 0);
die_mc.num.autoSize = true;
tf = new TextFormat(  );
tf.size = 24;
die_mc.num.setNewTextFormat(tf);

// Move die_mc so that it is visible on stage.
die_mc._x = 200;
die_mc._y = 200;

// Create a method that generates random numbers and sets
// the text field of the die to display those values.
die_mc.onToss = function (  ) {

// Generate a random number from 1 to 15 to mimic a 15-sided die.
var randNum = Math.randRange(1, 15);

// Display the value in the text field and center the text field on the die.
this.num.text = randNum;
this.num._x = -(this.num._width/2);
this.num._y = -(this.num._height/2);

// Count to 20 and set the onEnterFrame(  ) method to null. This animates the die for
// 21 frames and then stops until it is clicked again.
this.count++;
if (this.count > 20) {
this.count = 0;
this.onEnterFrame = null;
}
};

// When the user clicks on the die_mc movie clip, set onEnterFrame to the onToss(  )
// method so it is called at the frame rate until 20 frames have animated. After
// which, onEnterFrame(  ) becomes null and nothing more happens until the user clicks
// on it again.
die_mc.onRelease = function (  ) {
this.onEnterFrame = this.onToss;
};```  Preface  Part I: Local Recipes  Chapter 1. ActionScript Basics  Chapter 2. Runtime Environment  Chapter 3. Color  Chapter 4. Drawing and Masking  Chapter 5. Numbers and Math  Introduction  Recipe 5.1 Representing Numbers in Different Bases  Recipe 5.2 Converting Between Different Number Systems  Recipe 5.3 Rounding Numbers  Recipe 5.4 Inserting Leading or Trailing Zeros  Recipe 5.5 Formatting Numbers for Display  Recipe 5.6 Formatting Currency Amounts  Recipe 5.7 Generating a Random Number  Recipe 5.8 Simulating a Coin Flip  Recipe 5.9 Simulating Dice  Recipe 5.10 Simulating Playing Cards  Recipe 5.11 Generating a Unique Number  Recipe 5.12 Converting Angle Measurements  Recipe 5.13 Calculating the Distance Between Two Points  Recipe 5.14 Determining Points Along a Circle  Recipe 5.15 Converting Between Units of Measurement  Recipe 5.16 Calculating Asset Appreciation (Future Value)  Recipe 5.17 Calculating Retirement Savings  Recipe 5.18 Calculating the Loan (Mortgage) You Can Afford  Recipe 5.19 Calculating Loan Amortization or Annuities  Chapter 6. Arrays  Chapter 7. Movie Clips  Chapter 8. Text  Chapter 9. Strings  Chapter 10. Dates and Times  Chapter 11. Forms  Chapter 12. Objects and Custom Components  Chapter 13. Programming Sound  Part II: Remote Recipes  Part III: Applications  Appendix A. Unicode Escape Sequences for Latin 1 Characters  Colophon