Forum Discussion

DeannaRoberts's avatar
DeannaRoberts
Community Member
9 days ago

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 hitting a '6'.

Is there a way to limit the number of rolls a learner can take and ensure a '6' pops up within those limited attempts? Here is the JavaScript used:

 function rollDice() {
    // Function to generate a random number between min and max (inclusive)
    function getRandomInt(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    // Create an array with two random numbers between 1 and 5
    const rolls = [getRandomInt(1, 5)];

    // Insert the number 6 at a random position in the array
    const position = getRandomInt(0, 2);
   rolls.splice(position, 0, 6);

    return rolls;
}
var x = rollDice();
//alert("rolls x:"+ x)

var player = GetPlayer();

var diceString = x;

player.SetVar("NewDice",diceString);

  • Kingman's avatar
    Kingman
    Community 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);