Looking for assistance with a School JavaScript assignment focusing on creating a 6-sided dice roller program? Need some guidance on how to approach this task?
The program should allow users to choose how many dices to roll, ranging from 1 to 5. The sum of the dice rolls should always be displayed on the page. If a number 6 is rolled, the program should ignore it in the sum and instead throw two new dice, along with showing an error message indicating this situation.
Once all the dice rolls are completed, the total sum and the number of times the dice were thrown should be displayed. I've made progress with the code so far, but I'm unsure about handling the number 6 and if my approach is correct. Can you provide any insight or suggestions?
JavaScript Code
function rollDice() {
var numDice = document.getElementById("diceNum").value;
var container = document.getElementById("dieContainer");
container.innerHTML = "";
for (var i = 0; i < numDice; i++) {
var diceRoll = Math.floor(Math.random() * 6) + 1;
container.innerHTML += '<div class="dice">' + diceRoll + '</div>';
};
var x, text;
x = document.getElementById("diceNum").value;
if (isNaN(x) || x < 1 || x > 5) {
window.alert('Input not valid');
document.getElementById("dieContainer").style.display = "none";
} else {
document.getElementById("dieContainer").style.display = "block";
}
};
Update:
let diceThrows = numDice;
let sum = 0;
while(diceThrows > 0) {
var diceRoll = Math.floor(Math.random() * 6) + 1;
if(diceRoll == 6) {
diceThrows += 2;
console.log("You got a 6 and two new dices were thrown");
document.getElementById("msg").innerHTML = "You got a 6 and two new dices were thrown";
} else {
sum += diceRoll;
console.log(sum);
document.getElementById("msg").innerHTML = "Result: " + sum;
}
container.innerHTML += '<div class="dice">' + diceRoll + '</div>';
diceThrows -= 1;
}
I have successfully displayed the results, but now I am wondering if there is a way to prevent them from resetting every time the function is used. Any advice on persisting the results?