Probability with Javascript & Storyline

Oct 18, 2021

Hi there,

I've searched far and wide but had no luck in figuring out what Javascript code would be needed to trigger storyline redirects based on probability. For example, when a user clicks Button 2, they have a 40% chance of going to Slide 5 and a 60% chance of going to Slide 6. 

I'm trying to avoid using variables as there are quite a few slides requiring this treatment in the project I'm working on and I think Javascript could be a much more efficient solution. However if you have any other suggestions I am open to hearing them!

Thank you!

 

1 Reply
Math Notermans

These are exactly what triggers me to find a solution. Well here it is :-)
prob

The script that manages works like this. In the input field you offcourse can set you amount of probability... as seen above its set to 78.

In the code on the button there is a function that uses Math.random() to return true or not. If the value from Math.random() is above 0.78 its true..else its false. A count ( x ) is added when true...and when running a loop for 10000000 times you will see that the probability function returns true around the 78%.

var player = GetPlayer();

function probability(n){
return Math.random() < n;
}

var x = 0;
var prob = player.GetVar("NumericEntry")/100;
for(let i = 0; i < 10000000; i++){
if(probability(prob)){
x += 1;
}
}

player.SetVar("testData", x+" of 10000000 given results by Math.random() were under "+prob+" so, a probability of "+x / 100000+" %");

Adding the sample i made.

Kind regards,
Math