mathluaformula

Lua level formula


I'm trying to calculate a players level depending on the players experience.

This is what I have in text: Start at level 0 with 0 XP To reach level 1, you need 50 XP. One kill gives 10 XP. So, 5 kills = 50 XP = level 1. Now, level 2 should require 50 XP more than last level. So, level 2 requires a total of 150 XP. Level 1: 50 XP (5 kills total, 5 kills to go from level 0 to 1). Level 2: 150 XP(15 kills total, 10 kills to go from level 1 to 2). Level 3: 300 XP(30 kills total, 15 kills to go from level 2 to 3).

So far, all I got is this:

math.Round( xp / 50 )

This is 50 xp per level which isn't what I wanted; but I have really no idea where to go from here.

Simply put, I want each level to require 50 more XP than last level, and I need to get the level from an xp variable.


Solution

  • A quick math calculation shows that the experience point to reach level lv would be:

    (1 + 2 + 3 + ... + lv) * 50
    

    which equals:

    lv * (lv + 1) / 2 * 50
    

    So the question becomes to find the maximum non-negative integer lv that qualifies:

    lv * (lv + 1) / 2 * 50 <= xp
    

    That's the formula needs to be solved. And the math solution is:

    lv <= (math.sqrt(xp * 4 / 25 + 1) - 1) / 2
    

    Since you are looking for a non-negative integer, in the words of Lua, that's:

    local lv = math.floor((math.sqrt(xp * 4 / 25 + 1) - 1) / 2)
    

    You can wrap it to a function and give it a quick test like this:

    function xp_to_lv(xp)
        return math.floor((math.sqrt(xp * 4 / 25 + 1) - 1) / 2)
    end
    
    assert(0 == xp_to_lv(0))
    assert(0 == xp_to_lv(49))
    assert(1 == xp_to_lv(50))
    assert(2 == xp_to_lv(260))
    assert(3 == xp_to_lv(310))