vars not holding proper value after localStorage.getItem('key') - javascript

My code works fine up until I try to save my data, exit out, then reopen then load saved data. I save using localStorage.setItem('key', value) then I load using localStorage.getItem('key'), but after I load my vars are not holding the right values. Is localStorage.getItem('key') returning a string, because 1 +1 = 2, not 11 like it's displaying. please help.
The page itself is stored on my PC not online, I'm opening it up with Google Chrome. I run Windows Edge. When I try opening this with Internet Explorer, forget about localStorage.set/getItem all together. I've tried just running my code with the variables then try to save and load. (note:All my code works flawlessly until I try to save the variables, then reload them). I'm working on a video game so I need to be able to save my variables. And since I'm not sure where the problem in my code lies, I'm sorry but I see no other option than to post about 180 lines of code
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body bgcolor="black" >
<font color="white" >
<progress id="myProgress" value="10" max="10"></progress><br>
<p id='demo5' ;></p>
<button id="enemy" type="button" onclick="dealDamage(), imageSwap()"><img
id="enemy1" src="Game_Images/smiley_1.png"></button>
<button id="spriteTest" type="button" onclick="imageSwap2()"><img
id="enemy2" src="Game_Images/smiley_1.png"></button><br>
<button id="upgrade" type="button" onclick="upgradeClickDamage()">
</button>
<button type="button" onclick="moreGold()">More Gold</button><br>
<button type="button" onclick="saveGame()">Save Game</button>
<button type="button" onclick="loadGame()">Load Game</button>
<p id='demo' ;></p>
<p id='demo2' ;></p>
<p id='demo3' ;></p>
<p id='demo4' ;></p>
<script>
var clickDamage = 1;
var gold = 0;
var stage = 1;
var enemyNum = 1;
var enemiesTotal = 10;
var enemiesKilled = 0;
var cost = 100;
var enemyHPTotal = 10;
var enemyHPCurrent = 10;
document.getElementById("upgrade").innerHTML = "Upgrade click damage for:"
+ cost + " gold.";
document.getElementById("demo").innerHTML = "Gold: " + gold;
document.getElementById("demo2").innerHTML = "Stage: " + stage;
document.getElementById("demo3").innerHTML = "Enemies Killed This Stage:"
+ enemiesKilled + "/" + enemiesTotal;
document.getElementById("demo4").innerHTML = "Click Damage:" +
clickDamage;
document.getElementById("demo5").innerHTML = "Enemy HP remaining:" +
enemyHPCurrent + "/" + enemyHPTotal;
function imageSwap() {
var image = document.getElementById("enemy1");
if (image.src.match("Game_Images/smiley_1")){
image.src="Game_Images/smiley_2.png"
}
else if (image.src.match("Game_Images/smiley_2")){
image.src="Game_Images/smiley_3.png"
}
else {
image.src="Game_Images/smiley_1.png"
}
}
function imageSwap2(){
var image2 = document.getElementById("enemy2");
if(image2.src.match("Game_Images/smiley_1")){
setTimeout(image2.src="Game_Images/smiley_2.png", 300);
}
else if(image2.src.match("Game_Images/smiley_2")){
setTimeout(image2.src="Game_Images/smiley_3.png", 300);
}
else {
setTimeout(image2.src="Game_Images/smiley_1.png", 300);
}
}
function dealDamage() {
document.getElementById("myProgress").value -= clickDamage;
//If enemy is hit but does not die
if(document.getElementById("myProgress").value >= 1){
enemyHPCurrent = document.getElementById("myProgress").value
enemyHPTotal = document.getElementById("myProgress").max
document.getElementById("demo5").innerHTML = "Enemy HP remaining:"
+ enemyHPCurrent + "/" + enemyHPTotal;
}
//If enemy is killed and there are remaining enemies in the current stage
if (document.getElementById("myProgress").value == 0 && enemyNum < 10) {
document.getElementById("myProgress").value =
document.getElementById("myProgress").max;
gold += (1 * stage);
enemyHPTotal = document.getElementById("myProgress").value;
enemyNum += 1;
document.getElementById("demo").innerHTML = "Gold: " + gold;
document.getElementById("demo2").innerHTML = "Stage: " + stage;
enemiesKilled += 1;
document.getElementById("demo3").innerHTML = "Enemies Killed This
Stage:" + enemiesKilled + "/" + enemiesTotal;
document.getElementById("demo4").innerHTML = "Click Damage:" +
clickDamage;
enemyHPCurrent = enemyHPTotal;
document.getElementById("demo5").innerHTML = "Enemy HP remaining:"
+ enemyHPCurrent + "/" + enemyHPTotal;
}
//If the enemy is killed and it is the last enemy of the current stage
if (document.getElementById("myProgress").value == 0 && enemyNum == 10) {
document.getElementById("myProgress").max += 1;
document.getElementById("myProgress").value =
document.getElementById("myProgress").max;
gold += (1 * stage);
enemyNum = 1;
stage += 1;
document.getElementById("demo").innerHTML = "Gold: " + gold;
document.getElementById("demo2").innerHTML = "Stage: " + stage;
enemiesKilled = 0;
document.getElementById("demo3").innerHTML = "Enemies Killed This
Stage:" + enemiesKilled + "/" + enemiesTotal;
document.getElementById("demo4").innerHTML = "Click Damage:" +
clickDamage;
enemyHPTotal = document.getElementById("myProgress").max;
enemyHPCurrent = enemyHPTotal;
document.getElementById("demo5").innerHTML = "Enemy HP remaining:"
+ enemyHPCurrent + "/" + enemyHPTotal;
}
}
function upgradeClickDamage() {
if (gold >= cost) {
gold -= cost;
clickDamage += 1;
cost += 100;
document.getElementById("messageBox").innerHTML =
"Congratulations!!! You just upgraded your click damage."
document.getElementById("upgrade").innerHTML = "Upgrade click damage
for:" + cost + " gold.";
document.getElementById("demo").innerHTML = "Gold: " + gold;
document.getElementById("demo4").innerHTML = "Click Damage:" +
clickDamage;
}
else if (gold < cost) {
document.getElementById("messageBox").innerHTML = "You don't have
enough gold for this upgrade."
}
}
function moreGold() {
gold += 100;
document.getElementById("demo").innerHTML = "Gold: " + gold;
}
function saveGame(){
//save all vars
localStorage.setItem('CLICKDAMAGE', clickDamage);
localStorage.setItem('GOLD', gold);
localStorage.setItem('STAGE', stage);
localStorage.setItem('ENEMYNUM', enemyNum);
localStorage.setItem('ENEMIESTOTAL', enemiesTotal);
localStorage.setItem('ENEMIESKILLED', enemiesKilled);
localStorage.setItem('COST', cost);
localStorage.setItem('ENEMYHPTOTAL', enemyHPTotal);
localStorage.setItem('ENEMYHPCURRENT', enemyHPCurrent);
}
function loadGame(){
//load all vars
clickDamage = localStorage.getItem('CLICKDAMAGE');
gold = localStorage.getItem('GOLD');
stage = localStorage.getItem('STAGE');
enemyNum = localStorage.getItem('ENEMYNUM');
enemiesTotal = localStorage.getItem('ENEMIESTOTAL');
enemiesKilled = localStorage.getItem('ENEMIESKILLED');
cost = localStorage.getItem('COST');
enemyHPTotal = localStorage.getItem('ENEMYHPTOTAL');
enemyHPCurrent = localStorage.getItem('ENEMYHPCURRENT');
}
</script>
<div id="messageBox"></div>
</font>
</body>
</html>
I expected all variables to function properly after loading.
gold, cost, and enemiesKilled are all affected by this same problem. If gold = 1, and I save that variable then load that variable later, then add 1 again, I get 11, not 2. With cost, if cost = 100, then I save, then I load later, then I add 100 to cost, cost = 100100 not 200.

