[RPG] How to execute code depending on a die value in AnyDice

anydicedice

I'd like to be able to have a conditional test the value of a die or set of dice. Here's a simple example using a d6, but I'm looking for a way to check values of arbitrary dice sets.

X: 1d6

if X = 1 {
  \execute arbitrary code\
  output 0
}
if X = 2 {
  \execute other arbitrary code\
  output 1
}
\and so on for other values of X.\

If you plug this into AnyDice right now, you'll get this rather unhelpful error.

calculation error
Boolean values can only be numbers, but you provided "d{?}".
Depending on what you want, you might need to create a function.

I searched the documentation and function library for a way to typecast the die value to a number so that it could work in booleans, but found nothing. I tried creating a separate variable to hold the boolean, as seen here:

X: 1d6
Y: X = 1

if Y {
  ...

But that didn't work either. I looked at several other questions related to looking for unusual values in AnyDice, but they all use various probability tricks to solve the specific problem instead of applying a general solution. This question mentions the [count] function, so I tried using that, but to no avail.

X: 1d6

if [count 1 in X] = 1 {
  ...

This outputs the same error as the code above. With a tool as powerful as AnyDice, there must be a way to do something as simple as execute code based on the value of a die. How can this be done?

Best Answer

What you need to do is have your conditional inside a function with a number parameter. Then when you pass it a die, anydice will roll the die at that time and use the result in the function.

function: X:n conditional {

if X = 1 {execute arbitrary code here}

if X = 2 {execute arbitrary code here}

if X = 3 {execute arbitrary code here}

if X = 4 {execute arbitrary code here}

if X = 5 {execute arbitrary code here}

if X = 6 {execute arbitrary code here}

}

output [d6 conditional]

There are some slightly more practical examples of this technique in my answer here.

Related Topic