我试图编写一个使用铜,银和金的货币系统的游戏。 一旦变量达到100,我如何更改其中一个?
var copper = 0;
var silver = 0;
var gold = 0;
答案 0 :(得分:0)
使用if语句:
if (copper == 100) {
// set copper back to 0
copper = 0;
}
答案 1 :(得分:0)
这应该有效,只需在玩家获得金钱(未经测试)时调用addMoney():
var copper = 0;
var silver = 0;
var gold = 0;
function addMoney(type, amount){
if(type=='copper'){
copper += amount;
while(copper >= 100){
copper -= 100;
silver++;
}
while(silver >= 100){
silver -= 100;
gold++;
}
} else if(type=='silver'){
silver += amount;
while(silver >= 100){
silver -= 100;
gold++;
}
} else if(type=='gold'){
gold += amount;
} else {
return false;
}
return true;
}
示例:
getMoney('silver', 5);
应该返回true并将银增加5。
答案 2 :(得分:0)
我认为我们可以同时处理所有类型的货币,并认为加铜时银或金可能超过100。
var Money = (function(){
var m_copper = 9;
var m_silver = 25;
var m_gold = 30; //assume get from sever, may be ajax
var targetTop = 100;
var addCopper = function(){
m_copper += amount.copper;
while (m_copper >= targetTop){
m_copper -= targetTop;
m_silver += 1;
}
};
var addSilver = function(){
m_silver += amount.silver;
while (m_silver >= targetTop){
m_silver -= targetTop;
m_gold += 1;
}
};
var addGold = function(){
m_gold += amount.gold;
};
var validate = function(){
if (isNaN(amount.copper) || isNaN(amount.silver) || isNaN(amount.gold)){
return false;
}
return true;
}
return {
money: {
copper: 0,
silver: 0,
gold: 0
}, // actually this is not required, just for reference
add: function( money ){
amount = money;
if (!(validate())){return;}
addCopper();
addSilver();
addGold();
return {copper: m_copper, silver: m_silver, gold: m_gold};
}
};
}());
var a = Money.add({copper: 103, silver: 245, gold: 10});
console.log(a);
var b = Money.add({copper: 103, silver: 245, gold: 10});
console.log(b);