dice

package module
v0.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 3, 2022 License: MIT Imports: 6 Imported by: 0

README

dice

'dice' is a package built to make it easy to construct complicated rolls quickly. It allows for these rolls to be saved, loaded, and easily modified through the use of tags.

Basic Usage

Quick Start

To create any roll, it starts with a simple roll := dice.Create(N) command. This will create a N sided die, which can then be rolled with result := roll.Roll(). The Roll() method returns a Result object which looks like this:

type Result struct {
    Sides  int      `json:"sides"`
    Rolls  []Result `json:"rolls"`
    Values []int    `json:"values"`
    Total  int      `json:"total"`
}

An example of more advanced rolls looks something like this:

r := Create(8).Multiple(2) // Roll two d8s
s := Create(20).Advantage() // Roll a d20 at advantage

In general, rolls are created through chaining operations like this such that each operation applies its method to all previous operations. An example explained is shown below.

r := Create(6).Disadvantage().Multiple(2)
s := Create(4).Multiple(2)
t := Merge(r, s)

A := t.AnalyzeTime(1.0, 12)

This will create a single roll t which consists of rolling two d4s, and adding that result to rolling a d6 at disadvantage twice. It will then analyze the roll by continuously rolling the definition on 12 different threads for 1.0 seconds (Returning an Analysis object). This particular roll has an average roll of ~10 with a standard deviation of ~2.5.

// The Analysis object stores information about many trials.
type Analysis struct {

    // Combined values of each roll in a standard array.
    Rolls map[int]int

    // The number of trials for this analysis. The length of the "Rolls"
    //     attribute should be equal to this.
    N int

    // The mean value of the trial.
    Mean float64

    // The standard deviation of the trial.
    Deviation float64

    // The standard deviation up and down
    DeviationUp   float64
    DeviationDown float64

    // Timing information, in seconds
    Duration float64
}
Roll Operations
Aggregations
Reroll Conditions
Built-Ins

Advanced Usage

In addition to using the built-in methods, you can customize your Roll Operations as well.

Custom Usage

In addition to customizing your Roll Operations, you can also create your own Roll Operations, Aggregations, and Reroll conditions. These will not have methods attached to the Definition objects, which are slightly inconvenient, but it will allow you to use the custom definitions for it to work.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddAggregationFunction

func AddAggregationFunction(name string, aggregation AggregationFunction)

Call this function to add an aggregation function to the aggregation map so that it

may be loaded and unloaded easily via a json format.

func AddRerollCondition

func AddRerollCondition(name string, f RerollCondition)

Call this function to add an reroll function to the reroll map so that it

may be loaded and unloaded easily via a json format.

func AddRollOperation

func AddRollOperation(name string, f RollOperation)

Call this function to add an rollOperation function to the rollOperation map so that it

may be loaded and unloaded easily via a json format.

func Aggregate_CustomMultiply added in v0.0.2

func Aggregate_CustomMultiply(results *[]Result, params map[string]any) ([]int, int)

Aggregate_Multiply returns the multiplication of all the values in the array.

func Aggregate_CustomSpan added in v0.0.2

func Aggregate_CustomSpan(results *[]Result, params map[string]any) ([]int, int)

Aggregate_CustomSpan returns the difference between the Nth maximum value in the array

and the Mth minimum value of the array

func Aggregate_CustomSum

func Aggregate_CustomSum(results *[]Result, params map[string]any) ([]int, int)

Create a sum aggregation which takes some arbitrary indices from the sorted

result array to include in the total.

func Aggregate_Last

func Aggregate_Last(results *[]Result, _ map[string]any) ([]int, int)

Aggregate_Last just returns the last values in the array. Commonly used for

something like a rerolling until a certain condition is met.

func Aggregate_LastN added in v0.0.2

func Aggregate_LastN(results *[]Result, params map[string]any) ([]int, int)

Aggregate_Last just returns the last values in the array. Commonly used for

something like a rerolling until a certain condition is met.

func Aggregate_Multiply

func Aggregate_Multiply(results *[]Result, _ map[string]any) ([]int, int)

Aggregate_Multiply returns the multiplication of all the values in the array.

func Aggregate_Span

func Aggregate_Span(results *[]Result, _ map[string]any) ([]int, int)

Aggregate_Span returns the difference between the maximum value in the array

and the minimum value of the array

func Aggregate_Sum

