Reputation: 3
So I just started out with python recently and I tried using a while loop in the code but when I click run, the program just runs forever without printing anything. I did some research on while loops but I didn't find anything that would help me. Here is the code in its entirety:
import random
HeroHP = random.randint(120 , 120)
WitchHP = random.randint(100 , 100)
Alive = 1
Dead = 0
if WitchHP > 0:
WitchStatus = Alive
if WitchHP < 1:
WitchStatus = Dead
if HeroHP > 0:
HeroStatus = Alive
if HeroHP < 1:
HeroStatus = Dead
HeroCritChance = random.randint(0 , 2)
if HeroCritChance == 2:
HeroATK = 25
if HeroCritChance == 0 or FriskCritChance == 1:
HeroATK = 10
WitchHitChance = random.randint(0 , 1)
if WitchHitChance == 0:
WitchATK = 30
if WitchHitChance == 1:
WitchATK = 0
while WitchStatus == Alive and HeroStatus == Alive:
WitchHP = WitchHP - HeroATK
HeroHP = HeroHP - WitchATK
if WitchStatus == Alive and HeroStatus == Dead:
print ("the Hero has been defeated...")
if WitchStatus == Dead and HeroStatus == Alive:
print ("the Hero has triumphed!")
if WitchStatus == Dead and HeroStatus == Dead:
print ("Peace has returned... But at a price...")
(Sorry if I'm making a very silly mistake, as I mentioned earlier, I'm really new to coding in general.)
Upvotes: 0
Views: 84
Reputation: 1424
Change this:
while WitchStatus == Alive and HeroStatus == Alive:
WitchHP = WitchHP - HeroATK
HeroHP = HeroHP - WitchATK
To an if statement:
if WitchStatus == Alive.....
In the original, once WitchStatus == Alive, it will remain that way and the loop will keep running because there is nothing that changes it. It's like forgetting to add the i = i + 1 line in a numerically counted loop.
Upvotes: 0
Reputation: 98338
In Python the assignment operation does not work that way.
It looks like when you write:
if WitchHP > 0:
WitchStatus = Alive
You think that using WitchStatus
in a future condition it will actually check the value of WitchHP
. But that's not the case, it does the secuence: first it evaluates the condition, then if that is true it assigns to WitchStatus
. If then, the value of WitchHP
changes, the WitchStatus
will not change, unless you run this statement again.
What you want is a function:
def WitchStatus():
if WitchHP > 0:
return Alive
else:
return Dead
while WitchStatus() == Alive:
WitchHP = WitchHP - HeroATK
Then, every time you use the function with WitchStatus()
the program will check the condition again.
Upvotes: 2