Unlimited 6 sided dice roller - javascript

Need help with a JavaScript assignment from School but don't know how I should do it and was hoping for some tips?
We're supposed to create a 6 sided dice roller program and the user will have the option to choose between how many dices should be rolled, min 1 and max 5 dices.
The sum of the amount of dices used should always be displayed on the page. But if a number 6 is thrown, then this should make the program disregard it to the sum and instead throw two new dices, there should be an error message displaying this when it happens.
When all the dices are thrown the total sum of all the dices should be displayed and how many times you threw the dices.
I've managed to create this so far but I'm not sure how I should do regarding the number 6 or even if I'm on the right path here?
JS
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";
}
};
EDIT
I updated it to this now
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 och two new dices were thrown");
document.getElementById("msg").innerHTML = "You got a 6 och 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 managed to display the results, but wondering now if there is a way display the results without them getting reset every time you use the function?

Replace loop for by loop while:
let diceThrows = 6;
let sum = 0;
while(diceThrows > 0) {
var diceRoll = Math.floor(Math.random() * 6) + 1;
if(diceRoll == 6) {
diceThrows += 2;
} else {
sum += diceRoll;
}
container.innerHTML += '<div class="dice">' + diceRoll + '</div>';
diceThrows -= 1;
}

You can do something like this:
function rollDice() {
var numDice = Number(document.getElementById("diceNum").value);
if (isNaN(numDice) || numDice < 1 || numDice > 5) {
window.alert('Input not valid');
return
}
var container = document.getElementById("dieContainer");
container.innerHTML = "";
var total = 0
for (var i = 0; i < numDice; i++) {
var diceRoll = Math.floor(Math.random() * 6) + 1;
container.innerHTML += '<div class="dice">' + diceRoll + '</div>';
if(diceRoll === 6) {
//Increase the maximum by 1 (because ignore 6: -1; add two: +2)
numDice++
//Decrease the current by 1 (to ignore the 6)
i--
continue
}
total += diceRoll
};
document.getElementById("diceTotal").innerText = total
document.getElementById("diceCount").innerText = numDice
}
<input type="number" id="diceNum">
<button onclick="rollDice()" >Roll Dice</button><br>
Total (without 6s): <span id="diceTotal" ></span><br>
Count of rolls (without 6s): <span id="diceCount" ></span><br>
<div id="dieContainer" ></div>

Related

While loop multiple statements in js. "The Dice Game"

