Pet*_*ter -3 php algorithm math
我正在建立一个小游戏,并陷入开发调平系统.我创建了一个函数,它将指数级地增加下一级所需的体验.但是,我不知道如何扭转它,以便我可以投入用户获得的经验并获得相应的级别.
function experience($level, $curve = 300) {
// Preset value to prevent notices
$a = 0;
// Calculate level cap
for ($x = 1; $x < $level; $x++) {
$a += floor($x+$curve*pow(2, ($x/7)));
}
// Return amount of experience
return floor($a/4);
}
Run Code Online (Sandbox Code Playgroud)
我想知道如何对这个函数进行逆向工程,以便为一定的经验返回正确的级别.
使用上面的函数,我的代码将输出以下内容:
Level 1: 0
Level 2: 83
Level 3: 174
Level 4: 276
Level 5: 388
Level 6: 512
Level 7: 650
Level 8: 801
Level 9: 969
Level 10: 1154
Run Code Online (Sandbox Code Playgroud)
我正在寻找的是一种方法来反转这个功能,以便我可以输入一定数量,它将返回相应的水平.
例如,1000经验应该返回9级.
Roa*_*ich 15
将值插入excel并创建趋势线,我得到以下等式:
y = 1.17E-09x^3 - 4.93E-06x^2 + 1.19E-02x + 6.43E-02
Run Code Online (Sandbox Code Playgroud)
所以你的逆向工程方程就是
function level($xp) {
$a = 1.17e-9;
$b = -4.93e-6;
$c = 0.0119;
$d = 0.0643
return round($a*pow($xp, 3) + $b*pow($xp,2) + $c * $xp + $d);
}
Run Code Online (Sandbox Code Playgroud)
结果精确到1dp以内,但如果您的$curve更改,则需要重新计算.我也没有超过10级.
其他选项包括缓存查找结果:
$levelXpAmounts = array()
function populateLevelArray($curve=300) {
$levelXpAmounts[$curve] = array();
for($level = $minlevel; $level <= $maxLevel; $level++) {
$levelXpAmounts[$curve][$level] = experience($level);
}
}
//at game load:
populateLevelArray()
Run Code Online (Sandbox Code Playgroud)
然后,您的反向查找将是
function level($xp, $curve=300) {
if (!array_key_exists($levelXpAmounts, curve)
populateLevelArray($curve);
for($level = $minlevel; $ level <= $maxLevel; $level++) {
if ($xp < $levelXpAmounts[$curve][$level]) {
return $level - 1;
}
}
}
Run Code Online (Sandbox Code Playgroud)
这样,对于每个不同的值,只对所有级别进行迭代$curve.您还可以experience()使用(很可能更快)查找替换旧函数.
注意:自从我编写任何php以来已经有一段时间了,所以我的语法可能有点生疏.对于这方面的任何错误,我事先道歉.