Reputation: 591
im trying to make a function that takes the players hp, max hp, and ammount heald and returns the new hp, but does not return a new hp higher than the max hp. i must have done the math wrong somewhere but dont know where. my first attempt:
def heal(hp,max_hp,heal):
if hp > heal:
return (max_hp + heal)
else:
overflow = heal-max_hp
new_hp = hp - overflow
return (new_hp)
hp = heal(10,30,20)
print hp #prints 20, should print 30
hp = heal(10,30,10)
print hp #prints 30, should print 20
hp = heal(10,20,30)
print hp #prints 0, should print 20.
my second attempt:
def heal(hp,max_hp,heal):
if hp > heal:
return (max_hp + heal)
else:
overflow = max_hp - heal
new_hp = hp - overflow
return (new_hp)
hp = heal(10,30,20)
print hp #prints 0, should print 30
hp = heal(10,30,10)
print hp #prints -10, should print 20
hp = heal(10,20,30)
print hp #prints 20, should print 20.
Upvotes: 0
Views: 166
Reputation: 761
This code may work:
def heal(hp,max_hp,heal):
if hp + heal > max_hp:
return (max_hp)
else:
return (hp + heal)
The new hp = current hp + heal, but can not beyond the max hp, so we compare the current hp + heal to max hp, then return the total hp of current hp plus heal, or max hp if they big than max hp.
Upvotes: 0
Reputation: 1870
First add heal to hp, then if it exceeds max_hp, return max_hp:
def heal(hp,max_hp,heal):
hp = hp + heal
if hp > max_hp:
return max_hp
else:
return hp
Upvotes: 0
Reputation: 82899
Just add the healed hit points to the current hit points and then return the smaller of that value and the max hit points.
def heal(hp, max_hp, healed):
return min(hp + healed, max_hp)
Upvotes: 4
Reputation: 881573
This should do it. Just add the healing value regardless then drop the hit points back to the maximum value if they exceed it:
def heal (hp, max_hp, heal):
hp = hp + heal
if hp > max_hp:
hp = max_hp
return hp
For what it's worth, both your solutions are defective if only because they contain:
return (max_hp + heal)
There should be no circumstance where you return something greater than max_hp
. That's aside from the strange if
conditions which I haven't analysed in depth because there's no need to - just use the code I provided above.
Upvotes: 2