I have recently begun programming in Python and decided to start my journey by writing a text-based RPG. The issue that I have now stumbled upon is that I was trying to create an EXP-system to make the character’s stats dependent on their level, but it doesn’t seem to work the way I want it to. While I have achieved to change the character’s level based on their EXP, it does not seem to affect the other instance’s values (i.e. health, strenght etc.).
First, I defined the class “Player” which is a child class:
from termcolor import colored
class Player(Subject):
def __init__(self, name, sex, health, power, accuracy, speed):
super().__init__(name, sex, health, power, accuracy, speed)
self.level = 0
self.health = int(health + self.level * 30)
self.power = int(power + self.level * 20)
self.accuracy = float(accuracy + self.level * 0.005)
self.speed = float(speed + self.level * 10)
self.exp = 0
After that, I defined an instance method and created a list for the EXP required to reach a certain level. (the list is actually imported, but I am going to put it here):
def player_level(self, exp):
print("You receive", colored(f"{exp} EXP.", "green"))
old_level = self.level
self.exp = self.exp + exp
self.level = len([x for x in levels if self.exp >= x])
if self.level > old_level:
print(colored(f"You are now LvL {self.level}!", "green"))
levels = [0, 50, 100, 200, 300, 400, 600, 850]
# let's assume I wanted to run the following
p = Player("Alpha", "male", 100, 40, 0.7, 100)
Player.level(p, 200)
The issue that now occurs is that I can say
print(p.level)
and it returns the correct value, but if I let it print any other attribute:
print(p.health, p.power, p.accuracy, p.speed)
, they remain exactly the same as defined at the beginning.
How could I fix this so that if e.g. p.level = 4, p.health would be 220?
Edit: I put
self.level
at the top and tried out different values. I does calculate the other attributes correctly, but I cannot change it with my method outside of the__init__
.
Advertisement
Answer
Your class variables retain the value you initialized them with until you change them. You need to modify your player_level method to update the attributes on a change of level from their old values to new values.
It should look like this:
def player_level(self, exp):
print("You receive", colored(f"{exp} EXP.", "green"))
old_level = self.level
self.exp = self.exp + exp
self.level = len([x for x in levels if self.exp >= x])
if self.level > old_level:
self.health = int(self.health + self.level * 30)
self.power = int(self.power + self.level * 20)
self.accuracy = float(self.accuracy + self.level * 0.005)
self.speed = float(self.speed + self.level * 10)
print(colored(f"You are now LvL {self.level}!", "green"))
Additionally you could modify your method to print out the new values and verify they are as expected.
Finally you never call your player_level method. I would have expected code like
p = Player("Alpha", "male", 100, 40, 0.7, 100)
p.player_level(200)