How to roll multiple dice using a for loop? - javascript

The following code rolls 5 dice at once but with 5 different variables. I'm trying to use a for-loop to achieve this instead. Is this logical or do I need 5 different variables for every dice?
function dieroll() {
var roll= "&#x268" + Math.floor(Math.random() * 6) + ";";
var roll2= "&#x268" + Math.floor(Math.random() * 6) + ";";
var roll3= "&#x268" + Math.floor(Math.random() * 6) + ";";
var roll4= "&#x268" + Math.floor(Math.random() * 6) + ";";
var roll5= "&#x268" + Math.floor(Math.random() * 6) + ";";
var roll6= "&#x268" + Math.floor(Math.random() * 6) + ";";
return roll + roll2 + roll3 + roll4 + roll5;
}

Another approach could be:
function dieroll() {
var result = [];
for (var i = 0; i < 5; i++){
result.push("&#x268" + Math.floor(Math.random() * 6) + ";");
}
return result;
};
With this definition, a call to dieroll() would look like:
dieroll()
["⚁", "⚂", "⚂", "⚂", "⚂"]

Related

Chrome console prints out function source code instead of doing something

I'm trying to make a simple blackjack game on Javascript. I really don't understand why the function does not work properly?
var OurHand = 0;
var TheirHand = 0;
function dealCards() {
OurHand += Math.floor(Math.random() * 10) + 1
OurHand += Math.floor(Math.random() * 10) + 1
TheirHand += Math.floor(Math.random() * 10) + 1
TheirHand += Math.floor(Math.random() * 10) + 1
}
You will have to execute your code using functionName() with parenthesis. Here is your example working & writing "done" in the console as an result.
var OurHand = 0;
var TheirHand = 0;
function dealCards() {
OurHand += Math.floor(Math.random() * 10) + 1
OurHand += Math.floor(Math.random() * 10) + 1
TheirHand += Math.floor(Math.random() * 10) + 1
TheirHand += Math.floor(Math.random() * 10) + 1
console.log('Done dealing cards.')
}
dealCards() // this will execute your code of the dealCards function
console.log(OurHand)
console.log(TheirHand)

Save the input of loop without creating 3 different variables

