Question

What is wrong with this function? When I use 31 for exp, this function becomes an infinite loop! How can I fix that? Please help and optimize this function for me if you can, thanks.

public function exp_calc($exp)
    {
        $level2 = 30; // Required EXP for 2nd level
        $current_lvl = 0; // Current level
        $level = 0; // Required EXP for next level

        while((int)$level <= $exp)
        {
            $level += $level2;
            $level2 *= 0.25;
            $current_lvl++;
        }

        if($current_lvl >= 80)
            $current_lvl = 80;

        return array ($current_lvl, (int)$level);
    }
Was it helpful?

Solution

$level2 *= 0.25;

 1   2     3
30 7.5 1.125

I assume you mean *= 1.25 there, to increase the amount of experience needed for the next level exponentially :).

The current function limits somewhere below 40 I think (get some calculus to calculate the limit ;)).

Edit; to clearify (since I though it wasn't yet):

level one requires 30 exp total now; level two requires 7.5 additional exp; total of 37.5 level three requires 1.125 exp; total of 38.625 etc.

When using *= 1.25; the amount of exp needed to reach the next level actually increases: 30 -> 37.5 -> 46.875 -> 58.594 -> etc

OTHER TIPS

I'm not sure what you want the outcome to be, but the reason it becomes an infinite loop is that every iteration you make $level2 smaller (a quarter of its size) until eventually it will practically become 0. The loop won't exit until $level is as great as (or equal) to $exp, which will never happen once $level2 becomes 0. Without doing the maths I guess 31 is the threshold that can never be reached as $level2 becomes too small to increment by.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top