Put a dice roll result in the sheet

From Wiki Let's Role

Summary

In this tutorial, we'll see how to fill a label based on a dice roll result.

You will see that the solution can only be made with some script. Here the solution uses a specific action button in the Dice Result.

Step by step

  1. create an element that will trigger the dice roll. Ex: a label with the id labelTriggeringDiceRoll
  2. create an element that will receive the dice roll result (or anything based on the dice roll). Ex: a label with the id labelReceivingDiceRoll
  3. in the script, add an click event that rolls the dice you need by using Dice.roll
  4. Dice.roll accepts a list of action buttons as last parameter. This is an object whose keys are the Button label that will be shown in the Dice log and values are a function that is called when the button is clicked (see the Actions section in the Dice API documentation). The parameter given to the function is a Dice Result.
  5. If correctly defined, the function can have an elegant access to the sheet.
  6. This access to the sheet is the main way to change the desired label.

Final code

Here is the code used in the System Builder Demo

const labelToClick = sheet.get("labelTriggeringDiceRoll");      // get the label that will roll dice when clicked
labelToClick.on("click", function () {                          // handle the click event on the label
  const actions = {};                                           //   initiate the list of actions in dice result
  actions[_("Apply to sheet")] = function (dice) {              //   add a translated button label
    const labelToFill = sheet.get("labelReceivingDiceRoll");    //     when click on the action button, the code can access to the label to change
    labelToFill.value("Last roll was " + dice.total);           //     set anything in the label, based on dice
  };
  Dice.roll(sheet, "10+1D10", "Roll strength", "all", actions); // Roll the dice
});

Live example

You can see a live example in the System Builder Demo in the tab "Fill with Dice Result" (you must run a table in order to have dice rolls, the sheet preview block dice rolls)

You can check the code in the function initFillWithRoll that illustrates what is described in this tutorial.