func Aggregate_Sum(results *[]Result, _ map[string]any) ([]int, int)

Aggregate_Sum takes all the sorted results and returns all the values

from them while summing them. This is commonly used in scenarios when
you want to roll multiple of the same dice. "4d6" would use this to
sum together all the d6 results into one total.

func Condition_AtLeast

func Condition_AtLeast(roll Result, _ *[]Result, params map[string]any) bool

Will reroll if the total is greater than or equal to N.

func Condition_AtMost

func Condition_AtMost(roll Result, _ *[]Result, params map[string]any) bool

Will reroll if the total is less than or equal to N.

func FetchMapValue

func FetchMapValue[T any](m map[string]any, key string, standard T) T

Internal function for quickly fetching parameters without erroring

func GetRerollDepth

func GetRerollDepth() int

Function for fetching the max depth. Again, this is to avoid race conditions.

func SetRerollDepth

func SetRerollDepth(depth int)

Simple function to handle internal variables without cause race conditions.

func SetSeed

func SetSeed(s int64)

Set the default Source based on an int64 seed.

func SetSource

func SetSource(s *rand.Rand)

Set the default Source based on a provide *rand.Rand Source.

Types

type AggregationFunction

type AggregationFunction func(results *[]Result, params map[string]any) ([]int, int)

An aggregation function takes a list of results and returns the values to

use from them as well as the new total value based on the aggregation.

func FetchAggregation

func FetchAggregation(r *Definition) AggregationFunction

Method for fetching an aggregation generator from the map without causing

race conditions.

type Analysis

type Analysis struct {

	// Combined values of each roll in a standard array.
	Rolls map[int]int

	// The number of trials for this analysis. The length of the "Rolls"
	// 	attribute should be equal to this.
	N int

	// The mean value of the trial.
	Mean float64

	// The standard deviation of the trial.
	Deviation float64

	// The standard deviation up and down
	DeviationUp   float64
	DeviationDown float64

	// Timing information, in seconds
	Duration float64
}

The Analysis object stores information about many trials.

type Definition

type Definition struct {

	// Base information needed for functionality. This information is not stored anywhere
	// 	when saving as it is unneccessary. (The Source can be set whenever and the roll
	// 	is dynamically generated each time.)
	Source       *rand.Rand              `json:"-"`
	RollFunction func(*rand.Rand) Result `json:"-"`

	// If the definition consists of children definitions, they will appear here
	Definitions []*Definition `json:"definitions,omitempty"`

	// Tags. These are used to update the roll as necessary or to store additional
	// 	information about the roll when it's saved.
	Tags map[string]TagLocation `json:"tags,omitempty"`

	// Include all the basic definition parameters as well
	DefinitionParameters
}

The Definition struct is the base object for the entirity of the "dice"

package. The Roll Definition contains many methods which are expanded upon
in other files. Each Definition requires:
	Source: The main random Source from which any random numbers which are
		necessary will be generated from.
	roll: A function which produces a Result object. This function
		will be editted as Definition functions are called.

Each definition also contain DefinitionParameters which define how that particular

roll is constructed. See the DefinnitionParameters definition for more detail.

func Create

func Create(sides int) *Definition

Main function for starting a roll Defintion. You start a definition by instantiating

the number of sides of the die to roll. You can expand and combine the dice later using
the other methods and public functions.

func InitializeRollOperation added in v0.0.2

func InitializeRollOperation(
	operationName string,
	parameters DefinitionParameters,
	definitions ...*Definition,
) *Definition

Generic part of a roll operation which every roll operation will need to call

func Merge

func Merge(definitions ...*Definition) *Definition

Merge multiple Definitions and then aggregate them by summing

them all together. Very simple wrapper.

func MergeAdvantage

func MergeAdvantage(definitions ...*Definition) *Definition

Merge Definitions and take the largest total.

func MergeDisadvantage

func MergeDisadvantage(definitions ...*Definition) *Definition

Merge Definitions and take the lowest total.

func MergeHighest

func MergeHighest(N int, definitions ...*Definition) *Definition

Merge Definitions and take the N highest.

func MergeIndices added in v0.0.2

func MergeIndices(indices []int, definitions ...*Definition) *Definition

Merge Definitions and take indices described. (Sorted from min to max)

func MergeLowest

func MergeLowest(N int, definitions ...*Definition) *Definition

Merge Definitions and take the N lowest.