for (var i = 0; i < 3; i++) {
var rgb = Math.floor(Math.random() * 255 + 1);
var randomRGB = ("rgb"+"("+rgb+","+rgb+","+rgb+")");
console.log (randomRGB);
}
I am getting this as input :
rgb(165,165,165)
rgb(195,195,195)
rgb(231,231,231)
what i would like to get is this instead :
rgb(165, 195, 231)
What am i doing wrong?
You can do this using an array:
for (var i = 0; i < 3; i++) {
var rgb = [];
for (var i = 0; i < 3; i++){
rgb.push(Math.floor(Math.random() * 255 + 1));
}
var randomRGB = ("rgb"+"("+ rgb.join(",") +")");
console.log (randomRGB);
}
This way you're technically using one variable (an array of integer values) to set the RGB values, it's running a for loop to create the rgb array (or this can be done on initialization without using a for loop, but I feel this looks neater). This also means the variable is being re-initialized each time it runs the outer loop so you'll end up with different RGB's for the 3 times the outer loop is run.
Try this:
var r = Math.floor(Math.random() * 255 + 1);
var g = Math.floor(Math.random() * 255 + 1);
var b = Math.floor(Math.random() * 255 + 1);
var randomRGB = "rgb(" + r + "," + g + "," + b + ")";
console.log (randomRGB);
Or if you do want to avoid creating variable:
var randomRGB = "rgb(" + Math.floor(Math.random() * 255 + 1) + "," + Math.floor(Math.random() * 255 + 1) + "," + Math.floor(Math.random() * 255 + 1) + ")";
var color = [];
for (var i = 0; i < 3; i++) {
var rand = Math.floor(Math.random() * 255 + 1);
color.push(rand);
}
var randomRGB = ("rgb"+"("+ color.join(",") +")");
console.log (randomRGB);
var r = Math.floor(Math.random() * 255 + 1);
var g = Math.floor(Math.random() * 255 + 1);
var b = Math.floor(Math.random() * 255 + 1);
var randomRGB = "rgb(" + r + "," + g + "," + b + ")";
console.log (randomRGB);
You need three variables if you want to store three values.
You can do it without a looping statement,
var getRgb = () => Math.floor(Math.random() * 255 + 1);
var randomRGB = ("rgb"+"("+ getRgb() +","+ getRgb() + ","+ getRgb() +")");
console.log (randomRGB);
If you want to do it by iteration then do like,
var getRgb = () => Math.floor(Math.random() * 255 + 1);
var randomRGB = "rgb(" + (["","",""].map(getRgb) + ")"
console.log (randomRGB);

How do I call a function inside a if...else statement?

Is it possible to call a function inside an if else in a function. I want to make a function, who use if else to call 1 function in each.
Live demo
The first js code to call the other functions:
function randomClick(number){
var gamerand = Math.floor(Math.random() * (3 - 1 + 1)) + 1;
if (gamerand == 1){
loseClick();
}else{
winClick();
};
Lose function:
function loseClick(number){
var rand = Math.floor(Math.random() * (150 - 75 + 75)) + 1;
var rprand = Math.floor(Math.random() * (5 - 1 + 1)) + 1;
var xprand = Math.floor(Math.random() * (200 - 100 + 100)) + 1;
xp = parseInt(xp) + xprand;
cookies = parseInt(cookies) + rand;
rp = parseInt(rp) + rprand;
losses = parseInt(losses) + 1;
}
Win function:
function winClick(number){
var rand = Math.floor(Math.random() * (200 - 100 + 100)) + 1;
var rprand = Math.floor(Math.random() * (20 - 1 + 1)) + 1;
var xprand = Math.floor(Math.random() * (300 - 150 + 150)) + 1;
xp = parseInt(xp) + xprand;
cookies = parseInt(cookies) + rand;
rp = parseInt(rp) + rprand;
wins = parseInt(wins) + 1;
}
Thanks in advance.
You have a missing } for your function randomClick
function randomClick(number){
var gamerand = Math.floor(Math.random() * (3 - 1 + 1)) + 1;
if (gamerand == 1){
loseClick();
}else{
winClick();
}
}//This was missing
You missed the } of else inside randomClick().
You can use ternary operator as follow:
function randomClick(number) {
var gamerand = Math.floor(Math.random() * (3 - 1 + 1)) + 1;
gamerand == 1 ? loseClick() : winClick();
}
Demo: http://jsfiddle.net/tusharj/omo9yv9q/5/
You have a missing }. It should work without problems with this fix.
function randomClick(number){
var gamerand = Math.floor(Math.random() * (3 - 1 + 1)) + 1;
if (gamerand == 1){
loseClick();
}else{
winClick();
// missing one bracket here
};

Dice roll in javascript

function rolldice() {
var x = Math.floor(Math.random() * ((6 - 1) + 1) + 1);
var y = Math.floor(Math.random() * ((6 - 1) + 1) + 1);
var dicetotal = x + y;
var double = 0;
$('.dice1').attr('id', "dice" + x);
$('.dice2').attr('id', "dice" + y);
if (x == y) { //<----checking if there is a double
var double = double++; //<---increment double count
//Now reroll the dice, but if you hit 3 doubles in a row, you get message go to jail.
}
};
I want to know if I am going to need some loop...Please help me. This is part of a monopoly game. What do i have to add in the code, to make it loop if there is a double.
You only need to make an recursive call:
var dbl = 0;
function rolldice() {
var x = Math.floor(Math.random() * ((6 - 1) + 1) + 1);
var y = Math.floor(Math.random() * ((6 - 1) + 1) + 1);
var dicetotal = x + y;
$('.dice1').attr('id', "dice" + x);
$('.dice2').attr('id', "dice" + y);
if (x == y) { //<----checking if there is a double
dbl++; //<---increment double count
if(dbl%3==0) $('.out').attr('id', "jail");
//Now reroll the dice, but if you hit 3 doubles in a row, you get message go to jail.
rolldice();
}
};
I think you need to create something like this:
var double = 0;
function rolldice(){
var x = Math.floor(Math.random() * ((6-1)+1) + 1);
var y = Math.floor(Math.random() * ((6-1)+1) + 1);
var dicetotal = x + y;
$('.dice1').attr('id', "dice" + x);
$('.dice2').attr('id', "dice" +y);
if(x==y) {
if (double < 3) {
double++; // increase dobule
rolldice(); // Call rolldice again...
} else {
// Here there is 3 in a row....
}
}
}
This has some complications. When there is a change of player, you need to reset the value of your variable for checking double rolls.
Do the following:
var dblRolls;
function userChange(){//call this on change of user
dblRolls=0;
rollDice();
}
function rolldice() {
var x = Math.floor(Math.random() * ((6 - 1) + 1) + 1);
var y = Math.floor(Math.random() * ((6 - 1) + 1) + 1);
var dicetotal = x + y;
var double = 0;
$('.dice1').attr('id', "dice" + x);
$('.dice2').attr('id', "dice" + y);
if (x == y) { //<----checking if there is a double
dblRoll++; //<---increment double count
if(dblRoll==3)
//jail
else
rollDice();
}
};
Don't use a loop.
Instead add the doubles counter as a parameter for the rolldice() function and call the function from within itself:
function rolldice(doubleCount) {
var x = Math.floor(Math.random() * ((6 - 1) + 1) + 1);
var y = Math.floor(Math.random() * ((6 - 1) + 1) + 1);
var dicetotal = x + y;
$('.dice1').attr('id', "dice" + x);
$('.dice2').attr('id', "dice" + y);
if (x == y) { //<----checking if there is a double
doubleCount++;
if (doubleCount == 3)
{
//go to jail
}
else
{
rolldice(doubleCount);
}
}
};
The initial call for a player's first roll would look like rolldice(0);
Ok, besides this is more than two hours old and has already 4 answers, I want to add my 2 cents.
You state you want to make a Monopoly game. After most, if not all, dice rolls the player has to make decisions. That means after each roll you wait for user input (e.g., some button presses).
All other answers postet suggest to use recursive calls in some way. Instead I suggest to store the number of doubles alongside with the current player in some global variable. You do not use a loop, but instead something like:
var doubleCount = 0;
function rolldice() {
var x = Math.floor(Math.random() * ((6 - 1) + 1) + 1);
var y = Math.floor(Math.random() * ((6 - 1) + 1) + 1);
var dicetotal = x + y;
$('.dice1').attr('id', "dice" + x);
$('.dice2').attr('id', "dice" + y);
if (x == y) { //<----checking if there is a double
doubleCount++; //<---increment double count
if (doubleCount > 2) {
// Got to Jail
}
}
// Proceed as usual and come back to this, when the user presses the "Roll" Button again
};
This script works:
function rollDice(){
var dice1 = document.getElementById("dice1");
var dice2 = document.getElementById("dice2");
var status = document.getElementById("status");
var d1 = Math.floor(Math.random() * 6) + 1;
var d2 = Math.floor(Math.random() * 6) + 1;
var diceTotal = d1 + d2;
dice1.innerHTML = d1;
dice2.innerHTML = d2;
status.innerHTML = "You rolled "+diceTotal+".";
if(d1 == d2){
status.innerHTML += "<br />DOUBLES! You get a free turn!!";
}
}
This is one possible solution.
function rolldice(dbl=0){
var x = Math.floor(Math.random()*((6-1)+1) + 1);
var y = Math.floor(Math.random()*((6-1)+1) + 1);
if(x===y){
if(dbl!==3){
dbl++;
rolldice(dbl);
}else{
//goto jail
}
}else{
//no double
dbl=0;
}
}
or
function rolldice(dbl=0){
var x = Math.floor(Math.random()*((6-1)+1) + 1);
var y = Math.floor(Math.random()*((6-1)+1) + 1);
if(x===y&&dbl!==3)
dbl++;
rolldice(dbl);
}else if(x===y&&dbl===3){
//goto jail
}else{
//no double
dbl=0;
}
}

