I have to write a code to simulate a one-on-one dual between 2 warriors. To do this I have written a class
attack as its attributes.
The duel occurs according to the following principle:
Every turn one of the warriors will hit another one, who will lose his health in the same value as the attack of the first warrior. After that, the second warrior will do the same to the first one.
To achieve the above logic, I have written the below recursive function called
class Warrior: def __init__(self, x, y): self.health = x self.attack = y self.is_alive = True def lets_dual(warrior1, warrior2): print('warrior1 health', warrior1.health) print('warrior2 health', warrior2.health) if warrior2.health > 1 and warrior1.health > 1: # print('after attack warrior1 health', warrior1.health) warrior2.health -= warrior1.attack print('after attack warrior2 health', warrior2.health) # check if warrior 2 is still alive or not if warrior2.health > 0: warrior1.health -= warrior2.attack print('after attack warrior1 health', warrior1.health) lets_dual(warrior1, warrior2) print('this wont get printed') elif warrior1.health > 0: warrior2.is_alive = False else: warrior1.is_alive = False dave = Warrior(50, 5) carl = Warrior(50, 7) print(lets_dual(dave, carl)) print(dave.is_alive)
The problem is that the recursion logic is not working properly. Somehow the statement
'this wont get printed' is getting executed. Also I want to add a return statement showing the
warrior2.is_alive flag but it is returning