Megan
Megan

Reputation: 231

Simplifying this Python code for RPG levels

I am making a simple RPG game where Characters level based on experience (represented by x in the code below) in an exponential fashion. The levels only go up to Level 10, but I am confused what to do if their experience falls in-between the exponential numbers- I wrote this code below to round their Levels down to the lowest experience level, but is there a way to make this code simpler or more efficient?

  if 2<x<4:
        level=1
    if 4<x<8:
        level=2
    if 8<x<16:
        level=3
    if 16<x<32:
        level=4
    if 32<x<64:
        level=5
    if 64<x<128:
        level=6
    if 128<x<256:
        level=7
    if 256<x<512:
        level=8
    if 512<x<1024:
        level=9
    if x>1024:
        level=10
    print (level)

Upvotes: 1

Views: 284

Answers (3)

Shashank
Shashank

Reputation: 13869

We want to compute what is essentially floor(log_base_2(x)). Since integers are stored in binary format, their bits correspond to powers of 2. So one way to compute the level is to count the number of right-bitshifts it takes for our number to become 1. Note that a right-bitshift is essentially the same as dividing an integer by 2 and ignoring the remainder.

x_ = x
level = 0
while x_ > 1 and level < 10:
    x_ >>= 1
    level += 1

Upvotes: 1

Konstantin
Konstantin

Reputation: 25329

Based on Daniel's and abarnert's suggestions

level = min(x.bit_length()) - 1, 10)

Upvotes: 3

Aleksandr Kovalev
Aleksandr Kovalev

Reputation: 3734

from math import log

...

level = int(log(x, 2))
level = min(level, 10) # as suggested by Morb
print(level)

Upvotes: 11

Related Questions