Click here to Skip to main content
15,923,689 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello! I am creating a game where you can buy pokemon. When the pokemon is bought, I obviously want the coins variable to drop by the # of coins the pokemon costs. However, when I do this, the coins variable always stays at 1000 and does not drop when I buy the pokemon. Here is the function that is used when onclick on a button:

function buymagikarp() {
  if(coins >= 100 ) {
    swal("Success", "You bought 1 magikarp!", "success");
    coins - 100;
    pokemonchosen.push("Magikarp");
  } else {
    swal("Error", "Not enough balance", "error");
  }
}


What I have tried:

I have tried to remove the swal("") to see if the alerts were messing up the coins variable.
Posted
Updated 1-Aug-17 4:51am
Comments
Member 13257242 1-Aug-17 10:52am    
After tweaking the code a bit, I took a step backward and a step forward. I added in local storage:

function getName() {
var coins;
if(localStorage.getItem('coins') === null) {
localStorage.setItem('coins', coins);
} else {
coins = localStorage.getItem('coins');
}
document.getElementById("p1").innerHTML = "Coins: " + coins;
}

Now, the coins actually deplete, and they save after page reload but they still always show up as 1000 even in the console when I type in coins it shows that they depleted? This is honestly really confusing to me.

1 solution

coins - 100 just calculates the value, but never stores it. Did you mean:
JavaScript
coins -= 100; // (equivalent of:) coins = coins - 100;
?
 
Share this answer
 
v2
Comments
Member 13257242 1-Aug-17 10:54am    
After tweaking the code a bit, I took a step backward and a step forward. I added in local storage:

function getName() {
var coins;
if(localStorage.getItem('coins') === null) {
localStorage.setItem('coins', coins);
} else {
coins = localStorage.getItem('coins');
}
document.getElementById("p1").innerHTML = "Coins: " + coins;
}

Now, the coins actually deplete, and they save after page reload but they still always show up as 1000 even in the console when I type in coins it shows that they depleted? This is honestly really confusing to me.
Thomas Daniels 1-Aug-17 10:55am    
Where are you defining coins? Are you also defining it outside of getName? In that case, the 'coins' in getName probably shadows the 'coins' outside of getName.
Member 13257242 1-Aug-17 11:07am    
I am defining coins outside at the top of the code.

var coins = 1000;
Thomas Daniels 1-Aug-17 11:09am    
Well, then you don't need the 'var coins;' line in getName().
Member 13257242 1-Aug-17 11:12am    
Even after removing var coins; , it still won't deplete

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900