# VBForums CodeBank > CodeBank - C# >  [.NET 2.0+] Rolling Dice

## jmcilhinney

VB version here.

Quite a few people have asked how to "roll dice" for games.  Here's the "proper" way.  First you define a Die class to represent a die.
CSharp Code:
public class Die{    private static Random faceSelector = new Random();     private int _faceCount;    private int _value;     public int FaceCount    {        get        {            return this._faceCount;        }        set        {            this._faceCount = value;        }    }     public int Value    {        get        {            return this._value;        }    }     public Die(int faceCount)    {        if (faceCount <= 0)        {            throw new ArgumentOutOfRangeException("faceCount", "Dice must have one or more faces.");        }         this._faceCount = faceCount;    }     public int Roll()    {        this._value = faceSelector.Next(1, this.FaceCount + 1);        return this.Value;    }}
Note that the Die class has a static variable of type Random.  This means that there is one and only one Random object for the class.  This same object is used to generate random sides for each and every instance of the class.

The Roll method generates the random number based on the number of faces the current die has.  It returns this value and it is also available via the Value property thereafter.

Many games use multiple dice though, so it's appropriate to define a class that represents multiple Die objects.

(Note that this code snippet is labelled as VB.NET code but it is obvioulsy C#.  It's just that the C# and CSharp code parsers seem to butcher opening square brackets, which is a problem when indexing in C# code.)
CSharp Code:
public class DieCollection : System.Collections.ObjectModel.Collection<Die>{    public int[] RollAll()    {        int[] values = new int[this.Count];         for (int index = 0; index < values.Length; index++)        {            values[index] = this.Items[index].Roll();        }         return values;    }}
There's very little code to write for this class because it inherits all the standard collection functionality for the generic Collection<Die> class.  Inherited functionality includes an indexer of type Die and an Add method that takes a Die parameter.

Here's an example of using these classes.  As is supposed to be the case in OOP, using the types is dead simple because all the work is done inside the classes themselves.  You simply create a DieCollection, create and add as many Die objects as you need and call RollAll:
CSharp Code:
// Create the collection to store the dice.DieCollection dice = new DieCollection(); // Add two six-sided dice.dice.Add(new Die(6));dice.Add(new Die(6)); // Roll all the dice.int[] rolls = dice.RollAll(); // Display the values rolled.foreach (int roll in rolls){    MessageBox.Show(roll.ToString(), "You rolled a ...");}
Obviously for a game you would assign your DieCollection to a member variable and then call it's RollAll method each time a player had to roll the dice.  You would not create a new DieCollection and Die objects each time you wanted to roll.

----------


## jmcilhinney

Actually, having thought about it seems more appropriate to me for the RollAll method to return the total of all the rolls.
CSharp Code:
public class DieCollection : System.Collections.ObjectModel.Collection<Die>{    public int RollAll()    {        int total = 0;         foreach (Die die in this.Items)        {            total += die.Roll();        }         return total;    }}
If you want the individual values you could loop through the dice and get their Value properties:
CSharp Code:
// Create the collection to store the dice.DieCollection dice = new DieCollection(); // Add two six-sided dice.dice.Add(new Die(6));dice.Add(new Die(6)); // Roll all the dice.int total = dice.RollAll(); // Display the total rolled.MessageBox.Show(total.ToString(), "You rolled..."); // Display the values rolled.foreach (Die die in dice){    MessageBox.Show(die.Value.ToString(), "You rolled a...");}
You could even add a property to the DieCollection that returned all the Values:
vb.net Code:
public int Values{    get    {        int[] faces = new int[this.Count];         for (int index = 0; index < this.Count; index++)        {            faces[index] = this.Items[index].Value;        }         return faces;    }}

----------


## jmcilhinney

Having read this thread, I like the idea of using Dependency Injection as suggested by Evil_Giraffe.  As a result, I have improved the code for my dice and added that functionality, along with some other additions.
CSharp Code:
/// <summary>
/// Represents a single die.
/// </summary>
public class Die
{
#region Fields
     /// <summary>
    /// The number of faces a die will have by default, if not specified by the user.
    /// </summary>
    public static readonly int DefaultFaceCount = 6;
     /// <summary>
    /// The object used to select a die face.
    /// </summary>
    private IRandomNumberGenerator faceSelector;
 #endregion Fields
 #region Properties
     /// <summary>
    /// Gets or sets the number of faces the die has.
    /// </summary>
    /// <value>
    /// An <b>Int32</b> containing the number of faces.
    /// </value>
    /// <remarks>
    /// The default number of faces is defined by <see cref="DefaultFaceCount" />
    /// </remarks>
    public int FaceCount { get; set; }
     /// <summary>
    /// Gets the current face value of the die.
    /// </summary>
    /// <value>
    /// An <b>Int32</b> containing the current face value.
    /// </value>
    /// <remarks>
    /// This would be the side facing upwards on a physical die.
    /// </remarks>
    public int Value { get; private set; }
 #endregion Properties
 #region Constructors
     /// <summary>
    /// Creates a new instance of the <see cref="Die" /> class with the default number of faces and using the default random number generator.
    /// </summary>
    /// <remarks>
    /// The default number of faces is defined by <see cref="DefaultFaceCount" />
    /// </remarks>
    public Die()
        : this(DefaultFaceCount)
    {
    }
     /// <summary>
    /// Creates a new instance of the <see cref="Die" /> class using the default random number generator.
    /// </summary>
    /// <param name="faceCount">
    /// The number of faces the die has.
    /// </param>
    public Die(int faceCount)
        : this(faceCount, new RandomNumberGenerator())
    {
    }
     /// <summary>
    /// Creates a new instance of the <see cref="Die" /> class with the default number of faces.
    /// </summary>
    /// <param name="randomNumberGenerator">
    /// The object used to select a die face.
    /// </param>
    /// <remarks>
    /// The default number of faces is defined by <see cref="DefaultFaceCount" />
    /// </remarks>
    public Die(IRandomNumberGenerator randomNumberGenerator)
        : this(DefaultFaceCount, randomNumberGenerator)
    {
    }
     /// <summary>
    /// Creates a new instance of the <see cref="Die" /> class.
    /// </summary>
    /// <param name="faceCount">
    /// The number of faces the die has.
    /// </param>
    /// <param name="randomNumberGenerator">
    /// The object used to select a die face.
    /// </param>
    public Die(int faceCount, IRandomNumberGenerator randomNumberGenerator)
    {
        if (faceCount <= 0)
        {
            throw new ArgumentOutOfRangeException("faceCount", "Dice must have one or more faces.");
        }
         this.FaceCount = faceCount;
         if (randomNumberGenerator == null)
        {
            randomNumberGenerator = new RandomNumberGenerator();
        }
         faceSelector = randomNumberGenerator;
    }
 #endregion Constructors
 #region Methods
     /// <summary>
    /// Rolls the die.
    /// </summary>
    /// <returns>
    /// An <b>Int32</b> that is the new value of the <see cref="Value"/> property.
    /// </returns>
    public int Roll()
    {
        Value = faceSelector.GenerateRandomNumber(FaceCount);
         return Value;
    }
 #endregion Methods
}

CSharp Code:
/// <summary>
/// A collection to store multiple <see cref="Die" /> objects.
/// </summary>
public class DieCollection : System.Collections.ObjectModel.Collection<Die>
{
#region Constructors
     /// <summary>
    /// Creates a new, empty instance of the <see cref="DieCollection" /> class.
    /// </summary>
    public DieCollection()
    {
    }
     /// <summary>
    /// Create a new instance of the <see cref="DieCollection" /> with the specified number of items.
    /// </summary>
    /// <param name="dieCount">
    /// The initial number of items in the collection.
    /// </param>
    /// <remarks>
    /// The initial items all have the default number of faces, as defined by the <see cref="Die.DefaultFaceCount" /> field, and use the default random number generator.
    /// </remarks>
    public DieCollection(int dieCount)
    {
        for (var i = 0; i < dieCount; i++)
        {
            Items.Add(new Die());
        }
    }
     /// <summary>
    /// Create a new instance of the <see cref="DieCollection" /> with the specified number of items.
    /// </summary>
    /// <param name="dieCount">
    /// The initial number of items in the collection.
    /// </param>
    /// <param name="faceCount">
    /// The number of faces each die has.
    /// </param>
    /// <remarks>
    /// The initial items all use the default random number generator.
    /// </remarks>
    public DieCollection(int dieCount, int faceCount)
    {
        for (var i = 0; i < dieCount; i++)
        {
            Items.Add(new Die(faceCount));
        }
    }
     /// <summary>
    /// Create a new instance of the <see cref="DieCollection" /> with the specified number of items.
    /// </summary>
    /// <param name="dieCount">
    /// The initial number of items in the collection.
    /// </param>
    /// <param name="randomNumberGenerator">
    /// The object used to select a die face.
    /// </param>
    /// <remarks>
    /// The initial items all have the default number of faces, as defined by the <see cref="Die.DefaultFaceCount" /> field.
    /// </remarks>
    public DieCollection(int dieCount, IRandomNumberGenerator randomNumberGenerator)
    {
        for (var i = 0; i < dieCount; i++)
        {
            Items.Add(new Die(randomNumberGenerator));
        }
    }
     /// <summary>
    /// Create a new instance of the <see cref="DieCollection" /> with the specified number of items.
    /// </summary>
    /// <param name="dieCount">
    /// The initial number of items in the collection.
    /// </param>
    /// <param name="faceCount">
    /// The number of faces each die has.
    /// </param>
    /// <param name="randomNumberGenerator">
    /// The object used to select a die face.
    /// </param>
    public DieCollection(int dieCount, int faceCount, IRandomNumberGenerator randomNumberGenerator)
    {
        for (var i = 0; i < dieCount; i++)
        {
            Items.Add(new Die(faceCount, randomNumberGenerator));
        }
    }
 #endregion Constructors
 #region Methods
     /// <summary>
    /// Rolls all the dice in the collection and returns the sum of the results.
    /// </summary>
    /// <returns>
    /// An <b>Int32</b> containing the summed values of all dice.
    /// </returns>
    public int RollAll()
    {
        return Items.Sum(die => die.Roll());
    }
 #endregion Methods
}
Here is the interface and default implementation for dependency injection:
CSharp Code:
/// <summary>
/// Represents an object that can generate a random integer.
/// </summary>
public interface IRandomNumberGenerator
{
    /// <summary>
    /// Generates a random integer.
    /// </summary>
    /// <param name="max">
    /// The maximum value (inclusive) that should be generated.
    /// </param>
    /// <returns>
    /// An <b>Int32</b> containing a random number.
    /// </returns>
    /// <remarks>
    /// The value returned should never be less than 1.
    /// </remarks>
    int GenerateRandomNumber(int max);
}
  /// <summary>
/// Represents an object that can generate a random integer.
/// </summary>
/// <remarks>
/// This class is the default random number generator for the <see cref="Die" /> class.
/// </remarks>
public class RandomNumberGenerator : IRandomNumberGenerator
{
    /// <summary>
    /// The underlying random number generator.
    /// </summary>
    /// <remarks>
    /// A single <b>Random</b> object is used by all instances to avoid duplicate results when multiple values are generated quickly.
    /// </remarks>
    private static Random rng = new Random();
     /// <summary>
    /// Generates a random number.
    /// </summary>
    /// <param name="max">
    /// The maximum value (inclusive) that can be generated.
    /// </param>
    /// <returns>
    /// An <b>Int32</b> containing a random number.
    /// </returns>
    /// <remarks>
    /// The value returned will never be less than 1.
    /// </remarks>
    public int GenerateRandomNumber(int max)
    {
        if (max < 1)
        {
            throw new ArgumentOutOfRangeException("max", max, "Value cannot be less than 1.");
        }
         return rng.Next(1, max + 1);
    }
}
If you want to create dice that behave randomly then you use one of the constructors that doesn't have a parameter of type IRandomNumberGenerator.  In that case, an instance of the RandomNumberGenerator class will be used, which uses a shared Random object internally.

If you wanted your dice to produce known results for testing purposes then you could create your own implementation of the IRandomNumberGenerator interface and then pass an instance of that to one of the Die constructors that has a parameter of that type.  Your dice will then produce the results you expect and you can test that your "game" behaves as expected under those circumstances.

----------

