I have a list of objects at the class level, and a class method fight which operates with the objects from that list:
from Heroes import Hero
from Creatures import Creature
from random import randint
class Battle():
"""template to simulate the battle"""
obj_list = []
def __init__(self,obj1_name,obj2_name):
#create hero
self.obj1 = Hero(obj1_name, health = randint(70,100), strength = randint(70,80), defence = randint(45,55), speed = randint(40,50), luck = randint(10,30))
Battle.obj_list.append(self.obj1)
#create creature
self.obj2 = Creature(obj2_name, health = randint(70,100), strength = randint(70,80), defence = randint(45,55), speed = randint(40,50), luck = randint(10,30))
Battle.obj_list.append(self.obj2)
@classmethod
def fight(cls):
"""simulate fight"""
# first attack is landed by the obj with highest speed
if cls.obj_list[0].speed > cls.obj_list[1].speed:
cls.obj_list[1].health = cls.obj_list[0].attack() - cls.obj_list[1].defence
# same speed first attack landed by the obj with highest luck
elif cls.obj_list[0].speed == cls.obj_list[1].speed:
if cls.obj_list[0].luck >= cls.obj_list[1].luck:
cls.obj_list[1].health = cls.obj_list[0].attack() - cls.obj_list[1].defence
else:
cls.obj_list[0].health = cls.obj_list[1].attack() - cls.obj_list[0].defence
#self.obj1.speed < self.obj2.speed
else:
cls.obj_list[0].health = cls.obj_list[1].attack() - cls.obj_list[0].defence
return cls.obj_list
if __name__ == "__main__":
first_round = Battle("Icarus","Beast")
for i in Battle.obj_list:
print(i.name,i.health)
Battle.fight()
for i in Battle.obj_list:
print(i.name,i.health)
Battle.fight()
for i in Battle.obj_list:
print(i.name,i.health)
Output:
Icarus 90
Beast 74
Icarus 30
Beast 74
Icarus 30
Beast 74
The first call of the fight method updates correctly the health attribute of the objects from obj_list but then no matter how many times I call the method, health attribute it's not updated anymore. What am I missing, should I use another approach to share the state for objects ?