I'm creating a text based game with multiple stats you have to keep up, such as stamina, health, etc. and I am having trouble with what happens if they go below 0
. I know a while-loop would work I could do:
life = 1
while(life > 0):
print("You are alive!")
print("Oh no! You got shot! -1 Life")
life-1
print("You are dead! Game Over!")
But I don't know how to do that with multiple conditions such as stamina, hunger, strength etc.
您可以使用min
将它们合并为一个测试:
while min(life, health, stamina) > 0:
Since 0
evaluates to False
in Python, you can use all
:
while all((life, stamina, hunger, strength)):
This will test if all of the names are not equal to zero.
If however you need to test if all of the names are greater than zero (meaning, they could become negative), you can add in a generator expression :
while all(x > 0 for x in (life, stamina, hunger, strength)):
You can always use and
and or
. For example:
while (life > 0) and (health > 0) and (stamina > 0):
You could put if
statements into the while loop that check those stats at the start of each iteration. That way you can handle each event individually.
life = 1
while(life > 0):
if stamina < 1:
print "out of stamina"
break
if hunger < 1:
print "You died of hunger"
break
print("You are alive!")
print("Oh no! You got shot! -1 Life")
life-1
print("You are dead! Game Over!")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.