设计“战士”类,实例化两个对象,赋予相应属性和行为,实现两个战士的战斗行为,直到其中一个Hp≤0;
时间: 2024-05-07 10:17:38 浏览: 6
好的,您想让我帮您回答这个问题。下面是我设计的战士类的代码和实例化两个对象的过程:
```python
class Warrior:
def __init__(self, name, hp, power):
self.name = name
self.hp = hp
self.power = power
def attack(self, other):
damage = self.power
print(f'{self.name} attacks {other.name} for {damage} damage.')
other.hp -= damage
if other.hp <= 0:
print(f'{other.name} has been defeated.')
def __str__(self):
return f'{self.name} (HP: {self.hp}, Power: {self.power})'
# 实例化两个战士对象
warrior1 = Warrior('张三', 100, 20)
warrior2 = Warrior('李四', 120, 18)
# 让两个战士对象战斗直到其中一个Hp≤0
while warrior1.hp > 0 and warrior2.hp > 0:
warrior1.attack(warrior2)
warrior2.attack(warrior1)
if warrior1.hp <= 0:
print(f'{warrior1.name}被击败了!')
else:
print(f'{warrior2.name}被击败了!')
```
以上就是我设计的战士类和实例化两个对象的过程。如果您有任何问题或需要进一步帮助,请随时告诉我。