Skip to content Skip to sidebar Skip to footer

Level System Based Off Points

I'm trying to make a level system based off of points, but it's kinda getting too long of a code. If you can help me make it smaller I really would appreciated it. To describe what

Solution 1:

Just to shorten your code you can save levels as a list and then count how many levels user have passed by comparing points to the level splits:

levels = [100, 200, 300, 400, 500]
lvl = len([x for x in levels if points > x])

I wouldn't worry about the speed here, but using generator could be considered as a better practice (or not, a matter of taste in this case):

lvl = sum(1 for x in levels if points > x)

Solution 2:

The bisect module is good for finding 'which item in this list is in the right range'. It returns the index number of upper end of the range your value falls into. For example

import bisect

exp_level = [100,200,300,400,500]  # bisect lists need to be sorted
level = bisect.bisect(exp_level, 127)   # = 1

In that example bisect.bisect would return "1", since index 1 (that is, 200) is the next item up in the list.

Solution 3:

If you find yourself repeating the same/similar code over and over again more than twice, it's a good sign that you need to use a loop:

xp_levels = [500, 1500, 2500, 5000, 10000, 15000, 20000, 30000, 50000, 100000, 250000]

defpointLevel(name):
    points = int(Point.dPoint[name])

    level = -1for index, xp inenumerate(xp_levels):
        if points < xp:
            level = index
            break

Solution 4:

To elaborate a bit on @sashkello, here is a function that takes in the points as an integer, and spits out the level:

defgetLevel(points):
    levels=[500,1500,2500,5000,10000,15000,20000,30000,50000,100000,250000]
    lvl = len([x for x in levels if points > x])
    return lvl

Post a Comment for "Level System Based Off Points"