I'm making a leveling system based on experience you have on the site. I already have all the experience stuff figured out, and how I want to do the leveling, but I need a more efficient way to do it. I know this would probably would be achieved using an array, but I don't really know how to go about doing that. Enough blabbering, though, this is what I'm trying to do...
Level 1 will be anything under 150 experience Then I'm going to multiply that by 1.5, so Level 2 will be anything under 225 Level 3 will be anything under 337.5 and so on. This is the inefficient way that I was going to do.
if($xp < 150){
$level = "1";
}elseif($xp < 225){
$level = "2";
}elseif($xp < 337.5){
$level = "3";
}
I could use a variable for the number and multiple by 1.5 ($number*1.5
), but like I said before I don't really know how that'd work.
*Some more info.. I have a session file included on every page and I have queries that would check every time there is new experience earned and this code would be used to update the level on the database automatically.
Try
$level = min(max((int)(log($xp / 100, 1.5) + 1), 1), $maxLevel);
That takes the logarithm base 1.5 of xp/100 (i.e. the number of times you'd have to multiply 100 by to get $xp), then adds one (since log($x, 1.5) is less than one if $x is less than 1.5). The min(max(..., minLevel), maxLevel)
construct lets you clamp the level to lie between 1 and $maxLevel
, also avoiding any issues with negative levels (if $xp
is sufficiently less than 150).
I'd agree. either objects or arrays would be best.
Something like:
$array = array(
array(
'xp_required' => 150,
'level' => 1
),
array(
'xp_required' => 225,
'level' => 2
),
array(
'xp_required' => 337.5,
'level' => 3
)
);
$current_xp = 155;
foreach( $array as $reqs ){
if( $current_xp > $reqs['xp_required'] ){
$level = $reqs['level'];
}
}
echo $level';
well at the moment once you grab the users exp you can have that code block as a function to constantly check for variations in exp levels, but use a ranged statement
if($xp < 150){
$level = "1";
}elseif($xp > 150 && $xp < 225 ){
$level = "2";
}elseif($xp > 225 && $xp < 337.5){
$level = "3";
}
Here's how I did my level system. It's a little more advanced featuring skill points..
<?php
$level_up = ($level + 1);
if ($exp >= $max_exp)
{
$sql = "UPDATE users SET level=(level + 1) , max_exp=(exp * 1.05) , skill_points=(skill_points + 3) WHERE id='".$id."' LIMIT 1";
$res = mysql_query($sql);
if ($exp >= $max_exp)
echo '<div class="Leveled">' . 'You sucessfully leveled up to ' . $level_up . '!' . ' As a reward you were given 3 skill points!' . '</div>';
}
else
{
}
?>