(This will restate a bit of what you hypothesized in your question for the sake of completeness)
If you look at the documentation for Storage.getItem(), it says:
Return value
A DOMString containing the value of the key. If the key does not exist, null is returned.
This means that no matter what data type you give in setItem, the output of getItem will always be a string. This is easy to test in the console:
localStorage.setItem("test", 1);
> undefined
localStorage.getItem("test");
> "1"
When you add a string to a number, it just concatenates the two together. In your case, you're adding "1" + 1 which becomes "11" instead of adding 1 + 1 which would be 2. The solution is to convert the number string into a number, which can be done several ways, but is easiest to do (in my opinion) by simply prefixing the expression with a +.
+localStorage.getItem("test");
> 1

The localStorage.setItem converts all passed values to string. Once you call localStorage.getItem you are getting back string value.
So you are trying to concatenate string and number "1" + 1 === "11".
To prevent this behavior you need to manually convert values to stringified JSON:
localStorage.setItem('CLICKDAMAGE', JSON.stringify(clickDamage));
And then parse it back:
clickDamage = JSON.parse(localStorage.getItem('CLICKDAMAGE'));

Related

Having a problem with my javascript code - computer has to guess the digit value I input

First I created a version of this which worked where I didn't input the value on the webpage:
<p>Enter in how many fingers (between 0 and 5) you are holding up: </p>
<p>
<input id="fingersInput" type="text">
<button id="fingersSubmit">Guess!</button>
</p>
<div id="fingers-game-v2"></div>
<p id="computer-guess-results"></p>
<script type="text/javascript">
var numberOfFingers = document.getElementById("fingersInput").value;
var fingersText = "";
var correctGuesses = 0;
i = 0;
while (i < 5)
{
var computerGuess = Math.floor((Math.random()*5)+1);
fingersText += "<p>" + computerGuess + "</p>";
if (computerGuess == 3)
{
var correctGuesses = correctGuesses + 1;
}
i++;
}
document.getElementById("fingers-game-v2").innerHTML = fingersText;
document.getElementById("computer-guess-results").innerHTML = "<h3>" + "Number of times the computer guessed correctly: " + "</h3>" + correctGuesses;
</script>
Then this is the version I'm trying to create where I enter in the input on the webpage, and then the computer tries to guess it, but it's not executing at all or showing anything when I try to debug in the console.
<p>Enter in how many fingers (between 0 and 5) you are holding up: </p>
<p>
<input id="fingersInput" type="text">
<button id="fingersSubmit">Guess!</button>
</p>
<div id="fingers-game-v2"></div>
<p id="computer-guess-results"></p>
<script type="text/javascript">
var numberOfFingers = document.getElementById("fingersInput").value;
var fingersText = "";
var correctGuesses = 0;
document.getElementById("fingersSubmit").onclick = function ()
{
i = 0;
while (i < 5)
{
var computerGuess = Math.floor((Math.random()*5)+1);
fingersText += "<p>" + computerGuess + "</p>";
if (computerGuess == numberOfFingers)
{
var correctGuesses = correctGuesses + 1;
}
i++;
}
document.getElementById("fingers-game-v2").innerHTML = fingersText;
document.getElementById("computer-guess-results").innerHTML = "<h3>" + "Number of times the computer guessed correctly: " + "</h3>" + correctGuesses;
}
I'm a beginner coder so if there is any useful knowledge pertaining to this in addition to showing me the correct code, then I'd greatly appreciate that!
Thanks!
Here's a working version where I tried to stay as close to your original code as possible:
<html>
<body>
<p>Enter in how many fingers (between 0 and 5) you are holding up:</p>
<p>
<input id="fingersInput" type="text" />
<button id="fingersSubmit">Guess!</button>
</p>
<div id="fingers-game-v2"></div>
<p id="computer-guess-results"></p>
<script type="text/javascript">
document.getElementById('fingersSubmit').onclick = function() {
i = 0;
var fingersText = '';
var correctGuesses = 0;
var numberOfFingers = document.getElementById('fingersInput').value;
while (i < 5) {
var computerGuess = Math.floor(Math.random() * 5 + 1);
fingersText += '<p>' + computerGuess + '</p>';
if (computerGuess == numberOfFingers) {
correctGuesses = correctGuesses + 1;
}
i++;
}
document.getElementById('fingers-game-v2').innerHTML = fingersText;
document.getElementById('computer-guess-results').innerHTML =
'<h3>' +
'Number of times the computer guessed correctly: ' +
'</h3>' +
correctGuesses;
};
</script>
</body>
</html>
The main reason your code wasnt working is because you need to get the input value when the button is clicked (i.e. place it inside the onclick)
The other issue is that you redeclare correctGuesses inside the if block, so you should just remove the var keyword, otherwise you will get NaN
Finally, this isn't strictly a problem with your code, but moving forward you should be aware that numberOfFingers is a string whereas correctGuesses is a number. In your if block, you compare the two values and it works because you used ==, which only checks value. It's typically better practice to use === which is a stricter equality check, comparing both value and type. So moving forward, you might want to make sure to convert numberOfFingers to a number before you do the equality check

