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

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

Related

Unlimited 6 sided dice roller

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>

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);

JS receiving NaN when trying to add number to a variable

I am trying to code a roll dice game, but I constantly get a NaN number in my console.
var dice, score;
function rollDice() {
dice = Math.floor((Math.random() * 6) + 1);
dice !== 1 ? score += dice : score = 0;
return score;
}
var hey = rollDice();
console.log(hey);
You need to assign a default value to the score variable, like score = 0, because now it's undefined. Example: JSFiddle
Your variable score is never initialized to a value, so when performing this operation:
score += dice
It is really performing:
undefined += 3
And undefined + a number is always NaN.
Try initializing score to 0:
var dice = 0;
var score = 0;
var dice = 0;
var score = 0;
function rollDice() {
dice = Math.floor((Math.random() * 6) + 1);
dice !== 1 ? score += dice : score = 0;
return score;
}
var hey = rollDice();
console.log(hey);
Your terniary is what's causing the NaN. Try this.
score = dice !== 1 ? (dice + 1) : 0;
Example: https://repl.it/NKul/1
EDIT
Fixed true condition for terniary.

Checking for two consecutive values match of a variable's value in JavaScript

I built a function called roll() which handles a roll of a dice. I'm trying to read the value of the roll and check if the roll hit 6 twice in a row so that I can interrupt the player's turn and turn it to the next player.
I can read the dice value alright, I'm having trouble trying to figure out how to check for a 6 twice in a row.
This is my function:
roll = function(){
if (gamePlaying){
// 1. Get a random number
//var dice = Math.floor(Math.random() * 6) + 1; //1 to 6 randomly
var dice = 6;
//2. Display the result
var diceDOM = document.querySelector('.dice');
diceDOM.style.display = 'block';
diceDOM.src = 'images/' + 'dice-' + dice + '.png';
//3. Update the roundScore IF the rolled number is not 1
// for type coersion, we need to use !== and not !=
if(dice !== 1) {
//add score
roundScore += dice; // same as roundScore = roundScore + dice
//it outputs to a div of ID = #myId
document.querySelector('#current-' + activePlayer).textContent = roundScore;
} else {
alert('Next Player')
nextPlayer();
}
// Is this right?
for(var i = 1; i >= 2; i++){
if (dice == 6){
console.log('sixes');
}
}
}
}
Being triggered by a button like this:
document.querySelector('.btn-roll').addEventListener('click', function(){
roll();
});
I loaded the game to this CODEPEN
P.S. I put a dice = 6; under the random function so you don't have to play the game until you get two sixes. Just uncomment it and comment out the dice = math function and you'll get nothing but sixes.
I also put a "Is this right?" comment on top of a for loop. What I mean by that is, " is this the right approach?" Should I keep experimenting with a loop or am I way off already?
And by the way, if 2 sixes do come up, the entire score is deleted which is being passed to the score[] But I can do that... I think lol
Many thanks.
You can try something like this, where you make roll() a self invoking function. That way you can store how many times they have rolled a six.
roll = (function(){
var count = 0;
var lastRoll = 0;
return function() {
if (gamePlaying){
// 1. Get a random number
var dice = Math.floor(Math.random() * 6) + 1; //1 to 6 randomly
var thisRoll = dice;
if(dice === 6) {
lastRoll = 6;
count += 1;
} else {
lastRoll = 0;
count = 0;
}
if(thisRoll === 6 && lastRoll === 6 && count === 2) {
alert('You rolled a six twice!');
lastRoll = 0;
count = 0;
// do your stuff for 2 sixes in a row here!
return;
}
//2. Display the result
var diceDOM = document.querySelector('.dice');
diceDOM.style.display = 'block';
diceDOM.src = 'http://sitedev.online/repo/' + 'dice-' + dice + '.png';
//3. Update the roundScore IF the rolled number is not 1
// for type coersion, we need to use !== and not !=
if(dice !== 1) {
//add score
roundScore += dice; // same as roundScore = roundScore + dice
//it outputs to a div of ID = #myId
document.querySelector('#current-' + activePlayer).textContent = roundScore;
console.log(dice);
} else {
alert('Next Player')
nextPlayer();
}
}
}
})();
Just for the heck of it, you don't need any global or outside vars to do this. The trick is, remember that functions are objects. You can read and write properties to them; you can even entirely change a function from within the function (which is the trick to an old JS singleton pattern).
Here's an example. If you say feed it "true", it will update the "last" reference values and return two random dice rolls. If you feed it "false", it will NOT update the previous reference values until you pass in true again (but it still returns a fresh roll). That way, you can keep rolling, hold the initial value, and compare it to a new second value all you want.
<html>
<head>
</head>
<body>
<script>
var rollfunc = function ( updateLast ) {
var d1 = Math.floor((Math.random() * 6) + 1);
var d2 = Math.floor((Math.random() * 6) + 1);
if ( updateLast ) {
rollfunc.d1 = d1;
rollfunc.d2 = d2;
}
return {
dice1 : d1,
dice2 : d2,
bothsixes : ( ( d1 + d2 === 6 ) && ( rollfunc.d1 + rollfunc.d2 === 6 ) )
};
}
var result = rollfunc ( true );
// If you pass in true then d1, d2, and rollfunc.d1, rollfunc.d2 will always be the same
console.log ( "Reference updated: ", result, "d1 = " + rollfunc.d1, ", d2 = " + rollfunc.d2 );
var result = rollfunc ( false );
// If you pass in false, the reference won't change, but the new roll will, you can compare the two
console.log ( "Reference left alone: ", result, "d1 = " + rollfunc.d1, ", d2 = " + rollfunc.d2 );
</script>
</body>
</html>
I get this might be overly academic, but it's useful to know JS can do this.
A little late to this game. But I'm new to JavaScript, and currently on a similar project from udemy.com.
Here's a solution I found that apparently works. I verified it on your CodePen, too.
document.querySelector('.btn-roll').addEventListener('click', function() {
if (gamePlaying) {
// 1. Get a random number
dice = Math.floor(Math.random() * 6) + 1; //1 to 6 randomly
thisRoll = dice;
if (dice === 6) {
lastRoll = 6;
count += 1;
} else {
lastRoll = 0;
count = 0;
}
if (thisRoll === 6 && lastRoll === 6 && count === 2) {
alert('You rolled a six twice!');
lastRoll = 0;
count = 0;
nextPlayer();
// do your stuff for 2 sixes in a row here!
return;
}
//2. Display result
var diceDOM = document.querySelector('.dice');
diceDOM.style.display = 'block';
diceDOM.src = 'http://sitedev.online/repo/' + 'dice-' + dice + '.png';
//3. Update round score if the rollled number was not a 1
if (dice !== 1) {
//Add score
roundScore += dice;
//roundScore = roundScore + dice
document.querySelector('#current-' + activePlayer).textContent = roundScore;
} else {
nextPlayer();
}
}
});
Working on the same problem. Found another solution on udemy. Hope it helps...
var lastRoll;
document.querySelector('.btn-roll').addEventListener('click', function() {
// Generating a random variable
var dice = Math.floor(Math.random() * 6) + 1;
// Check for two consecutive 6's'
if ( dice === 6 && lastDice === 6) {
//If consecutive 6's code goes here
}
lastRoll = dice;
});

