var score = 0, time = 1, heart = 3;
window.onload = function() {
var input = document.getElementById("wordTyped");
var timeLeft = document.getElementById("time");
var life = document.getElementById("life");
input.addEventListener("click", timer, false);
function timer() {
var id = setInterval(countdown, 10);
function countdown() {
input.removeEventListener("click", timer, false);
timeLeft.innerHTML = "Time left: " + (time - 0.01).toFixed(2) + "s";
time = 1 * (time - 0.01).toFixed(2);
if (time == 0 && life.innerHTML == "") {
clearInterval(id);
} else if (time == 0) {
--heart;
time = 1;
life(heart);
}
}
function life(heart) {
heart *= 1; // To make sure it is a number type
console.log(heart);
switch (heart) {
case 2:
life.innerHTML = "❤️❤️";
console.log(life.innerHTML);
break;
case 1:
life.innerHTML = "❤️";
console.log(life.innerHTML);
break;
case 0:
default:
life.innerHTML = "";
console.log(life.innerHTML);
break;
}
/*if(heart === 2) {
life.innerHTML = "❤️❤️";
}
else if(heart == 1) {
life.innerHTML = "❤️";
}
else {
life.innerHTML = "";
}*/
}
}
}
<div id="wordGenerated">illustration</div>
<input id="wordTyped" type="text" />
<div id="time">Time left: 1.00s</div>
<div id="score">Score: 0</div>
<div id="life">❤️❤️❤️</div>
I'm not sure what is wrong within the function life(heart).
I'm trying to decrease the amount of '❤️' by one as the time hit 0 and reset back to its original value, repeating until heart equals to 0.
If I use life.innerHTML = " example " outside the function timer() scope, it will work.
Using console.log(), it shows that life.innerHTML has changed, however, the display of HTML document stays the same and I don't understand why.
I've tried .nodeValue, .innerText, and .textContent, and all still gave the same result
There is a conflict usage with life variable and life() function. Change life() function name to something else like updateLife() and your code works,
Note: You can't have the same name for variable or function or Objects within the scopes.
Demo
var score = 0, time = 1, heart = 3;
window.onload = function() {
var input = document.getElementById("wordTyped");
var timeLeft = document.getElementById("time");
var life = document.getElementById("life");
input.addEventListener("click", timer, false);
function timer() {
var id = setInterval(countdown, 10);
function countdown() {
input.removeEventListener("click", timer, false);
timeLeft.innerHTML = "Time left: " + (time - 0.01).toFixed(2) + "s";
time = 1 * (time - 0.01).toFixed(2);
if (time == 0 && life.innerHTML == "") {
clearInterval(id);
} else if (time == 0) {
--heart;
time = 1;
updateLife(heart);
}
}
function updateLife(heart) {
heart *= 1; // To make sure it is a number type
console.log(heart);
switch (heart) {
case 2:
life.innerHTML = "❤️❤️";
console.log(life.innerHTML);
break;
case 1:
life.innerHTML = "❤️";
console.log(life.innerHTML);
break;
case 0:
default:
life.innerHTML = "";
console.log(life.innerHTML);
break;
}
/*if(heart === 2) {
life.innerHTML = "❤️❤️";
}
else if(heart == 1) {
life.innerHTML = "❤️";
}
else {
life.innerHTML = "";
}*/
}
}
}
<div id="wordGenerated">illustration</div>
<input id="wordTyped" type="text" />
<div id="time">Time left: 1.00s</div>
<div id="score">Score: 0</div>
<div id="life">❤️❤️❤️</div>
there is a conflict between life and life function so you can go like $("#life").innerHTML="" or any thing else
Related
I have this bit of code, I would like the user to be redirected to another page (test.html) after a 10 second timer has gone by. How would I accomplish this if the "if" statement is true.
case 'disconnect':
if (connect === 1) {
$('#terminal').append('<div>C:/root/anon> ' + $(this).val() + '<br><br>Disconnecting...<br>Disconnected<br><br><span id="blinking">_</span></div>');
disconnect = 1;
connect = 0;
minutes = 0;
seconds = 0;
} else {
$('#terminal').append('<div>C:/root/anon> ' + $(this).val() + '<br><br>Failed.<span id="blinking">_</span></div>');
}
break;
default:
Can you try this:
var timeleft = 10;
var downloadTimer = setInterval(function(){
timeleft -= 1;
if(timeleft <= 0){
clearInterval(downloadTimer);
window.location='http://www.google.com';
}
}, 1000);
You can use setTimeout method.
ex.
window.setTimeout(function(){
window.location.href="YOUR ADDRESS HERE";
},10000);
This would redirect the page after a time of 10000ms (10 seconds) has elapsed.
Hope adding this works for you.
var seconds = 10;
setTimeout(function(){ window.location = '/test.html'; }, seconds*1000);
case 'disconnect':
if (connect === 1) {
$('#terminal').append('<div>C:/root/anon> ' + $(this).val() + '<br><br>Disconnecting...<br>Disconnected<br><br><span id="blinking">_</span></div>');
disconnect = 1;
connect = 0;
minutes = 0;
seconds = 10;
setTimeout(function(){ window.location = '/test.html'; }, seconds*1000);
} else {
$('#terminal').append('<div>C:/root/anon> ' + $(this).val() + '<br><br>Failed.<span id="blinking">_</span></div>');
}
break;
default:
I have a game where every time the user's score is 5, 10, or 15 it adds a new enemy. The numbers I randomly chose and intend to change later on.
I was able to figure out how to add new enemies every time the player reaches one of these scores but I have to make a new boolean variable for every new score. How can I write this same code in a smarter way without many booleans?
Sketch.js
var addEnemyAt5= true; //boolean I have to create over and over
var addEnemyAt10 = true;
var addEnemyAt15 = true;
var score = 0;
if (score == 5 && enemyScore5) {
console.log("new enemy at 5");
addEnemyAt5 = false;
} else if (score == 10 && enemyScore10) {
console.log("new enemy at 10");
addEnemyAt10 = false;
} else if (score == 15 && enemyScore15) {
console.log("new enemy at 15");
addEnemyAt15 = false;
}
HUD.js
this.scoreUpdate = function() {
score += 5;
}
You could create a lastScore variable to track when changes to score have been accounted for:
Sketch.js:
var lastScore = 0
var score = 0
if (score > lastScore) {
if (score === 5) {
console.log("new enemy at 5")
} else if (score === 10) {
console.log("new enemy at 10")
} else if (score === 15) {
console.log("new enemy at 15")
}
lastScore = score
}
HUD.js:
this.scoreUpdate = function() {
score += 5
}
Demo Snippet:
var lastScore = 0
var score = 0
setInterval(function SketchDotJS() {
if (score > lastScore) {
if (score === 5) {
console.log("new enemy at 5")
} else if (score === 10) {
console.log("new enemy at 10")
} else if (score === 15) {
console.log("new enemy at 15")
}
lastScore = score
}
}, 10)
;(function HUDDotJS() {
this.scoreUpdate = function() {
score += 5
}
})()
<!-- Boilerplate code to get the demo to work -->
<button onclick="scoreUpdate()">Increase <var>score</var> by 5</button>
<pre><var>score</var> = <span id="score">0</span></pre>
<script>setInterval(function(e){score===+e.textContent||(e.textContent=score)},10,document.getElementById('score'))</script>
Try perhaps:
createEnemyAtScore = {
5: true,
10: true,
15: true
};
var score = 10;
if (createEnemyAtScore[score]) {
// create your enemy... or whatever..
}
but I would suggest moving this question to CodeReview
You can organize theme into an object
var milestoneMet = {
5: false,
10: false,
15: false
};
// for each milestone, check and set milestoneMet
I am making a javascript code that has a button and when I click on it, it displays one of 5 symbols but when I click the button, it shows the random symbol but the button disapears. I'm new to javascript so can I please get some help?
<script>
function slots()
{
var slot1 = Math.floor(Math.random()*5);
if (slot1 == 0) {
document.write("\u2663");
}
if (slot1 == 1) {
document.write("\u2665");
}
if (slot1 == 2) {
document.write("\u2666");
}
if (slot1 == 3) {
document.write("\u2660");
}
if (slot1 == 4) {
document.write("7");
}
}
</script>
<button type="button" value="Spin" name="SPIN"onClick="slots(); return false;"></button>
When you write document.write() the screen refreshes, so I guess you could do something like this:
<script>
function slots()
{
var slot1 = Math.floor(Math.random()*5);
if (slot1 == 0) {
document.getElementById('value').innerHTML = "\u2663";
}
if (slot1 == 1) {
document.getElementById('value').innerHTML = "\u2665";
}
if (slot1 == 2) {
document.getElementById('value').innerHTML = "\u2666";
}
if (slot1 == 3) {
document.getElementById('value').innerHTML = "\u2660";
}
if (slot1 == 4) {
document.getElementById('value').innerHTML = "7";
}
}
</script>
<button type="button" value="Spin" name="SPIN" onClick="slots();">Click</button>
<span id="value"></span>
Slightly optimized version of otrebla's code, see it in action:
function slots() {
var slot1 = Math.floor(Math.random() * 5);
var value = document.getElementById('value');
switch (slot1) {
case 0:
value.innerHTML = "\u2663";
break;
case 1:
value.innerHTML = "\u2665";
break;
case 2:
value.innerHTML = "\u2666";
break;
case 3:
value.innerHTML = "\u2660";
break;
case 4:
value.innerHTML = "7";
break;
}
}
<button type="button" value="Spin" name="SPIN" onClick="slots();">Click</button>
<span id="value"></span>
I have a problem i want to check a variable.If its 0 then gain ++ after 1.5s.If its 10 then gain ++ after .4s.Its complicated.It doesnt really work.My code so far:
if(road == 1){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1400);}
else if(road == 2){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1300);}
else if(road == 3){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1200);}
else if(road == 4){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1100);}
else if(road == 5){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1000);}
else if(road == 6){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},900);}
else if(road == 7){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},800);}
else if(road == 8){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},600);}
else if(road == 9){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},400);}
else if(road == 10){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},200);}
else{setInterval(function(){stamina++;document.getElementById("stamina").innerHTML = stamina;},1500);}
And the code to build a road is this:
function build_road() {
if ((wood + tavern) >= 29 && stone > 4 && road < 10) {
road++;
document.getElementById("road_count").innerHTML = road;
wood = (wood + tavern) - 20;
stone = stone - 5;
document.getElementById("wood").innerHTML = wood;
document.getElementById("stone").innerHTML = stone;
exp = exp + 20;
var x = document.getElementById("PROGRESS");
x.setAttribute("value", exp);
x.setAttribute("max", max);
if (exp == 100) {
exp = 0;
level++;
document.getElementById("level").innerHTML = level;
}
alert("Congratulations,You've create a Road,Now you gain stamina slightly faster.");
}
else {
alert("You need: 30Wood,5Stone .Maximum 10 Roads.")
}
}
Make reusable functions (it's often a good practice, when you a difficulties with a piece of code, to break it into small functions):
var staminaIncreaseTimer = null;
function configureStaminaIncrease(delay) {
if (staminaIncreaseTimer !== null)
clearInterval(staminaIncreaseTimer);
staminaIncreaseTimer = setInterval(function () {
increaseStamina();
}, delay);
}
function increaseStamina() {
stamina += 1;
document.getElementById("stamina").innerHTML = stamina;
}
Solution with an array (suggested by Jay Harris)
var roadIndex = road-1;
var ROAD_DELAYS = [1400, 1300, 1200, /*...*/];
var DEFAULT_DELAY = 1500;
if (roadIndex < ROAD_DELAYS.length) {
configureStaminaIncrease(ROAD_DELAYS[roadIndex]);
} else {
configureStaminaIncrease(DEFAULT_DELAY);
}
Solution with a switch instead of you if-elseif mess:
switch (road) {
case 1:
configureStaminaIncrease(1400);
break;
case 2:
configureStaminaIncrease(1300);
break;
case 3:
configureStaminaIncrease(1200);
break;
//and so on...
default:
configureStaminaIncrease(1500);
}
In my script to generate a playing card, it's generating a 0, even though my random generator is adding a 1, so it should never be 0. What am I doing wrong?! If you refresh, you'll eventually get a "0 of Hearts/Clubs/Diamonds/Spades":
var theSuit;
var theFace;
var theValue;
var theCard;
// deal a card
function generateCard() {
var randomCard = Math.floor(Math.random()*52+1)+1;
return randomCard;
};
function calculateSuit(card) {
if (card <= 13) {
theSuit = "Hearts";
} else if ((card > 13) && (card <= 26)) {
theSuit = "Clubs";
} else if ((card > 26) && (card <= 39)) {
theSuit = "Diamonds";
} else {
theSuit = "Spades";
};
return theSuit;
};
function calculateFaceAndValue(card) {
if (card%13 === 1) {
theFace = "Ace";
theValue = 11;
} else if (card%13 === 13) {
theFace = "King";
theValue = 10;
} else if (card%13 === 12) {
theFace = "Queen";
theValue = 10;
} else if (card%13 === 11) {
theFace = "Jack";
theValue = 10;
} else {
theFace = card%13;
theValue = card%13;
};
return theFace;
return theValue
};
function getCard() {
var randomCard = generateCard();
var theCard = calculateFaceAndValue(randomCard);
var theSuit = calculateSuit(randomCard);
return theCard + " of " + theSuit + " (this card's value is " + theValue + ")";
};
// begin play
var myCard = getCard();
document.write(myCard);`
This line is problematic:
} else if (card%13 === 13) {
Think about it: how a remainder of division to 13 might be equal to 13? ) It may be equal to zero (and that's what happens when you get '0 of... '), but will never be greater than 12 - by the very defition of remainder operation. )
Btw, +1 in generateCard() is not necessary: the 0..51 still give you the same range of cards as 1..52, I suppose.
card%13 === 13
This will evaluate to 0 if card is 13. a % n will never be n. I think you meant:
card % 13 === 0
return theFace;
return theValue
return exits the function; you'll never get to the second statement.