我想要一些算法来构建一个PHP升级系统我已经建立了一个系统来升级人们,但是如果人们获得了大量的exp,那么他们需要多次升级我的代码示例:
if(isset($_POST['id']) && isset($_POST['amount'])) {
$amount = $_POST['amount'];
$user = $_POST['id'];
$exp;$etnl;$newExp;$level;
`//select exp and etnl from DB
$result = DB::getInstance() ->query("SELECT exp,etnl,level FROM exp WHERE id = $user");
$result->setFetchMode(PDO::FETCH_ASSOC);
$row = $result->fetch();
$exp = $row['exp'];
$etnl = $row['etnl'];
$level = $row['level']
//c where to level up user or to add exp to his ep bar
if($amount + $exp > $etnl) {
$etnl = $etnl * 2;
$leftOvers = ($amount + $exp) - $etnl;
$newExp = $leftOvers;
$level = $level + 1;`
$result = DB::getInstance()->prepare("UPDATE exp SET exp=?,level=?,etnl=? WHERE id=?");
$result->execute(array($amount,$level,$etnl,$user));
} else {
$result = DB::getInstance()->prepare("UPDATE exp SET exp=? WHERE id=?");
$result->execute(array($amount,$user));
}
}`
` 但是如果exp可以将任何帮助或任何新代码提升2倍,那么这个系统会失败吗? BTW etnl代表exp到下一级谢谢
答案 0 :(得分:0)
你必须得到一个水平表,基本上是[exp,level]对的列表。例如,
$level_list = [
['exp' => 0, 'level' => 1],
['exp' => 100, 'level' => 2],
['exp' => 1000, 'level' => 3],
// etc.
];
然后,从结尾开始迭代表:
$i = count($level_list);
while($i > 0) {
$i--;
if ($user_exp >= $level_list[i]['exp']) {
// this is the level we need
break;
}
}
$target_level = $level_list[$i]['level'];
$target_exp = $level_list[$i]['exp'];
答案 1 :(得分:0)
如果您不想像其他答案一样手动输入关卡表,您也可以尝试使用递归函数进行处理:
$current_exp = 0;
$current_level = 1;
$to_next_level = 1000;
function did_level( $amount = 0 ) {
global $current_exp;
global $curent_level;
global $to_next_level;
$tmp_amount = $amount + $current_exp;
$tmp_amount_remainder = $tmp_amount - $to_next_level;
if ($tmp_amount >= $to_next_level) {
$current_level++;
$to_next_level *= 2;
$current_exp = $tmp_amount;
if ($tmp_amount_remainder > 0) {
// Level us up again.
did_level( $tmp_amount_remainder );
} else {
// Store the new level, to next level, and current exp
}
} else {
// Store the new exp amount
}
}