ExamplesIntermediate

Random games and dice

Build fair dice challenges, prompt decks, rare outcomes, and repeatable random results with Sugar.

The examples are complete Boop Code modules. To use one on an Item, place its top-level variables and functions in Item Code, then put its text declaration inside an action.

One-roll challenge

var difficulty = 12 with {
  input: true,
  min: 2,
  max: 20,
};

text {
  let roll = Rand::roll("1d20");

  if roll >= difficulty {
    show chip "Success";
    "@1 needed {difficulty} and rolled {roll}!"
  } else {
    show chip "Failed";
    "@1 needed {difficulty} but rolled {roll}."
  }
}

The dice embed and the returned text always agree because the program rolls once and saves the result in roll.

Prompt deck

text {
  let prompts = (
    "Tell the group your most embarrassing secret",
    "Choose someone to complete a dare",
    "Show the last photo you saved",
    "Let another player ask you anything"
  );
  let position = Rand::pick(1..=len(prompts));
  show chip format("Prompt #{position}");
  prompts[position]
}

Lists begin at 1, so the random position starts at 1 too.

Rare result

Add named media called jackpot and regular_win.
text {
  if Rand::chance(5) {
    show media &jackpot;
    show chip "5% jackpot";
    "@1 hit the rare result!"
  } else {
    show media &regular_win;
    "@1 receives the regular prize."
  }
}

Rand::chance(5) returns true about 5 percent of the time.

Hidden dice

Use false when the result should affect the program without showing JOI’s dice embed:

var health = 100;
const maxHealth = 100;

text {
  let damage = Rand::roll("2d6+3", false);
  health = clamp(health - damage, 0, maxHealth);
  "The trap deals {damage} damage. Health: {health}"
}

Time-sensitive result

text "@1 receives {}." with if Date::now().weekday == "friday" then "the Friday double bonus" else "today's regular bonus";

Use an Automation instead when a stored value should change on a schedule. Time functions only read the current day or time.