在我的程序中,我希望当英雄的健康状况为0而不是整个程序时退出该功能。我可以做什么?

时间:2017-04-24 06:33:53

标签: python python-3.x

当用户输入食物='Apple'健康状况变为0并且在我的循环中它将持续到3次我想要在健康变为0 0r小于0时退出循环。
如何解决退出函数循环的问题,但继续执行剩余的程序?

print("Let us play a game")

class Hero():
def __init__(self, heroName):
    self.heroName = heroName
    self.health = 100
def game(self, food):
    if food == 'Apple':
        print("Hero is dead")
        self.health = self.health - 100
    #something to do here I think
    elif food == 'Banana':
        self.health +=30
    elif food == 'Pear':
        self.health -= 40
    else:
        print("We are strict to our rules You just got 3 choices")

    x = input("Press <A> to continue")
   if x == 'a':
   name = input("Enter Your Name")
  print("Welcome!",name, " You can Play An Intersting Game")
  heroName = input(" What name do you want to give your hero")
  hero = Hero(heroName)
  print("Ok, Your Hero is ", hero.heroName)
  print("Now lets paly the game...\n\n You have three choices to food your 
  hero (i) Apple (ii) Banana (iii) Pear\n\n")

 i = 0
 while i < 3:
    food = input("What You want your hero to feed")
    hero.game(food)
    print("Life of",hero.heroName,"is",hero.health)

    i +=1



  sth = input("Press anykey and then hit <ENTER> to exit...")

3 个答案:

答案 0 :(得分:2)

当英雄的健康状况为break时,您应该<= 0。添加类似

的内容
if hero.health <= 0:
    break

在循环中的适当位置。

答案 1 :(得分:1)

这样的事情:

退出循环意味着

while something:
    if self.health <= 0:
       break

退出该功能并继续使用程序

while something:
    if self.health <= 0:
        break

call_hero()

答案 2 :(得分:0)

print "Let us play a game"

class Hero():

     def __init__(self, heroName):

     self.heroName = heroName

     self.health = 100

def game(self, food):

    if food == 'Apple':

       print"Hero is dead"

       self.health = self.health - 100

   elif food == 'Banana':

      self.health +=30

  elif food == 'Pear':

     self.health -= 40

  else:

   print "We are strict to our rules You just got 3 choices"

x = raw_input("Press 'a' to continue")

if x == 'a':

    name = str(raw_input("Enter Your Name"))

    print "Welcome!",name, " You can Play An Intersting Game"

    heroName =str(raw_input(" What name do you want to give your hero"))

    hero = Hero(heroName)

    print "Ok, Your Hero is ", hero.heroName

    print "Now lets paly the game...\n\n You have three choices to food your 
    hero (i) Apple (ii) Banana (iii) Pear\n\n"

i = 0

else:

   print "entry not allowed"

   i=4

while i < 3:

     food=str(raw_input("What You want your hero to feed"))

     hero.game(food)

     if hero.health<1:

          i=i+4

     else:

          print "Life of",hero.heroName,"is",hero.health

          i +=1

sth = str(raw_input("Press anykey and then hit <ENTER> to exit..."))

您可以使用此代码来学习并制作有趣的游戏来解决问题。