2016-12-26 39 views
-1

我正在嘗試創建一個簡單的關卡系統,但它以某種方式不更新關卡。誰能幫我這個? (錢和XP下運行)xp,金錢和關卡的簡單關卡系統

var money = 0; 
var xp = 0; 
var level = 1; 

window.onload = function() { 
document.getElementById("money").innerHTML = 'Money: ' + money; 
document.getElementById("xp").innerHTML = 'XP: ' + xp; 
document.getElementById("level").innerHTML = 'Current level: ' + level; 
} 

function giveExp(number){ 
money = parseInt(money) + 50; 
xp = xp + 100; 

document.getElementById("money").innerHTML = 'Money: ' + money; 
document.getElementById("xp").innerHTML = 'XP: ' + xp; 
} 


if (xp > 150 && xp < 450) { 
level = level + 1; 
document.getElementById("level").innerHTML = 'Current level: ' + level; 
} 
+0

就把如果到gibeExp功能 –

回答

0

您的代碼+更好strucuture和工作XP系統:

var money=0,level=1,xp=0; 

function updatecounters(){ 
    if (xp > 400) { 
     level+=Math.floor(xp/400);// if xp is 1000, two levels up 
     xp=xp%400;// what is left when increasing levels 
    } 
    document.getElementById("money").innerHTML = 'Money: ' + money; 
    document.geElementById("xp").innerHTML = 'XP: ' + xp; 
    document.getElementById("level").innerHTML = 'Current level: ' + level; 
    } 


function giveExp(number){ 
    money += 50; 
    xp += 100; 
    updatecounters();//update 
} 

    window.onload=updatecounters;//onload init counters 

更好(使用IIFE和Closure):

var user=(function(){ 
    window.onload=user.update; 
    var money=0,level=1,xp=0;// no way to change these without updating (better work flow) 
    return { 
     increaseXP:function(val){ 
      xp+=val; 
      if(xp>400){//enough xp for level up 
      level+=Math.floor(xp/400); 
      xp=xp%400; 
     } 
     user.update(); 
     }, 
    increaseMoney:function(val){ 
     money +=val; 
     user.update(); 
    }, 
    update:function(){ 
     document.getElementById("money").innerHTML = 'Money: ' + money; 
     document.geElementById("xp").innerHTML = 'XP: ' + xp; 
     document.getElementById("level").innerHTML = 'Current level: ' + level; 
    }}; 
    })(); 

使用這樣的:

user.increaseXP(200); 
user.increaseMoney(-500);// bad day :/ 
user.money=500; // error, so you cant change without updating -> prevent bugs 
1

移動if語句轉換成giveExp功能:

function giveExp(number){ 
money = parseInt(money) + 50; 
xp = xp + 100; 

document.getElementById("money").innerHTML = 'Money: ' + money; 
document.getElementById("xp").innerHTML = 'XP: ' + xp; 

if (xp > 150 && xp < 450) { 
    level = level + 1; 
    document.getElementById("level").innerHTML = 'Current level: ' + level; 
} 

} 
+0

好它的工作原理,但有沒有更好的方式來創建某種級別的系統,當你達到XP的量,你的水平?因爲當我點擊按鈕時,我平了2次。 –

+0

@Raul:關於重新設置XP級別(請參閱我的解決方案)... –