Optional
seed: SeedOptional
results: number[]Protected
_resultsStatic
versionProtected
_nextProtected
_randomProtected
convertProtected
hashProtected
parseOptional
seed: SeedReturns the support of the given distribution.
Protected
Static
parseStatic
uniqidTakes a random key from an object with a key:number pattern
Using a Map allows objects to be specified as keys, can be useful for choosing between concrete objects.
The values to choose from
The random choice from the array
Will return:
rng.weightedChoice({
a: 1,
b: 2,
c: 3,
d: 4
});
Will return:
const diamond = new Item('diamond');
const ruby = new Item('ruby');
const pebble = new Item('pebble');
const choices = new Map();
choices.set(diamond, 1);
choices.set(ruby, 10);
choices.set(pebble, 100);
rng.weightedChoice(choices);
Mean of n uniformly distributed values
Support: [0, 1]
The mean of n uniform values
NumberValidationError If the input parameters are not valid.
A version of the bates distribution that returns gaussian normally distributed results, with n acting as a shape parameter.
Number of values to sum
The mean of n uniform values
NumberValidationError If the input parameters are not valid.
Probability that random number is less than p, returns 1 or 0.
Support: {0, 1}
1 or 0, depending on if random number was less than p
NumberValidationError If the input parameters are not valid.
Generates a value from the Beta distribution.
Support: (0, 1)
Optional
alpha?: numberThe alpha parameter of the Beta distribution, must be positive, default 0.5.
Optional
beta?: numberThe beta parameter of the Beta distribution, must be positive, default 0.5.
A value from the Beta distribution, (0, 1).
NumberValidationError If the input parameters are not valid.
Generates a value from the Beta-binomial distribution.
Support: {0, 1, 2, ..., n}
Optional
alpha?: numberThe alpha parameter of the Beta distribution, default 1, must be positive.
Optional
beta?: numberThe beta parameter of the Beta distribution, default 1, must be positive.
Optional
n?: numberThe number of trials, default 1, must be positive integer.
The number of successes in n trials, {0, 1, 2, ..., n}
NumberValidationError If the input parameters are not valid.
Generates a value from the Binomial distribution.
Probability distribution of getting number of successes of n trials of a boolean trial with probability p
Support: {0, 1, 2, ..., n}
Optional
n?: numberThe number of trials, must be positive integer, default 1.
Optional
p?: numberThe probability of success, must be a number between 0 and 1 inclusive, default 0.5.
The number of successes, {0, 1, 2, ..., n}.
NumberValidationError If the input parameters are not valid.
Generates a Gaussian normal value via Box–Muller transform
There are two ways of calling, either with an object with mean and stddev as keys, or just with two params, the mean and stddev
Support: [0, 1]
A value from the Log-Normal distribution.
NumberValidationError If the input parameters are not valid.
Generates a value from the Cauchy distribution.
Support: (-∞, +∞)
@example:
rng.cauchy({ median: 2, scale: 1 }) rng.cauchy({ median: 2 }) rng.cauchy({ scale: 1 })
Optional
median?: numberThe location parameter (median, sometimes called x0) - default 0.
Optional
scale?: numberThe scale parameter, must be positive - default 1.
A value from the Cauchy distribution (-∞, +∞).
NumberValidationError If the input parameters are not valid.
Generates a value from the Chi-squared distribution.
Support: [0, ∞)
@example:
rng.chiSquared({ k: 2 }) rng.chiSquared(2) // Equivalent
A value from the Chi-squared distribution [0, ∞).
NumberValidationError If the input parameter is not valid.
This function uses the inverse transform sampling method to generate an exponentially distributed random variable.
Support: [0, ∞)
NumberValidationError If the input parameters are not valid.
Generates a random number from the Gamma distribution.
Support: (0, ∞)
Optional
rate?: numberThe rate parameter, must be postive, default 1.
Optional
scale?: numberThe scale parameter, must be postive, ( = 1/rate).
Optional
shape?: numberThe shape parameter, must be postive, default 1.
A random number from the Gamma distribution, from (0, ∞).
rng.gamma({ shape = 0.5, rate = 0.5 })
rng.gamma({ shape = 0.5, scale = 2 })
rng.gamma({ shape = 0.5, rate = 0.5, scale = 2 }) // Redundant as scale = 1 / rate
rng.gamma({ shape = 0.5, rate = 2, scale = 2 }) // Error('Cannot supply scale and rate')
NumberValidationError If the input parameters are not valid.
Generates a gaussian normal number, but with a special skewing procedure that is sometimes useful.
Optional
mean?: numberOptional
skew?: numberOptional
stddev?: numberMust be > 0
A normally distributed number
NumberValidationError If the input parameters are not valid.
Generates a value from the Hermite distribution.
Support: {0, 1, 2, 3, ...}
@example:
rng.hermite({ lambda1: 1, lambda2: 2 }) rng.hermite({ lambda1: 1 }) rng.hermite({ lambda2: 2 })
Optional
lambda1?: numberThe mean of the first Poisson process, must be positive.
Optional
lambda2?: numberThe mean of the second Poisson process, must be positive.
A value from the Hermite distribution, {0, 1, 2, 3, ...}
NumberValidationError If the input parameters are not valid.
This function uses combinations to calculate probabilities for the hypergeometric distribution.
The hypergeometric distribution is a discrete probability distribution that describes the probability of k successes (random draws for which the object drawn has a specified feature) in n draws, without replacement, from a finite population of size N that contains exactly K objects with that feature
Support: {max(0, n+K-N), ..., min(n, K)}
Optional
k?: numberThe number of observed successes, must be positive integer lteq K and n.
Optional
K?: numberThe number of successes in the population, must be positive integer lteq N.
Optional
n?: numberThe number of draws, must be positive integer lteq N.
Optional
N?: numberThe population size, must be positive integer.
The probability of exactly k successes in n draws, {max(0, n+K-N), ..., min(n, K)}.
NumberValidationError If the input parameters are not valid.
Sum of n uniformly distributed values
Support: [0, n]
The sum
NumberValidationError If the input parameters are not valid.
Generates a value from the Kumaraswamy distribution.
Support: (0, 1)
@example:
rng.kumaraswamy({ alpha: 1, beta: 2 }) rng.kumaraswamy({ alpha: 1 }) rng.kumaraswamy({ beta: 2 })
Optional
alpha?: numberThe first shape parameter of the Kumaraswamy distribution, must be positive.
Optional
beta?: numberThe second shape parameter of the Kumaraswamy distribution, must be positive.
A value from the Kumaraswamy distribution, (0, 1).
NumberValidationError If the input parameters are not valid.
Generates a value from the Laplace distribution.
Support: (-∞, +∞)
@example:
rng.laplace({ mean: 2, scale: 1 }) rng.laplace({ mean: 2 }) rng.laplace({ scale: 1 })
Optional
mean?: numberThe location parameter (mean) - default 0.
Optional
scale?: numberThe scale parameter, must be positive - default 1.
A value from the Laplace distribution (-∞, +∞).
NumberValidationError If the input parameters are not valid.
Generates a value from the Logistic distribution.
Support: (-∞, +∞)
@example:
rng.logistic({ mean: 2, scale: 1 }) rng.logistic({ mean: 2 }) rng.logistic({ scale: 1 })
Optional
mean?: numberThe location parameter (mean) - default 0.
Optional
scale?: numberThe scale parameter, must be positive - default 1.
A value from the Logistic distribution (-∞, +∞).
NumberValidationError If the input parameters are not valid.
Generates a value from the Log-Normal distribution.
Support: (0, ∞)
@example:
rng.logNormal({ mean: 2, stddev: 1 }) rng.logNormal({ mean: 2 }) rng.logNormal({ stddev: 1 })
Optional
mean?: numberThe mean of the underlying normal distribution - default 0.
Optional
stddev?: numberThe standard deviation of the underlying normal distribution, must be positive - default 1.
A value from the Log-Normal distribution (0, ∞).
NumberValidationError If the input parameters are not valid.
Generates a value from the Generalized Pareto distribution.
Support: [scale, ∞)
Optional
location?: numberThe location parameter, default 0.
Optional
scale?: numberThe scale parameter, must be positive ( > 0), default 1.
Optional
shape?: numberThe shape parameter, must be >= 0, default 0.5.
A value from the Generalized Pareto distribution, [scale, ∞).
rng.pareto({ shape: 0.5, scale: 1, location: 0 });
rng.pareto({ location: 0 });
rng.pareto({ scale: 1 });
rng.pareto({ shape: 0.5 });
NumberValidationError If the input parameters are not valid.
This function uses the fact that the Poisson distribution can be generated using a series of random numbers multiplied together until their product is less than e^(-lambda). The number of terms needed is the Poisson-distributed random variable.
Support: {1, 2, 3 ...}
Poisson distributed random number, {1, 2, 3 ...}
NumberValidationError If the input parameters are not valid.
Generates a value from the Rayleigh distribution
Support: [0, ∞)
@example:
rng.rayleigh({ scale: 2 }) rng.rayleigh(2) // Equivalent
A value from the Rayleigh distribution [0, ∞).
NumberValidationError If the input parameter is not valid.
Generates a value from the Student's t-distribution.
Support: (-∞, ∞)
@example:
rng.studentsT({ nu: 10 }) rng.studentsT(10)
A value from the Student's t-distribution, (-∞, ∞).
NumberValidationError If the input parameter is not valid.
Generates a value from the Wigner semicircle distribution.
Support: [-R; +R]
@example:
rng.wignerSemicircle({ R: 1 }) rng.wignerSemicircle(1)
A value from the Wigner semicircle distribution, [-R; +R].
NumberValidationError If the input parameters are not valid.
The chancy function has a very flexible calling pattern.
You can pass it a dice string, an object or a number.
The purpose of this is to have easily serialised random signatures that you can pass to a single function easily.
All chancy distribution functions (that is, when called with ChancyInterface) can be called with min and max parameters, however, it's highly advised to tune your parameters someway else.
Basically, the function will just keep resampling until a figure inside the range is generated. This can quickly lead to large recursion depths for out of bounds inputs, at which point an error is thrown.
Chancy type input
Optional
depth: numberA randomly generated number or an element from a passed array
rng.chancy({ min: 10 }); // Equivalent to calling rng.random(10, Number.MAX_SAFE_INTEGER)
rng.chancy({ max: 10 }); // Equivalent to calling rng.random(0, 10)
rng.chancy({ min: 0, max: 1 }); // Equivalent to calling rng.random(0, 1)
rng.chancy({ type: 'integer', min: 10 }); // Equivalent to calling rng.randInt(10, Number.MAX_SAFE_INTEGER)
rng.chancy({ type: 'integer', max: 10 }); // Equivalent to calling rng.randInt(0, 10)
rng.chancy({ type: 'integer', min: 10, max: 20 }); // Equivalent to calling rng.randInt(10, 20)
rng.chancy({ type: 'normal', ...args }); // Equivalent to calling rng.normal(args)
rng.chancy({ type: 'normal_integer', ...args }); // Equivalent to calling Math.floor(rng.normal(args))
// You can call any of the 'distribution' type functions with chancy as well.
rng.chancy({ type: 'boxMuller', ...args }); // Equivalent to calling rng.boxMuller(args)
rng.chancy({ type: 'bates', ...args }); // Equivalent to calling rng.bates(args)
rng.chancy({ type: 'exponential', ...args }); // Equivalent to calling rng.exponential(args)
This is your monster file monster.json
:
{
"id": "monster",
"hp": {"min": 1, "max": 6, "type": "integer"},
"attack": "1d4"
}
How about a stronger monster, with normally distributed health strong_monster.json
:
{
"id": "strong_monster",
"hp": {"min": 10, "max": 20, "type": "normal_integer"},
"attack": "1d6+1"
}
Or something like this for boss_monster.json
which has a fixed HP:
{
"id": "boss_monster",
"hp": 140,
"attack": "2d10+4"
}
Then in your code:
import {Rng, Chancy} from GameRng;
const rng = new Rng();
class Monster {
hp = 10;
id;
attack = '1d4';
constructor ({id, hp = 10, attack} : {id: string, hp: Chancy, attack: Chancy} = {}) {
this.id = options.id;
this.hp = rng.chancy(hp);
if (attack) this.attack = attack;
}
attack () {
return rng.chancy(this.attack);
}
}
const spec = await fetch('strong_monster.json').then(a => a.json());
const monster = new Monster(spec);
The chancy function has a very flexible calling pattern.
You can pass it a dice string, an object or a number.
The purpose of this is to have easily serialised random signatures that you can pass to a single function easily.
All chancy distribution functions (that is, when called with ChancyInterface) can be called with min and max parameters, however, it's highly advised to tune your parameters someway else.
Basically, the function will just keep resampling until a figure inside the range is generated. This can quickly lead to large recursion depths for out of bounds inputs, at which point an error is thrown.
Chancy type input
Optional
depth: numberA randomly generated number or an element from a passed array
rng.chancy({ min: 10 }); // Equivalent to calling rng.random(10, Number.MAX_SAFE_INTEGER)
rng.chancy({ max: 10 }); // Equivalent to calling rng.random(0, 10)
rng.chancy({ min: 0, max: 1 }); // Equivalent to calling rng.random(0, 1)
rng.chancy({ type: 'integer', min: 10 }); // Equivalent to calling rng.randInt(10, Number.MAX_SAFE_INTEGER)
rng.chancy({ type: 'integer', max: 10 }); // Equivalent to calling rng.randInt(0, 10)
rng.chancy({ type: 'integer', min: 10, max: 20 }); // Equivalent to calling rng.randInt(10, 20)
rng.chancy({ type: 'normal', ...args }); // Equivalent to calling rng.normal(args)
rng.chancy({ type: 'normal_integer', ...args }); // Equivalent to calling Math.floor(rng.normal(args))
// You can call any of the 'distribution' type functions with chancy as well.
rng.chancy({ type: 'boxMuller', ...args }); // Equivalent to calling rng.boxMuller(args)
rng.chancy({ type: 'bates', ...args }); // Equivalent to calling rng.bates(args)
rng.chancy({ type: 'exponential', ...args }); // Equivalent to calling rng.exponential(args)
This is your monster file monster.json
:
{
"id": "monster",
"hp": {"min": 1, "max": 6, "type": "integer"},
"attack": "1d4"
}
How about a stronger monster, with normally distributed health strong_monster.json
:
{
"id": "strong_monster",
"hp": {"min": 10, "max": 20, "type": "normal_integer"},
"attack": "1d6+1"
}
Or something like this for boss_monster.json
which has a fixed HP:
{
"id": "boss_monster",
"hp": 140,
"attack": "2d10+4"
}
Then in your code:
import {Rng, Chancy} from GameRng;
const rng = new Rng();
class Monster {
hp = 10;
id;
attack = '1d4';
constructor ({id, hp = 10, attack} : {id: string, hp: Chancy, attack: Chancy} = {}) {
this.id = options.id;
this.hp = rng.chancy(hp);
if (attack) this.attack = attack;
}
attack () {
return rng.chancy(this.attack);
}
}
const spec = await fetch('strong_monster.json').then(a => a.json());
const monster = new Monster(spec);
Rounds the results of a chancy call so that it's always an integer.
Not quite equivalent to Math.round(rng.chancy(input)) because it will also transform {type: 'random'} to {type: 'integer'} which aren't quite the same.
'random' has a range of [min, max) whereas interger is [min, max] (inclusive of max).
Given a string dice representation, roll it
Optional
n: Optional
d: numberOptional
plus: numberA random roll on the dice
Rolls dice and returns the results in an expanded format.
Generates a normally distributed number, but with a special clamping and skewing procedure that is sometimes useful.
Note that the results of this aren't strictly gaussian normal when min/max are present, but for our puposes they should suffice.
Otherwise, without min and max and skew, the results are gaussian normal.
Optional
options: { Optional
max?: numberMaximum value allowed for the output
Optional
mean?: numberThe mean value of the distribution
Optional
min?: numberMinimum value allowed for the output
Optional
skew?: numberThe skew to apply. -ve = left, +ve = right
Optional
stddev?: numberMust be > 0 if present
Optional
depth: number = 0used internally to track the recursion depth
A normally distributed number
NumberValidationError If the input parameters are not valid.
MaxRecursionsError If the function recurses too many times in trying to generate in bounds numbers
Determines the maximum value a Chancy input can take.
Chancy input
Maximum value a call to chancy with these args can take
Determines the minimum value a Chancy input can take.
Chancy input
Minimum value a call to chancy with these args can take
Gives the maximum result of a call to dice with these arguments
Optional
n: Optional
d: numberOptional
plus: numberGives the minimum result of a call to dice with these arguments
Optional
n: Optional
d: numberOptional
plus: numberStatic
chancyDetermines the maximum value a Chancy input can take.
Chancy input
Maximum value a call to chancy with these args can take
Static
chancyDetermines the minimum value a Chancy input can take.
Chancy input
Minimum value a call to chancy with these args can take
Static
diceGives the maximum result of a call to dice with these arguments
Static
diceGives the minimum result of a call to dice with these arguments
Create a new instance. Will use a globally set seed, so every instance returnd by this should generate the same numbers.
Optional
seed: SeedAn Rng instance, set to the given seed
Pass a function that will return uniform random numbers as the source of this rng's randomness.
Supersedes and seed setting.
Optional
source: null | RandfuncSeed the random number generator with the given seed.
Optional
seed: SeedCan be a string or a number
Static
predictableCreate a new instance. Will use a globally set seed, so every instance returnd by this should generate the same numbers.
An Rng instance, set to the given seed
Static
unserializeGets the bin "val" sits in when between "min" and "max" is separated by "bins" number of bins
This is right aligning, so .5 rounds up
This is useful when wanting only a discrete number values between two endpoints
The value to bin
The number of bins
Minimum value
Maximum value
The corresponding bin (left aligned)
Parses a string representation of a dice and gives the object representation {n, d, plus}
String dice representation, e.g. '1d6'
The dice representation object
Scales a number from [min, max] to [from, to].
Some might call this linear interpolation.
Min and max default to 0 and 1 respectively
The number - must be 0 <= number <= 1
The min number to scale to. When number === min, will return from
The max number to scale to. When number === max, will return to
The minimum number can take, default 0
The maximum number can take, default 1
A number scaled to the interval [from, to]
Scales a number from [0, 1] to [from, to].
Some might call this linear interpolation
The number - must be 0 <= number <= 1
The min number to scale to. When number === 0, will return from
The max number to scale to. When number === 1, will return to
A normal number scaled to the interval [from, to]
Static
parseParses a string representation of a dice and gives the object representation {n, d, plus}
String dice representation, e.g. '1d6'
The dice representation object
An Rng type that can be used to give predictable results for testing purposes, and giving known results.
You can set an array of results that will be returned from called to _next()
Note: To avoid unexpected results when using this in place of regular Rng, it is only allowed to make the results spread from [0, 1)
The numbers are returned and cycled, so once you reach the end of the list, it will just keep on going.
Example
Example
Example
Example