I have to create a dice roller game, if it lands on 2,3,6,12 the game is supposed to stop and tell me which of the numbers the sum of both my dices landed on and how many "rolls" or tries it took me to get there. I haven't been able to figure out why my program isn't working, if I erase the conditions in the while loop and leave only one for example: while(dice != 2); the program will run but it would obviously only match if it lands on 2. Please help me!
function play() {
var dice = -1;
var rolls = 1;
var numb1 = 2;
var numb2 = 3;
var numb3 = 6;
var numb4 = 12;
while (dice != numb1 || dice != numb2 || dice != numb3 || dice != numb4) {
dice = Math.floor(Math.random() * 11) + 2;
rolls++;
}
document.getElementById('results').innerHTML = 'Your dice landed on: ' + dice;
document.getElementById('rolls').innerHTML = 'Rolls: ' + rolls;
}
Change your || to && in your while
function play() {
var dice = -1;
var rolls = 1;
var numb1 = 2;
var numb2 = 3;
var numb3 = 6;
var numb4 = 12;
while (dice != numb1 && dice != numb2 && dice != numb3 && dice != numb4) {
dice = Math.floor(Math.random() * 11) + 2;
rolls++;
}
document.getElementById('results').innerHTML = 'Your dice landed on: ' + dice;
document.getElementById('rolls').innerHTML = 'Rolls: ' + rolls;
}
play()
<div id="results"></div>
<div id="rolls"></div>
you can improve the while condition by using includes
function play() {
var dice = -1;
var rolls = 1;
var numb1 = 2;
var numb2 = 3;
var numb3 = 6;
var numb4 = 12;
while (![numb1, numb2, numb3, numb4].includes(dice)) {
dice = Math.floor(Math.random() * 11) + 2;
rolls++;
}
document.getElementById('results').innerHTML = 'Your dice landed on: ' + dice;
document.getElementById('rolls').innerHTML = 'Rolls: ' + rolls;
}
play()
<div id="results"></div>
<div id="rolls"></div>
Your code doesn't work, because dice would need to be each of these numbers at the same time to work, which is impossible.
Try doing this:
while (![2, 3, 6, 12].includes(dice)) {
Also, your random function can't get 1, maybe try:
Math.floor(Math.random() * 12) + 1

How to find the average in javascript?

So I'm fairly new to JavaScript but I cannot seem to find the average in my code. I want to understand why my average is not working. Any help you guys?
function getEvenOdd() {
var oddSum = 0;
var evenSum = 0;
var num = 0;
var evenAvg = 0;
var oddAvg = 0;
while (true) {
num = parseInt(prompt("Enter a number(-1 to exit)"));
if (num == -1) {
break;
}
if (num % 2 == 0) {
evenSum += num;
} else {
oddSum += num;
}
evenAvg = evenSum / num;
oddAvg = oddSum / num;
}
alert("Sum of all even numbers is: " + evenSum);
alert("Sum of all odd numbers is: " + oddSum);
alert("Average of all even numbers is : " + evenAvg);
alert("Average of all odd numbers is: " + oddAvg);
}
On your code, to calculate the oddAvg and evenAvg, you have divided evenSum and oddSum by num variable (which is input from prompt).
And as you know, average = total sum / total count, so it's not right to divide the sum by the input number variable.
Instead of that, you need to calculate the count of odd and even numbers and divide the even and odd sum by the even and odd number counts as follows.
function getEvenOdd() {
var oddSum = 0;
var evenSum = 0;
var num = 0;
var evenAvg = 0;
var oddAvg = 0;
var evenCount = 0;
var oddCount = 0;
while (true) {
num = parseInt(prompt("Enter a number(-1 to exit)"));
if (num == -1) {
break;
}
if (num % 2 == 0) {
evenSum += num;
evenCount ++;
} else {
oddSum += num;
oddCount ++;
}
}
evenAvg = evenSum / evenCount;
oddAvg = oddSum / oddCount;
alert("Sum of all even numbers is: " + evenSum);
alert("Sum of all odd numbers is: " + oddSum);
alert("Average of all even numbers is : " + evenAvg);
alert("Average of all odd numbers is: " + oddAvg);
}
getEvenOdd();
These operations are dividing the evenSum or oddSum by the last input num.
evenAvg = evenSum / num;
oddAvg = oddSum / num;
You should divide the sum by the number of even or odd inputs.
Instead of evenSum / num use evenSum/Count of Numbers entered.
How about this solution? It is aiming to store odd and even numbers into oddList and evenList.
function getEvenOdd() {
var evenAvg = 0;
var oddAvg = 0;
var oddList = [];
var evenList = [];
var num = 0;
while (true) {
num = parseInt(prompt("Enter a number(-1 to exit)"));
if (num == -1) {
break;
}
if (num % 2 == 0) {
evenList.push(parseInt(num));
} else {
oddList.push(parseInt(num));
}
evenAvg = evenList.reduce((p, c) => p + c, 0) / evenList.length;
oddAvg = oddList.reduce((p, c) => p + c, 0) / oddList.length;
}
alert("Sum of all even numbers is: " + evenList.length);
alert("Sum of all odd numbers is: " + oddList.length);
alert("Average of all even numbers is : " + evenAvg);
alert("Average of all odd numbers is: " + oddAvg);
}
getEvenOdd();

Counting occurrences of integer from random outcome

I'm fairly new to coding and have this practice that I can't figure out the last part of it.
I'm rolling three dice and supposed to count how many combined value of sevens I get at 1000th roll.
Do I have to create an array? the hint given to me was to create a counter variable. But I can't find any solution. I know it must be something simple. I need your guidance!
var getRandomInt = function(x) {
var result = 0;
result = Math.floor((Math.random() * x) + 1);
return result;
};
//variables I need
var diceOne = 0;
var diceTwo = 0;
var diceThree = 0;
var diceSum = 0;
var roll = 0;
var average = 0;
for (var i = 1; i <= 1000; i++) {
//Simulate a Dice Roll
diceOne = getRandomInt(6);
diceTwo = getRandomInt(6);
diceThree = getRandomInt(6);
roll = roll + 1;
diceSum = diceOne + diceTwo + diceThree;
average += diceSum / 1000;
console.log("Roll #" + roll);
console.log("Value of Dice 1 is " + diceOne);
console.log("Value of Dice 2 is " + diceTwo);
console.log("Value of Dice 3 is " + diceThree);
console.log("The Sum of the Dice is " + diceSum);
// Announce average and count of 7s
if (i == 1000) {
console.log("The Average is " + average);
}
}
If you need to count the times the 3 dice add up to 7, you can create a variable to keep track of this.
Inside your loop, you increase this by one everytime diceSum is 7.
var getRandomInt = function(x) {
var result = 0;
result = Math.floor((Math.random() * x) + 1);
return result;
};
//variables I need
var diceOne = 0;
var diceTwo = 0;
var diceThree = 0;
var diceSum = 0;
var roll = 0;
var average = 0;
var sevenCount = 0;
for (var i = 1; i <= 1000; i++) {
//Simulate a Dice Roll
diceOne = getRandomInt(6);
diceTwo = getRandomInt(6);
diceThree = getRandomInt(6);
roll = roll + 1;
diceSum = diceOne + diceTwo + diceThree;
average += diceSum / 1000;
console.log("Roll #" + roll);
console.log("The Sum of the Dice is " + diceSum);
if(diceSum === 7){
sevenCount = sevenCount + 1;
}
// Announce average and count of 7s
if (i == 1000) {
console.log("The Average is " + average);
console.log("The seven count is " + sevenCount);
}
}
They're teaching you something that's actually really good to know.
You don't have to remember all values in order to calculate the average or number of 7s. You only have to count how many 7s you've seen and keep another variables that's the sum of all the values you've seen.
Edit: if you want to count the number of 7s you've seen, you need to create a variable, say count_7s and every time you see a 7, you increment count_7s = count_7s + 1.
You need no roll count, because you loop the same amount, and you need a counter for sevens. An you could take a variable for sum and calculate later the average. This is better in terms of numerical precision.
At the end show the result of average and count of sevens.
var getRandomInt = function(x) {
return Math.floor((Math.random() * x) + 1);
},
sum = 0,
average = 0,
sevens = 0;
for (var i = 1; i <= 1000; i++) {
let diceSum = getRandomInt(6) + getRandomInt(6) + getRandomInt(6);
sevens += diceSum === 7;
sum += diceSum;
}
average = sum / 1000;
console.log("The Average is " + average);
console.log("The Count of Sevens " + sevens);

Adding a line break after every 12 numbers inside a for loop in Javascript

My current code is:
for (count = 1; count <= 100; count = count + 1) {
text = "<br>" + " " + count;
document.getElementById("id").innerHTML += text;
}
When displaying it I need to add a line break after every 12 numbers in a line.
for (count = 1; count <= 100; count = count + 1) {
text = "<br>" + " " + count;
if (count % 12 === 0) {
document.getElementById("id").innerHTML += text;
}
}
You could take the reminder operator % and check if the result is zero.
Some annotations:
declare all variables,
collect all text,
assign to element at the end.
var text = "";
for (let count = 1; count <= 100; count++) {
text += count + ' ';
if (count % 12 === 0) {
text += "<br>";
}
}
document.getElementById("demo5").innerHTML += text;
<div id="demo5"></div>
You can help yourself with the % (remainder) operator. If number % 12 === 0 is because that number is a multiple of 12. You can use this to your advantage like so
var text = "";
for (let count = 1; count <= 100; count++) {
text += count + ' ';
if (count % 12 === 0) {
text += "<br>";
}
}
document.getElementById("answer").innerHTML += text;
<div id="answer"></div>
Another way could be to explicitly count how many items you're currently having and reset that count whenever it reaches 12:
var text = "";
var n = 0;
for (let count = 1; count <= 100; count++) {
text += count + ' ';
n++;
if (n === 12) {
n = 0;
text += "<br>";
}
}
document.getElementById("answer").innerHTML += text;
<div id="answer"></div>
Do the following
for (count = 1; count <= 100; count = count + 1) {
text += count+ " ";
if(count%12 == 0){
text = text + "</br>";
}
document.getElementById("id").innerHTML = text;
}

JavaScript- get sum of values inside a for loop

I'm trying to sum all the variables,
as many times as they appear in the loop,
that is- for example if hitpoints appears
3 times(as in my code) sum -12 + -12 + -12;
And then at the end I need a final result - a
sum of all of the variable values as many
times as they appear.
function calculate(number) {
var hitpoints = -12;
var points1 = 1;
var points3 = 5;
var points5 = 10;
var pointsx = 15;
for (var i =1; i <= number; i++) {
if ( i%10 ===0) {
console.log( i + "-" + hitpoints);
} else if ((i % 3 === 0) && (i% 5 ===0)) {
console.log( i + "-" + pointsx);
} else if (i %3 ===0) {
console.log ( i + "-" + points3);
} else if (i%5 ===0) {
console.log( i + "-" + points5);
} else {
console.log( i + "-" + points1);
}
}
}
calculate(30);
I assume you want the sum of the points.
Declare a variable sum and keep incrementing
function calculate(number) {
var hitpoints = -12;
var points1 = 1;
var points3 = 5;
var points5 = 10;
var pointsx = 15;
var sum=0;
for (var i =1; i <= number; i++) {
if ( i%10 ===0) {
sum += hitpoints;
} else if ((i % 3 === 0) && (i% 5 ===0)) {
sum += pointsx;
} else if (i %3 ===0) {
sum += points3;
} else if(i%5 ===0) {
sum += points5;
} else {
sum += points1;
}
}
console.log(sum)
}
calculate(30);

Categories

Resources