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;
}
}
Related
/*Declare each backgroundColor value for each divs*/
var RR;
var GG;
var BB;
/*Declare the numbers of divs for making boxes*/
var y_end = 70;
var x_end = 70;
/*Declare the position*/
var x;
var y;
/*the time now*/
var now = new Date();
/*CSS*/
document.write("<style>");
for (y = 1; y <= y_end; y++) {
for (x = 1; x <= x_end; x++) {
if (x < 6) RR = "0" + (x * 3).toString(16);
else RR = (x * 3).toString(16);
if (y < 6) GG = "0" + (y * 3).toString(16);
else GG = (y * 3).toString(16);
BB = (4 * now.getSeconds()).toString(16);
if (now.getSeconds() < 4) BB = "0" + (4 * now.getSeconds()).toString(16);
var hex = "#" + GG + BB + RR;
document.write(" .r" + x + "g" + y + "{ margin:0; padding:0;width:1vw; height:0.5vh; background-color:" + hex + "; }");
}
}
document.write("</style>");
/*makes divs for cubes*/
document.write("<div id='cube' style='display:block'>");
for (y = 1; y <= y_end; y++) {
document.write("<div style='display:table-cell;'>");
for (x = 1; x <= x_end; x++) {
document.write("<div class='r" + x + "g" + y + "'></div>");
}
document.write("</div>");
}
<script src="cube.js"></script>
I am making a color-square that changes in every single second.
but I can't find where should I put setInterval() in my code.
first, I use it only at /CSS/ but it doesn't work. also a bunch of error come.
You can't use document.write for anything else than initialising a html document.
If you want to use setInterval to change CSS values you can use dom manipulation, for example:
setInterval(function(){
var div = document.getElementById("mydiv");
div.style.background-color = "rgb(155, 102, 102)";
},1000);
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'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.
I've been trying to figure out why this 'for' only loops once. Having spent about 6 hours re-writing conditions, I was wondering if you could give me a hand with spotting the problem.
Thanks in advance for any piece of advise and your time !
var k;
var i = 1;
function stergeLinie(k) {
var tabel = document.getElementById('produse');
var rowCount = tabel.rows.length;
var row = document.getElementById("tr" + k);
row.parentNode.removeChild(row);
var t = rowCount;
for (y = k; y < t; y++) {
document.getElementById("nrcrtid" + (y + 1)).value = y;
document.getElementById("nrcrtid" + (y + 1)).name = "nr_crt" + y;
document.getElementById("nrcrtid" + (y + 1)).id = "nrcrtid" + y;
document.getElementById("prodid" + (y + 1)).name = "prod" + y;
document.getElementById("prodid" + (y + 1)).id = "prodid" + y;
document.getElementById("umid" + (y + 1)).name = "um" + y;
document.getElementById("umid" + (y + 1)).id = "umid" + y;
document.getElementById("cantitateid" + (y + 1)).name = "cantitate" + y;
document.getElementById("cantitateid" + (y + 1)).id = "cantitateid" + y;
document.getElementById("pretid" + (y + 1)).name = "pret" + y;
document.getElementById("pretid" + (y + 1)).id = "pretid" + y;
document.getElementById("pretfaraTVAid" + (y + 1)).name = "pretfaraTVA" + y;
document.getElementById("pretfaraTVAid" + (y + 1)).id = "pretfaraTVAid" + y;
document.getElementById("tvaid" + (y + 1)).name = "tva" + y;
document.getElementById("tvaid" + (y + 1)).id = "tvaid" + y;
document.getElementById("tr" + (y + 1)).id = "tr" + y;
document.getElementById("buton" + (y + 1)).id = "buton" + y;
document.getElementById("butons" + (y + 1)).onclick = function onclick(event) {
stergeLinie(y);
}
document.getElementById("butons" + y).id = "butons" + (y);
}
alert(y);
document.getElementById("tr" + i).style.height = "100%";
i--;
}
The main problem is this line:
document.getElementById("butons" + (y + 1)).onclick = function onclick(event) {
stergeLinie(y);
}
y is getting incremented each time the loop runs (y++), so when the button is actually clicked, y has the value it had on the final iteration - which is just enough to get the loop to run once.
Another issue you're having is this line:
var rowCount = tabel.rows.length;
Where your ids are 1-based, that is the lowest number is 1, whereas the length property is 0 based. If there are 4 rows, rowCount will be 3, meaning that your loop will never reach 4 because the condition is y < rowCount.
Here's a cut down version of your script: http://jsfiddle.net/trolleymusic/XTzjb/ -- I also had to run the function once at the beginning to bind the click in the way that you're doing it.
Here's an updated version that loops correctly: http://jsfiddle.net/trolleymusic/Z8UYp/
var k;
var i = 1;
function stergeLinie(k) {
console.log("k: " + k);
var tabel = document.getElementById('produse');
// Add 1 to the rowCount because the elements have been assigned
// ids starting with 1, and length is 0-based
var rowCount = tabel.rows.length + 1;
var row = document.getElementById("tr" + k);
row.parentNode.removeChild(row);
var t = rowCount;
console.log(t, k);
for (var y = k; y < t; y++) {
console.log("Loop: " + y);
// If the elements don't exist anymore because they were removed
// skip the loop
if (!document.getElementById("butons" + (y + 1))) {
continue;
}
document.getElementById("butons" + (y + 1)).onclick = function onclick(event) {
// Get the number out of the
// id of the element that was clicked
var x = parseInt(this.id.replace("butons",""));
console.log("x: " + x);
stergeLinie(x);
}
}
}
metadings helpfully added below that you could use a closure for y (http://jsfiddle.net/trolleymusic/dxy6N/)
for (var y = k; y < t; y++) {
(function (y) {
document.getElementById("butons" + (y + 1)).onclick = function onclick(event) {
console.log(y);
stergeLinie(y);
}
}(y));
}
It looks much more complicated, but it's not really. You're putting all of the actions into another function, and passing the value of y to that function as an argument - that means that y is not the same variable as the y that you're incrementing in the loop, it belongs to the function inside the loop. This is closure. The accepted answer to this question: How do JavaScript closures work? gives an excellent explanation of closure.
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);