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.
Related
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)
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
};
I have some problems with JavaScript.
So far, I have this code:
<!DOCTYPE html>
<html>
<body>
<p>This program generates random numbers from 100 to 999.</p>
<button onclick="maingen()">Start</button> <-- Here's the FUNCTION OF FUNCTIONS..It should generate 3 digits, but only generates 1 :(
<p id="numbers"></p>
<script>
function generate1() {
var a = Math.floor((Math.random() * 9) + 1);
document.getElementById("numbers").innerHTML = a; <--generating the first digit (from 1 to 9)
}
function generate2() {
var b = Math.floor((Math.random() * 9) + 0);
document.getElementById("numbers").innerHTML = b; <--generating the second digit (from 0 to 9)
}
function generate3() {
var c = Math.floor((Math.random() * 9) + 0);
document.getElementById("numbers").innerHTML = c; <--generating the third digit (from 0 to 9)
}
function maingen(){
generate1();
generate2();
generate3();
}
</script>
</body>
</html>
And it doesn't work like I intended to. It should generate a random number from 100 to 999.
(I am generating separate digits because later I will need to check if there are same digits in that number (for example 222)).
So what did I do wrong? Any kind of help would be nice. Thank you.
You could do it using the += in each function or you could simplify it a little more.
function generate1() {
return Math.floor((Math.random() * 9) + 1);
}
function generate2() {
return Math.floor((Math.random() * 9) + 0);
}
function generate3() {
return Math.floor((Math.random() * 9) + 0);
}
function maingen() {
var a = generate1();
var b = generate2();
var c = generate3();
document.getElementById("numbers").innerHTML = a + '' + b + '' + c;
}
You can also do it like this
function generate_rand() {
return Math.floor((Math.random() * 9));
}
function maingen() {
var a = generate_rand() + 1;
var b = generate_rand();
var c = generate_rand();
document.getElementById("numbers").innerHTML = a + '' + b + '' + c;
}
Not sure if this is your solution, but looks like the functions are misspelled. I see:
function generuoti1() {
var a = Math.floor((Math.random() * 9) + 1);
document.getElementById("numbers").innerHTML = a; <--generating the first digit (from 1 to 9)
}
function generuoti2() {
var b = Math.floor((Math.random() * 9) + 0);
document.getElementById("numbers").innerHTML = b; <--generating the second digit (from 0 to 9)
}
But then your main function is calling different functions:
function maingen(){
generate1();
generate2();
generate3();
}
I see that one of those functions is spelled right, so that may be why you're only seeing 1 digit. Try fixing your function names for generate1() and generate2().
And then as mentioned in the comments, append your innerHTML with += instead of =
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;
}
}
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);