JavaScript setTimeout not working with prompt box

Here is my code:
var t = setTimeout("increment();", 1000 * 3);
var st;
function increment() {
st = 1;
}
for (i = 0; i < 10; i++) {
cnt = i;
var no1 = Math.floor(Math.random() * 101);
var no2 = Math.floor(Math.random() * 101);
if ((i % 4) == 0) {
crct_ans[i] = no1 + no2;
quest[i] = no1 + " + " + no2;
}
else if ((i % 4) == 1) {
crct_ans[i] = no1 - no2;
quest[i] = no1 + " - " + no2;
}
else if ((i % 4) == 2) {
crct_ans[i] = no1 * no2;
quest[i] = no1 + " x " + no2;
}
else if ((i % 4) == 3) {
crct_ans[i] = no1 / no2;
quest[i] = no1 + " / " + no2;
}
ans[i] = prompt(quest[i], "");
if (st == 1) break;
}​
I want to stop the for loop if 3 seconds pass. But this is not working. For loop runs after the 3 seconds also. How can I do this?
Remove () and quotes like this:
var t = setTimeout(increment, 3000);
Removing () disables running of that function straright away/immediately whereas setTimeout expects callabck.
Removing quotes makes sure that eval isn't used behind the scenes.
BTW, it is good practice to declare all variables with single var keyword like this:
var t = setTimeout(increment, 3000), st;
If it suits your requirements, you can simply check how much time pass.
Example:
var start = new Date();
for(i = 0; i < 10; i++){
var end = new Date();
var elapsed = end.getTime() - start.getTime();
if (elapsed >= 3000)
break;
}​
Try formatting like so:
var t = setTimeout(function(){increment();}, 3000);

Categories

Resources