Ask Your Question
3

How can a JavaScript dice game be created that checks the current roll set against all past roll sets until a specific number of distinct rolls are obtained?

asked 2023-05-29 14:44:17 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-05-29 15:12:02 +0000

bukephalos gravatar image

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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2023-05-29 14:44:17 +0000

Seen: 7 times

Last updated: May 29 '23