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.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-05-29 14:44:17 +0000
Seen: 7 times
Last updated: May 29 '23
Is it feasible to utilize a Toggle Button to switch among multiple classes exceeding 2?
What is the process for generating a dynamic subdomain/URL using vue.js?
How can I create a transition on click using CSS without the need for JavaScript?
How can the style of the loader be modified while the form submission is being processed?
I'm attempting to develop a Javascript-based comments section for my website.
What are some feasible methods to enable MIDI file playback on a web browser?