func Roll_Math

func Roll_Math(
	parameters DefinitionParameters,
	definitions ...*Definition,
) *Definition

Roll Math will perform some math operation to a single definition

func Roll_Merge

func Roll_Merge(
	parameters DefinitionParameters,
	definitions ...*Definition,
) *Definition

This is the main wrapper for all roll types which contain combining multiple

definitions into a single array and then aggregating them in some way. This is
*almost a carbon copy of the CustomMultiple function. The main reason to do it
this way is to allow more straightforward use to the users without worrying about
performance hits or overcomplications from writing a more general function.

func Roll_Multiple

func Roll_Multiple(
	parameters DefinitionParameters,
	definitions ...*Definition,
) *Definition

func Roll_Reroll

func Roll_Reroll(
	parameters DefinitionParameters,
	definitions ...*Definition,
) *Definition

This is the main wrapper for all definitions which include some sort of rerolling

mechanism. Common use cases involve "exploding" where you keep rerolling a die if
you roll greater than a certain value and sum together all the results. Another use
case would be something like "Halfling Luck" in D&D, where anytime you roll a 1, you
can reroll the die and take the new value. If you need to aggregate results, pass in
an AggregationFunction, otherwise, leave it nil.

The rerollCondition is given a reference to the result being constructed which contains

all the rolls that need to be aggregated (if it is an aggregation) as well as the most
recent roll. If it is an aggregation, the most recent roll will be in the array. If not,
the rolls of the first parameter will be empty.

func (*Definition) Add

func (r *Definition) Add(N int) *Definition

func (*Definition) Advantage

func (r *Definition) Advantage() *Definition

Roll a Definition twice and take the larger value.

func (*Definition) AnalyzeN added in v0.0.2

func (r *Definition) AnalyzeN(N int, threads int) *Analysis

Analyze a roll for a given number of rolls.

func (*Definition) AnalyzeTime added in v0.0.2

func (r *Definition) AnalyzeTime(duration float64, threads int) *Analysis

Analyze a roll for a given amount of time.

func (*Definition) CustomMultiple added in v0.0.2

func (r *Definition) CustomMultiple(N int, parameters DefinitionParameters) *Definition

Completely customizable version of Roll_Multiple. (Basically just a simple

binding for easier use inline)

func (*Definition) Disadvantage

func (r *Definition) Disadvantage() *Definition

Roll a Definition twice and take the larger value.

func (*Definition) Divide

func (r *Definition) Divide(F float64) *Definition

func (*Definition) Explode

func (r *Definition) Explode(N int) *Definition

Explode will continue to reroll if you roll at least a specified value.

It will then aggregate all the resulting rolls into a single value.

func (*Definition) Multiple

func (r *Definition) Multiple(N int) *Definition

Roll multiple of the same Definition and then aggregate them by summing

them all together. Very simple wrapper.

func (*Definition) MultipleAdvantage

func (r *Definition) MultipleAdvantage(N int) *Definition

Roll a Definition N number of times and take the highest roll

func (*Definition) MultipleDisadvantage

func (r *Definition) MultipleDisadvantage(N int) *Definition

Roll a Definition N number of times and take the lowest roll

func (*Definition) MultipleHighest

func (r *Definition) MultipleHighest(N, M int) *Definition

Roll N dice and take the highest M of them to sum

func (*Definition) MultipleLowest

func (r *Definition) MultipleLowest(N, M int) *Definition

Roll N dice and take the highest M of them to sum

func (*Definition) Multiply

func (r *Definition) Multiply(F float64) *Definition

func (*Definition) Power

func (r *Definition) Power(F float64) *Definition

func (*Definition) RandomSource

func (r *Definition) RandomSource() *Definition

Set a random Source for the roll. Just use the system time as the Source seed.

This is more thread-safe than using the default Source.

func (*Definition) RerollLessThan

func (r *Definition) RerollLessThan(N int) *Definition

Reroll until you get a value greater that or equal to N.

func (*Definition) Roll

func (r *Definition) Roll() Result

Execute a Roll on the Definition object. The Definition object is built to be

repeatable so that this function can be called over and over without messing
up internal data.

func (*Definition) SetFunction

func (r *Definition) SetFunction() *Definition

This function takes a *Definition object which doesn't have it's internal roll function set and will create it based on all the combined roll definitions.

func (*Definition) SetTag added in v0.0.2

