【问题标题】:Complete the while loop完成while循环
【发布时间】:2021-08-20 22:36:03
【问题描述】:

#Code Project : 射击游戏。

你正在创建一个射击游戏!

游戏有两种类型的敌人,外星人和怪物。你用你的激光射击外星人,用你的枪射击怪物。每次命中都会使敌人的生命减少 1。给定的代码声明了一个通用的 Enemy 类,以及 Alien 和 Monster 类,以及它们相应的生命值。它还为 Enemy 类定义了 hit() 方法。

您需要执行以下操作才能完成该程序:

1.从 Enemy 类继承 Alien 和 Monster 类。

2.完成while循环,不断地从用户输入中选择武器并调用相应对象的hit()方法。

示例输入:

laser
laser
gun
exit

样本输出:

Alien has 4 lives
Alien has 3 lives 
Monster has 2 lives

我完成了第 1 部分,但在第 2 部分需要帮助。

class Enemy:
  name = ""
  lives = 0
  def __init__(self, name, lives):
    self.name = name
    self.lives = lives

  def hit(self):
    self.lives -= 1
    if self.lives <= 0:
       print(self.name + ' killed')
    else:
        print(self.name + ' has '+ str(self.lives) + ' lives')

class Monster(Enemy):
  def __init__(self):
    super().__init__('Monster', 3)

class Alien(Enemy):
  def __init__(self):
    super().__init__('Alien', 5)


m = Monster()
a = Alien()

while True:
    x = input()
    if x == 'exit':
        break

【问题讨论】:

    标签: python python-3.x class inheritance methods


    【解决方案1】:

    在就 stackoverflow 提出任何问题时,请遵循社区准则。请查看此链接How do I ask and answer homework questions?

    查看此代码:

    while True:
        x = input()
        if x == 'exit':
            break
        elif x == 'laser':
            a.hit()
        elif x == 'gun':
            m.hit()
            
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-12
      • 2016-06-16
      • 2017-04-29
      • 2019-04-09
      • 1970-01-01
      • 1970-01-01
      • 2022-10-12
      • 1970-01-01
      相关资源
      最近更新 更多