Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One way to approach creating a JavaScript dice game that checks the current roll set against all past roll sets until a specific number of distinct rolls are obtained is to use an array to store the past rolls and continually check if the current roll is already in the array.

Here is a potential code snippet:

// Set variables for desired distinct rolls and current number of distinct rolls const desiredDistinctRolls = 4; let currentDistinctRolls = 0; // Create an empty array to store past rolls const pastRolls = []; // Roll function generates a random number between 1 and 6 function roll() { return Math.floor(Math.random() * 6) + 1; } // Play function loops until desired number of distinct rolls is reached function play() { while (currentDistinctRolls < desiredDistinctRolls) { // Roll the dice const roll1 = roll(); const roll2 = roll(); // Check if roll combination has already occurred const rollSet = `${roll1},${roll2}`; if (pastRolls.indexOf(rollSet) === -1) { // If the roll set is not in the past rolls array, add it and increment the distinct roll count pastRolls.push(rollSet); currentDistinctRolls++; } // Log the current roll set and the number of distinct rolls achieved so far console.log(`Rolls: ${roll1}, ${roll2} | Distinct rolls: ${currentDistinctRolls}`); } // Once the desired number of distinct rolls is reached, end the game console.log(`Game over! You achieved ${desiredDistinctRolls} distinct rolls.`); } // Call the play function to start the game play(); 

This code generates two random dice rolls each iteration and checks if the combination has already occurred by creating a string of the two rolls separated by a comma. If the roll set is not in the pastRolls array, it is added and the current distinct roll count is incremented. The game continues until the desired number of distinct rolls is reached, at which point it logs a message and ends the game.