How can I save best guess (higher/lower)

for example my toGuess number is 50 and my best lower guess is 48 but I guess 47 and it changes my best lower guess to that 47.
What I mean by this is that I want it not go lower anymore
Same thing with the higher guess
I want it to save/lock my best guess to the closest
'use strict'
var toGuess = Math.floor(Math.random() * (100 + 1));
console.log("To Guess: " + toGuess);
var guess = undefined;
var amount = 0;
var bestHigher = 100;
var bestLower = 0;
var hint = document.getElementById('hint');
var numbers = document.getElementById('numbers');
var lower = document.getElementById('lower');
var higher = document.getElementById('higher');
function GuessDone() {
var put = document.getElementById('number').value;
guess = Number(put);
console.log("Guess: " + guess);
document.getElementById('form').reset();
amount = amount + 1;
console.log("Guesses " + amount);
var numberDif = Number(toGuess) - Number(put);
var bestLower = Number(put) > toGuess;
var bestHigher = Number(put) < toGuess;
if (numberDif > bestLower) {
bestLower = Number(put);
console.log("Lower " + bestLower);
}
if (numberDif < bestHigher) {
bestHigher = Number(put);
console.log("Higher " + bestHigher);
}
if (guess > toGuess) {
hint.innerHTML = "You need to guess lower";
higher.innerHTML = "Best guess above " + bestHigher;
} else if (guess < toGuess) {
hint.innerHTML = "You need to guess higher";
lower.innerHTML = "Best guess below " + bestLower;
} else {
hint.innerHTML = "Congratz, " + toGuess + " was right! Guesses " + amount;
var print = "";
var i;
for (i = 0; i <= toGuess; i++) {
print += i + "<br>";
}
numbers.innerHTML = print;
}
return false;
EDIT
This is my html
<form id="form">
<label for="number">Guess number between 0-100: </label>
<input id="number" type="text" name="number">
<button type="submit">Guess</button>
</form>
<p id="lower"></p>
<p id="higher"></p>
<p id="hint"></p>
<p id="numbers"></p>
<script src="numbergame.js"></script>
FIDDLE
https://jsfiddle.net/d3761nbj/2/

Random Number Generator Javascript - Ranges

Looking for some guidance from those more knowledgeable than myself.
I'm writing a program that will prompt the user to click a button, which will then generate a random integer from 1 to 100.
I can manage that part fine. What I am struggling with is making the program print what range this random integer is in i.e. i<=33.
For example, when I click the button I want to see:
"10 is a number less than 33"
or
"55 is a number between 33 and 66"
Here is my code so far, I have put the code I am having problems with in comments.
<!DOCTYPE HTML5>
<html>
<head>
<meta charset="UTF-8">
<title>question2</title>
</head>
<body>
<p>Click the button to display a random number from 1 to 100.</p>
<button onclick="myFunction()">Click here</button>
<p id="demo"></p>
<script>
function myFunction() {
var text = "";
var i = Math.floor((Math.random() * 100) + 1);
document.getElementById("demo").innerHTML = i;
}
// if (myFunction <= 33) {
// text += ("<br>" + i + " is a number less than or equal to 33");
// }
// if (myFunction > 34 and i < 65) {
// text += ("<br>" + i + " is a number between 33 and 66 (exclusive)");
// }
// if (my Function >= 66) {
// text += ("<br>" + i + " is a number greater than or equal to 66");
// }
</script>
</body>
</html>
Thanks guys.
You could test and if true display the result and exit.
function getRandom() {
var i = Math.floor((Math.random() * 100) + 1);
if (i <= 33) {
document.getElementById("demo").innerHTML += i + " is a number less than or equal to 33<br>";
return;
}
if (i < 66) {
document.getElementById("demo").innerHTML += i + " is a number between 33 and 66 (exclusive)<br>";
return;
}
document.getElementById("demo").innerHTML += i + " is a number greater than or equal to 66<br>";
}
<p>Click the button to display a random number from 1 to 100.</p>
<button onclick="getRandom()">Click here</button>
<p id="demo"></p>
Did you mean something like this:
function myFunction() {
var text = "";
var i = Math.floor((Math.random() * 100) + 1);
if (i <= 33) {
text += ("<br>" + i + " is a number less than or equal to 33");
}
if (i > 34 && i < 65) {
text += ("<br>" + i + " is a number between 33 and 66 (exclusive)");
}
if (i >= 66) {
text += ("<br>" + i + " is a number greater than or equal to 66");
}
document.getElementById("demo").innerHTML = text;
}
The problem is you are calling variables from inside myFunction() outside of that function. Examples include i and myFunction(). It would be better to put the if else statements inside the main function.
function myFunction() {
var demo = document.getElementById("demo");
var i = Math.floor((Math.random() * 100) + 1);
if (i <= 33) {
demo.innerHTML = i + " is a number less than 33";
}
else if (i < 65) {
demo.innerHTML = i + "is a number between 33 and 65";
}
else {
demo.innerHTML = i + " is a number greater than or equal to 66";
}
}
<p>Click the button to display a random number from 1 to 100.</p>
<button onclick="myFunction()">Click here</button>
<p id="demo"></p>
Your function isn't what you should be comparing against in your if statements.
But, I did throw something together let me know if this is what you were looking for.
You were on the right track. Also on the middle comparison I changed you "and" to a shortcircuit "&&".
JSfiddle: https://jsfiddle.net/xew8dvbd/
$(document).ready(function() {
function myFunction() {
var i = Math.floor((Math.random() * 100) + 1);
var text = "";
if (i <= 33) {
text += ("<br>" + i + " is a number less than or equal to 33");
}
if (i > 34 && i < 65) {
text += ("<br>" + i + " is a number between 33 and 66 (exclusive)");
}
if (i >= 66) {
text += ("<br>" + i + " is a number greater than or equal to 66");
}
document.getElementById("demo").innerHTML = text;
};
$("#submit").click(myFunction);
});
Not sure why, but I had to do this as a function expression rather than a function definition to make it work. Oddly, that's the second time this one worked as a gotcha in the last hour.
myFunction = function() {
var text = "";
var i = Math.floor((Math.random() * 100) + 1);
document.getElementById("demo").innerHTML = i;
switch (true) {
case (i < 20):
console.log(i + " is less than 20.");
break;
case (i < 40):
console.log(i + " is between 21 and 40.");
break;
case (i < 60):
console.log(i+ " is between 21 and 60.");
break;
default:
console.log(i+ " is over 60.");
}
};
<p>Click the button to display a random number from 1 to 100.</p>
<button onclick="myFunction()">Click here</button>
<p id="demo"></p>

Adding up a current variable with the previous one

I have a problem here, basically I want my Dice game to display 3 lines.
The first line says what number of the die I got
The second line adds the number I got from the first die with the second die i rolled and so on.. (basically everytime i click the button).
The third line would just count how many times I rolled the dice.
My problem is that on my second line, im not sure how I can add up my current die roll with my previous one everytime I click the button.
var count=0;
function swap_pic()
{
var x = Math.floor(Math.random()*6)+1;
var pic = document.getElementById("dice");
var xx = x+x;
count++;
document.getElementById("result").innerHTML = "You got " + x;
document.getElementById("result").innerHTML += "<br>Your score is: " + xx;
document.getElementById("result").innerHTML += "<br>Number of tries = " + count;
if (count==5)
{
document.getElementById("result").innerHTML += "<br><span style='color:red;font-weight:bold;font-size:14px;'>Game Over!</span>";
count = 0;
document.getElementById('button').setAttribute("style","visibility:hidden");
}
if (x==1)
{
pic.src = "images/die1.png";
}
else if (x==2)
{
pic.src = "images/die2.png";
}
else if (x==3)
{
pic.src = "images/die3.png";
}
else if (x==4)
{
pic.src = "images/die4.png";
}
else if (x==5)
{
pic.src = "images/die5.png";
}
else if (x==6)
{
pic.src = "images/die6.png";
}
}
Problem is this line
document.getElementById("result").innerHTML += "<br>Your score is: " + xx;
Thank you for the help guys!
Several concatenation of innerHTML should be avoided, as well as repeated else if when possible. Try this:
var count = 0;
var sum = 0;
function swap_pic() {
var x = Math.floor(Math.random() * 6) + 1;
var pic = document.getElementById("dice");
sum += x;
count++;
var html = "You got " + x;
html += "<br>Your score is: " + sum;
html += "<br>Number of tries = " + count;
if (count == 5) {
html += "<br><span style='color:red;font-weight:bold;font-size:14px;'>Game Over!</span>";
count = 0;
document.getElementById('button').setAttribute("style", "visibility:hidden");
}
document.getElementById("result").innerHTML = html;
pic.src = "images/die" + x +".png";
}
Try this on for size
//create these as global variables
var totalScore;
var rollCount;
var lastRoll;
var image;
var text;
var button;
function reload(){
totalScore = 0;
rollCount = 0;
lastRoll = 0;
image = document.getElementById('dice'); //store image element
text = document.getElementById('result'); //store result element
button = document.getElementById('button'); //store button element
button.style.visibility = visible; //restore button visibility
}
function roll(){
lastRoll = Math.floor(Math.random()*6)+1; //generate random number
rollCount++; //increase our roll counter
totalScore+= lastRoll; //add new roll to score
image.src = "images/die" +lastRoll+ ".png"; //update dice image
text.innerHTML = "You got " // generate result string
+ lastRoll
+ "<br>Your score is: "
+ totalScore
+ "<br>Number of tries = "
+ rollCount;
if(rollCount >= 5){ //end game parameter!!
text.innerHTML += "<br><span style='color:red;font-weight:bold;font-size:14px;'>Game Over!</span>"; //add game over text
button.style.visibility = 'hidden';//hide button
//reload(); //uncomment to reset game now?
}
}
window.onload = reload; //set up on page load

Use if statement to get percentage of input?

Everything runs correctly, but I want to add a few things. At the very end of the function I want to change the height of the canvas by comparing how many you got correct out of the amount that you wanted to answer, but with a percentage. Sorry if this is difficult to understand.
JavaScript:
<script type="text/javascript">
function myFunction() {
score = 0;
questionAmount = prompt('How many question would you like to solve?');
for(i = 0; i < questionAmount; i++) {
var x = Math.floor(Math.random() * 13);
var y = Math.floor(Math.random() * 13);
question = prompt('What is ' + x + ' * ' + y + ' = ?');
if(question == null || isNaN(question)) {
break;
}
if(question == x * y) {
score++;
}
}
alert('You got ' + score + ' out of ' + questionAmount + ' correct.');
}
</script>
HTML:
<canvas id="content"></canvas>
<br />
<button onclick="myFunction()">CLICK</button>
Just create the percentage and apply it:
var correctPercent = (parseDouble(score) / parseDouble(questionAmount)) * 100;
//change the target elements style, apply above variable
document.getElementById("content").style.height = correctPercent + "%";

Categories

Resources