我正在尝试创建一个简单的关卡系统,但它不知何故不更新关卡。谁能帮我这个? (钱和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 :(得分: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;
}
}
答案 1 :(得分:0)
你的代码+更好的结构和一个有效的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