Jess Muir Jess Muir - 7 months ago 11
Javascript Question

How to change a variable once it reaches a certain number in javascript

I'm trying to write a game that has a money system using copper, silver, and gold.
How do I change one of the variables once it reaches 100?

var copper = 0;
var silver = 0;
var gold = 0;

Answer

This should work, just call addMoney() when the player gets money (untested):

var copper = 0;
var silver = 0;
var gold = 0;
function addMoney(type, amount){
    if(type=='copper'){
        copper += amount;
        while(copper >= 100){
            copper -= 100;
            silver++;
        }
    } else if(type=='silver'){
        silver += amount;
        while(silver >= 100){
            silver -= 100;
            gold++;
        }
    } else if(type=='gold'){
        gold += amount;
    } else {
        return false;
    }
    return true;
}

Example:

getMoney('silver', 5);

Should return true and increment silver by 5.