用python写:设计人和狗的属性:攻击力、血量等等。 游戏开始后,生成2个人和3条狗,可以随机生成它们的属性。 设计攻击方式,例如人可以用拳头攻击,狗可以用嘴巴攻击。 当人被狗咬了或者狗被人打了,双方掉血。 当某个角色的血量为0时,它就死亡了。 游戏结束时,显示胜利者。
时间: 2023-12-17 22:04:13 浏览: 21
下面是一个简单的示例代码,实现了你的要求:
```python
import random
class Character:
def __init__(self, name, attack, hp):
self.name = name
self.attack = attack
self.hp = hp
def is_alive(self):
return self.hp > 0
def take_damage(self, damage):
self.hp -= damage
if self.hp < 0:
self.hp = 0
class Human(Character):
def __init__(self, name=None):
attack = random.randint(10, 20)
hp = random.randint(50, 100)
super().__init__(name or 'Human', attack, hp)
def punch(self, target):
damage = random.randint(5, 15)
print(f'{self.name} punches {target.name} for {damage} damage')
target.take_damage(damage)
class Dog(Character):
def __init__(self, name=None):
attack = random.randint(5, 15)
hp = random.randint(20, 40)
super().__init__(name or 'Dog', attack, hp)
def bite(self, target):
damage = random.randint(2, 10)
print(f'{self.name} bites {target.name} for {damage} damage')
target.take_damage(damage)
humans = [Human(f'Human{i}') for i in range(1, 3)]
dogs = [Dog(f'Dog{i}') for i in range(1, 4)]
while True:
attacker = random.choice(humans + dogs)
targets = [t for t in (humans + dogs) if t != attacker and t.is_alive()]
if not targets:
break
target = random.choice(targets)
if isinstance(attacker, Human):
attacker.punch(target)
else:
attacker.bite(target)
if not target.is_alive():
print(f'{target.name} is dead')
winner = [c for c in (humans + dogs) if c.is_alive()]
print(f'{winner[0].name} wins!')
```
这个代码中,我们定义了一个 `Character` 基类,表示游戏中的角色,包括攻击力、血量等属性,以及掉血受伤和死亡判断等方法。然后分别定义了 `Human` 和 `Dog` 类,继承自 `Character`,并分别实现了攻击方法 `punch` 和 `bite`。最后,我们生成了两个人和三条狗,并使用随机数生成它们的属性。在游戏循环中,每次随机选择一个角色进行攻击,直到只剩下一个胜利者。
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)