Help with Roll Dice system

Twine Version: 2.3.14
Story Format: SugarCube 2.34.1

So, I am still noob to twine, this is probably stupid questions.

Question 1: I want to define the player stats ramdomly. So, when the player start the game and load the passage with the stats, they will be:

STR: <<print $STR>>
DEX: <<print $DEX>>

All the stats will be between 1 - 6, so, for STR for example, I have to use <<set $STR = random(1, 6)>> Is that right? Should I put this in the storyinit or is there a better way to do it?

Question 2: About dice rolls… In this context: the player has to make a dex test. The test consists of: 3D6 + STAT (in this case DEX) VS 15. Lets say the player DEX is 4. So: 3D6 + 4 vs 15. If they roll a 15 or more they pass, if not they faill. My question is, what is the code for that?

Question 3: Can I put this dice roll and its result in the same passage? Like that:

Passage A

Time for a DEX test!

Button: roll the dice
You got: x
You needed: y

If sucess: [[passage B]]
If fail: [[passage C]]

Something like that!

Sure, StoryInit is a good place to initialize your variables. If there’s a character creation screen, you could also possibly put it there (so if you revisit that page you’ll roll a new character). You want to make sure it happens before you try to use or display the stats, and you want to make sure it doesn’t happen again unless you mean it to.

Rolls could look something like this: _roll is a temporary variable that only exists for one page, since you probably don’t need to store it in the game history.

<<linkreplace "Roll the dice">>
<<set _roll to $STR + random(1,6) + random(1,6) + random(1,6)>>
You got: _roll
You needed: 15
<<if _roll >= 15>>[[passage B]]
<<else>>[[passage C]]
1 Like

If I may expand on Josh’s answer, I wrote this little dice rolling function a while back and I think it’s what you’re looking for. Following the same advice I gave on adding the function to your script here, just add this function:

window.rollDice = function(die) {
	var dice = die.toUpperCase().split("D");
	var plus = dice[1].split("+");
	if (plus.length > 1) {
		dice[1] = plus[0];
		plus = parseInt(plus[1]);
	else plus = 0;
	dice[0] = parseInt(dice[0]);
	dice[1] = parseInt(dice[1]);

	var total = 0;
	var a;
	for (a = 0; a < dice[0]; ++a) {
		total += random(1, dice[1]);
	total += plus;
	return total;

Then in your story script do what Josh suggested

<<set $STR = 2>>
<<linkreplace "Roll the dice">>
<<set _roll to rollDice("3D6") + $STR>>
You got: _roll
You needed: 15
<<if _roll >= 15>>[[passage B]]
<<else>>[[passage C]]

My function also allows for hard coding bonuses into what you pass it, so you could do rollDice("2d10+5") and that’d work as you expected. The “d” can be upper or lower case also.


thank you!!

thank you!

I have a dice roller in my macro set: Custom Macros