Forum Discussion
DeannaRoberts
2 months agoCommunity Member
Roll Die JavaScript
I've been using JavaScript to allow the learner to roll die. When they land on a '6', a topic of content will launch. I'm finding learners are rolling multiple times, sometimes over 8 times before hi...
Kingman
2 months agoCommunity Member
There are some major things you need to achieve with your code.
Most importantly is you need to have a figure for the max number of attempts, and you need to tell your JS to keep counting up until it hits that number.
Try and tinker with the following and edit the maxAttempts as needed.
function rollDice() {
let maxAttempts = 4; // Limit the number of rolls, update as needed
let rolls = [];
for (let i = 0; i < maxAttempts - 1; i++) {
rolls.push(Math.floor(Math.random() * 5) + 1); // Roll between 1 and 5
}
rolls.push(6); // Ensure a '6' appears in the final attempt
// Shuffle array to randomise when '6' appears
rolls.sort(() => Math.random() - 0.5);
return rolls;
}
var x = rollDice();
var player = GetPlayer();
player.SetVar("NewDice", x);