I'm trying to solve the following example script;
player = {
hp : 150,
maxHp : 150,
def : 12,
isDead : false,
level: 1,
xp : 0,
maxXp : [0,10,50,150,300,500,800,1500,3000,5000,9000,20000,50000,100000],
update(){
const thresholds = [0,10,50,150,300,500,800,1500,3000,5000,9000,20000,50000,100000];
const index = thresholds.findIndex((t) => t > this.xp);
const level = index === -1 ? thresholds.length : index;
this.level = level
}
}
In this case, I want to add a certain level to a player based on how much experience they have. Therefore, I added 15x numbers in the array that the player needs to reach a certain level. As an example, index 0 equals level 1 (default) and index 4 equals level 5.
If my XP is 299, then I'll be level 5 because my method only gets closet numbers.
CodePudding user response:
I think the easiest way is to find the index of which the required exp is greater than the total exp. Then you can check if the index was found or not for the level.
const thresholds = [0,10,50,150,300,500,800,1500,3000,5000,9000,20000,50000,100000];
const xp = 299;
const index = thresholds.findIndex((t) => t > xp);
const level = index === -1 ? thresholds.length : index;
console.log(level);