PHP Get Experience by Level

ぃ、小莉子 提交于 2019-12-11 09:42:11

问题


I have this piece of code that loops 1 through 99 and is a formula.

function getExperienceByLevel ($maxLevel)
{
    $levels = array ();
    $current = 0;

    for ($i = 1; $i <= $maxLevel; $i++)
    {
        $levels[$i - 1] = floor ($current / 4);
        $current +=  floor($i+300*pow(2, ($i/9.75)));
    }

    return $levels;
}

First you initiate it like so $aLevels = getExperienceByLevel(99); then to see how much EXP you need to get to level 6 you do this echo $aLevels[5]; since it's an array.

Now I'm trying to do reverse. Get Level by EXP.

function getLevelByExp($exp) 
{
    $myLevel = 0;
    $aLevels = getExperienceByLevel(99);

    for ($i = 1; $i < 100; $i++)
    {
        if ($exp > $aLevels[$i-1]) 
        { 
            return $myLevel;
        }
    }
}

When called upon getLevelByExp(1124); or any number inside, it seems to return a zero. But it seems to work when you put echos inside that statement.

Like instead of return $myLevel do echo "You are up to level $i<br />"; and it will go all the way up to the current level you've gained EXP for.

But still.. doesn't work when I want to simply return a number.


回答1:


This seems to work better than your function:

function getLevelByExp($exp)
{
        $aLevels = getExperienceByLevel(99);
        for ($i = 0;  $i <= 99;  ++$i)
        {
                //echo "cmp $exp >= aLevels[$i]={$aLevels[$i]}\n";
                if ($exp <= $aLevels[$i])
                        return $i - 1;
        }
        return -1;
}

It needs improvement for the edge cases, such as when $exp is zero.




回答2:


Return $i instead because it always '0'

if ($exp > $aLevels[$i-1]) { 
        return $i;
    }



回答3:


You never change $myLevel, so it will always stay at 0.

Try returning $i instead of $myLevel, as $i is actually changing:

function getLevelByExp($exp) {
    $aLevels = getExperienceByLevel(99);

    for ($i = 1; $i < 100; $i++) {
        if ($exp > $aLevels[$i-1]) { 
            return $i;
        }
    }
}


来源:https://stackoverflow.com/questions/12614786/php-get-experience-by-level

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!