F
F
funkydance2019-04-18 22:41:13
PHP
funkydance, 2019-04-18 22:41:13

How to find out the user level?

Hello.
I want to make a level system for users on the site.
The first level starts with 100 experience points, the next level is added + 10% of the previous one.
Level 1 = 100XP Level
2 = 110XP Level
3 = 121XP
etc.
I have only the sum of experience from the data, for example 2500 experience, how to subtract what level it will be in PHP? It turns out that this is the sum of the first n members of the geometric sequence with the beginning 100 and the multiplier 1.1.
Do not swear, while I can not even imagine how to do it.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Alexander Shapoval, 2019-04-18
@funkydance

require_once 'vendor/autoload.php';

function levelGenerate(&$levels)
{
    $max_level = 100; // тут указывается максимально возможный уровень
    $lastLevel = $levels->last();

    $levels->push([
        'level' => ++$lastLevel['level'],
        'rating' => $lastLevel['rating'] * 1.1,
    ]);

    if ($levels->last()['level'] < $max_level) {
        return levelGenerate($levels);
    }
}

$levels = collect();
levelGenerate($levels);

$my_rating = 1245;
$my_level = $levels->where('rating', '<=', $my_rating)->last();
dd($my_level['level']); // 27

// my_rating = 741
// array:2 [▼
//   "level" => 22
//   "rating" => 740.02499442582
// ]

// my_rating = 150
// array:2 [▼
//   "level" => 5
//   "rating" => 146.41
// ]

// my_rating = 1245
// array:2 [▼
//   "level" => 27
//   "rating" => 1191.8176537727
// ]

For the script to work, you need to include this library https://github.com/tightenco/collect
Requirements: PHP 7.1

A
Alexander Aksentiev, 2019-04-18
@Sanasol

Complex option: https://gamedev.stackexchange.com/a/110437
Simple: https://gamedev.stackexchange.com/a/110457
Even simpler: generate a table of levels exp, lvl with a finite number of levels and a simple sql query to find out current level without unnecessary calculations.

V
Victorius13, 2019-04-18
@Victorius13

echo getlevel(230);

function getlevel($xp) {
$l = 100;
for ($i = 0; ; $l = $l + $l * 1.1) {
  $i++;
  if ($l > $xp) {
    break;
  }
}
return $i;
}

A
antikirill, 2019-04-18
@antikirill

So the level can be described by the expression:
100*(1.1 to the power of n)= 2500
To get n - we need the power of the root of 2500/100 to get 1.1 (the integer part of the root)
Therefore:
$currentPoint = 2500/100;
$levelUp = 1.1;
$level = intval(log($currentPoint, $levelUp));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question