Triple conditioned do while loop

I'm trying to assign three random numbers to three variables (random1, random2, random3), and then assign these random variables to three elements. But I don't want any of them to be equal to the variable Sum which is the addition of two numeric innerHTML values.
So I have done that using do...while loop, but unfortunately the do...while loop doesn't work as expected .
Here is my code :
setTimeout(function () {
z.innerHTML = Math.floor((Math.random() * 3) + 1);
setTimeout(function applySUM() {
var Sum = parseInt(document.getElementById('fir').innerHTML) +
parseInt(document.getElementById('sec').innerHTML);
ch1.innerHTML = Sum;
}, 500);
do {
var random1 = Math.floor((Math.random() * 3) + 1);
var random2 = Math.floor(Math.random() * (6 - 4 + 1)) + 4;
var random3 = Math.floor(Math.random() * (10 - 7 + 1)) + 7;
} while (random1 == Sum || random2 == Sum || random3 == Sum);
setTimeout(function func() {
ch2.innerHTML = random1;
}, 1000);
setTimeout(function func() {
ch3.innerHTML = random2;
}, 1500);
setTimeout(function func() {
ch4.innerHTML = random3;
}, 2000);
}, 2000);
Looking at the code above, it seems to be impossible for the ch2.innerHTML, ch3.innerHTML and ch4.innerHTML to be equal to Sum, but when I test it the reality says something else. Why is this?
First thing, as many people mentioned, the sum variable is local to ApplySum so the rest of your code is referencing a global Sum variable instead (and it is "undefined" by default)
Another problem is that right now your do-while loop runs immediately, without waiting the 500 ms timeout and before Sum is assigned to a value. You can fix this by putting your code inside the settimeout callbacks:
z.innerHTML = Math.floor((Math.random() * 3) + 1);
setTimeout(function applySUM() {
var Sum = parseInt(document.getElementById('fir').innerHTML) +
parseInt(document.getElementById('sec').innerHTML);
ch1.innerHTML = Sum;
do {
var random1 = Math.floor((Math.random() * 3) + 1);
var random2 = Math.floor(Math.random() * (6 - 4 + 1)) + 4;
var random3 = Math.floor(Math.random() * (10 - 7 + 1)) + 7;
} while (random1 == Sum || random2 == Sum || random3 == Sum);
setTimeout(function func() {
ch2.innerHTML = random1;
}, 500);
setTimeout(function func() {
ch3.innerHTML = random2;
}, 1000);
setTimeout(function func() {
ch4.innerHTML = random3;
}, 1500);
}, 500);
(I also decreased 500ms from the other settimeouts to compensate for them being moved inside the first timeout)
Another tiny change you could consider is doing a separate loop for each variable instead of a single one for all of them.
var random1, random2, random3;
do { random1 = Math.floor((Math.random() * 3) + 1); } while (random1 == Sum);
do { random2 = Math.floor(Math.random() * (6 - 4 + 1)) + 4; } while (random2 == Sum);
do { random3 = Math.floor(Math.random() * (10 - 7 + 1)) + 7; } while (random3 == Sum);
The comments about scope seem like they're on the right track. Here's the relevant part of your code:
setTimeout(function applySUM() {
var Sum = parseInt(document.getElementById('fir').innerHTML) +
parseInt(document.getElementById('sec').innerHTML);
ch1.innerHTML = Sum;
}, 500);
// Outside of your applySum function, Sum has no meaning
do {
var random1 = Math.floor((Math.random() * 3) + 1);
var random2 = Math.floor(Math.random() * (6 - 4 + 1)) + 4;
var random3 = Math.floor(Math.random() * (10 - 7 + 1)) + 7;
} while (random1 == Sum || random2 == Sum || random3 == Sum);
// Outside of your loop body, random1, random2, and random3 have no meaning
// undefined == undefined => true
Perhaps if you changed it to this:
var Sum = 0;
setTimeout(function applySUM() {
Sum = parseInt(document.getElementById('fir').innerHTML) +
parseInt(document.getElementById('sec').innerHTML);
ch1.innerHTML = Sum;
}, 500);
var random1 = random2 = random3 = undefined;
do {
random1 = Math.floor((Math.random() * 3) + 1);
random2 = Math.floor(Math.random() * (6 - 4 + 1)) + 4;
random3 = Math.floor(Math.random() * (10 - 7 + 1)) + 7;
} while (random1 == Sum || random2 == Sum || random3 == Sum);
Then your variables might have scope in the appropriate spots. Just a hunch, there might be something else wrong with this.

Categories

Resources