func (r *Definition) SetTag(tag string, value interface{}) *Definition

This is used to set a specific tag to a new value

func (*Definition) Subtract

func (r *Definition) Subtract(N int) *Definition

func (*Definition) Tag added in v0.0.2

func (r *Definition) Tag(tag string, tagType TAG, parameter string) *Definition

This is used to set a tag for a roll. This should only be done when a definition

is the current highest level of definition. For example, don't ever do this:

x := dice.Create(6)
y := dice.Create(8)
z := dice.Merge(x, y)

x.Tag(...)

func (*Definition) WithSeed

func (r *Definition) WithSeed(s int64) *Definition

Set the Source seed for the roll

func (*Definition) WithSource

func (r *Definition) WithSource(s *rand.Rand) *Definition

Set the Source value for the roll

type DefinitionParameters

type DefinitionParameters struct {

	// Number of sides if this is a base case roll.
	Sides int `json:"sides,omitempty"`

	// Name of the roll this roll uses. If the name is "roll", then the
	// 	sides parameter will also be populated and it is considered the "base case".
	RollType       string         `json:"rollType"`
	RollParameters map[string]any `json:"rollParameters,omitempty"`

	// The aggregation describes how the results were aggregated together
	AggregationType       string         `json:"aggregationType,omitempty"`
	AggregationParameters map[string]any `json:"aggregationParameters,omitempty"`

	// The reroll describes which reroll condition to use
	RerollCondition           string         `json:"rerollCondition,omitempty"`
	RerollConditionParameters map[string]any `json:"rerollConditionParameters,omitempty"`
}

Helper struct for definition parameters. For each of RollType, AggregationType,

and RerollCondition, define which will be used, and any parameters
necessary for that function to operate nominally.

type RerollCondition

type RerollCondition func(roll Result, rolls *[]Result, params map[string]any) bool

Definition for the rerollCondition function type. These functions require

the most recent roll paired with a list of all existing rolls to be passed
in. RerollConditions which use just the first result should be
compatible with all reroll use cases. Those that require the second parameter
will only work with Reroll Definitions which have an aggregation function defined.
In order to avoid errors in this case, just make sure those conditions are
written in such a way that they don't break when an empty array is passed in.

type Result

type Result struct {
	Sides  int      `json:"sides"`
	Rolls  []Result `json:"rolls"`
	Values []int    `json:"values"`
	Total  int      `json:"total"`
}

The Result struct holds the information about all the rolls that went into

producing the ending total. It contains the objects:
	Sides: The number of sides for the roll. This is only applicable for the
		base-case. For each other case, this value will be set to "0".
	Rolls: A list of all sub-results. This is only applicable if not the base-case.
		During the base case, this will be a nil value. The array will automatically
		be sorted in ascending order of the "Total" value on each of the Results.
	Values: A list of values which contribute to the total. This is useful during
		cases where more rolls happen than those that actually count. An example would
		be during an advantage roll, two rolls happen, but only one is counted and
		added to the "Values" array.
	Total: The total value of all the integers in "Values". Sometimes this includes an
		additional operation to be performed.

type RollOperation

type RollOperation func(
	DefinitionParameters,
	...*Definition,
) *Definition

A RollOperation is a sequence of procedures for combining or augmenting and existing set of rolls.

func FetchRollOperation

func FetchRollOperation(functionType string) RollOperation

Method for fetching a roll function from the map without causing

race conditions.

type TAG added in v0.0.2

type TAG string

Define a basic enum for the tag locations to be used in tagging

const (
	TAG_SIDES                       TAG = "sides"
	TAG_ROLL_PARAMETERS             TAG = "rollParameters"
	TAG_AGGREGATION_PARAMETERS      TAG = "aggregationParameters"
	TAG_REROLL_CONDITION_PARAMETERS TAG = "rerollConditionParameters"
)

type TagLocation added in v0.0.2

type TagLocation struct {

	// Index at which this tag appears in the definitions array
	Indices []int `json:"indices,omitempty"`

	// Used to determine which field the tag represents. Viable values are:
	// 	sides, rollParameters, aggregationParameters
	// 	and rerollConditionParameters.
	Type TAG `json:"type,omitEmpty"`

	// The TagParameter is only applicable in the case where a "parameters"
	// 	tag type is provided.
	Parameter string `json:"parameter,omitempty"`
}

Helper struct for managing tags and their locations

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL