D. Winning D. Winning - 3 years ago 65
Javascript Question

Player Levelling function not working how I would like

I am creating a very simple text based RPG to test my skills. I am a beginner when it comes to JS and I am using this to learn and hone my existing skills so please bear with me if this seems really basic.

Effectively, I created a function that checks to see if the players current EXP is equal to or greater than the players required EXP. It works great in that it actually levels my player up and gives skill points etc.

Here is the function:

function getExp(amt) {
player.currentExp += amt;
if (player.currentExp >= player.reqExp) {
player.level ++;
player.reqExp = (player.level * 100) + ((player.level * 10) * 4);
player.currentExp = 0;
player.points += 5;
}
}


Say for example that your required EXP is 100 and you receive 120 EXP points. Instead of adding 20 EXP to the next level, it will always reset to 0. I understand that I have set it to do this, but I am wondering how I could get round this. I would still like the EXP bar to empty and start again from 0 (+ the extra EXP that carried over from the previous level).

I am using HTML progress bars for HP, MP and EXP.

Thanks in advance.

Lae Lae
Answer Source

All you have to do to fix problems like these is work your logic again from the start. The code above levels up the player and the resets the bar. You are not checking if the EXP your player gains is greater or equal to the required amount separately.
Instead what you should do is this:

function getExp(amt) {
  player.currentExp += amt;
  if (player.currentExp == player.reqExp) { //the amount gained is equal to the required
    player.level ++;
    player.reqExp = (player.level * 100) + ((player.level * 10) * 4);
    player.currentExp = 0;
    player.points += 5;
  } else if (player.currentExp > player.reqExp){//the amount gained is greater than the required one
    //calculate the extra EXP gained
    var extra = player.currentExp - player.reqExp;
    player.level ++;
    player.reqExp = (player.level * 100) + ((player.level * 10) * 4);
    player.currentExp = extra;
    player.points += 5;
}

A friendly note: this logic needs a lot more work, for example, what if the player gains exp equal to two levels?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download