< Dice‎ | RollerConfig
Revision as of 20:27, 13 April 2017 by Skizzerz (talk | contribs)

RollerConfig.GetRandomBytes Property

From DiceRoller Documentation

Gets or sets the function used to generate random numbers.

  • Namespace: Dice
  • Assembly: DiceRoller (in DiceRoller.dll)

Syntax

public Action<byte[]> GetRandomBytes { get; set; }

Property Value

Type: System.Action<byte[]>

The callback delegate that is used to populate die rolls.

Remarks

The delegate should populate the passed-in byte array with a 4-byte value. The Length of the byte array is 4. The BitConverter.GetBytes overloads may be useful should you wish to transform values of other types, such as integers, into a byte array.

If null, random values will be generated via the RNGCryptoServiceProvider.GetRandomBytes(byte[]) method in the System.Security.Cryptography namespace.

This property is used extensively by the unit-testing suite in order to provide fixed die rolls. It is exposed to applications wishing to override the default random number generator with their own version, or to fix die results as well. For example, in a play-by-post the dice should not be rerolled each time a post is previewed or edited, provided the dice expression did not change. As such, passing in a callback here which "re-rolls" the previously rolled values is one way to accomplish this functionality.

The number of sides to the die being rolled is not passed in as an argument to this callback, the resultant byte array is interpreted as a uint and then converted into the proper range via modulus operations, and addition/subtraction. To prevent bias, this function may be called numerous times in the course of rolling a single die should the value be outside of an even range (so that the modulus does not introduce any potential bias into the final result).

Examples

The following example causes all dice to roll 9. After all, we can never be sure about how random something truly is 😉.

using System;
using Dice;

class Sample
{
    public static void Main()
    {
        Roller.DefaultConfig.GetRandomBytes = GetRandomBytes;
        var result = Roller.Roll("2d20");
        Console.WriteLine(result.Value); // writes 18
    }

    public static void GetRandomBytes(byte[] param)
    {
        // 8 instead of 9 is intentional. For normal dice, this value will be +1 to adjust the number
        // from 1-20 (instead of 0-19). For fudge dice, the number is transformed the other way by subtracting
        // (maxResult + 1). In other words, this number is NOT the number that the die will end up as.
        BitConverter.GetBytes((uint)8).CopyTo(param, 0);
    }
}