python实现三人对决
时间: 2023-12-04 14:57:16 浏览: 112
以下是一个简单的Python程序,模拟三人对决的过程:
```python
import random
# 定义三个角色的属性
player1 = {'name': 'Alice', 'hp': 100, 'atk': 20}
player2 = {'name': 'Bob', 'hp': 100, 'atk': 20}
player3 = {'name': 'Charlie', 'hp': 100, 'atk': 20}
# 定义游戏结束的条件
def game_over():
return player1['hp'] <= 0 or player2['hp'] <= 0 or player3['hp'] <= 0
# 定义角色攻击的函数
def attack(attacker, target):
damage = random.randint(1, attacker['atk'])
target['hp'] -= damage
print(f"{attacker['name']} attacked {target['name']} and caused {damage} damage.")
if target['hp'] <= 0:
print(f"{target['name']} is defeated!")
# 开始游戏
while not game_over():
# 随机选择一个攻击者和一个目标
attacker = random.choice([player1, player2, player3])
target = random.choice([player1, player2, player3])
# 如果攻击者和目标相同,则重新选择目标
while target == attacker:
target = random.choice([player1, player2, player3])
# 攻击
attack(attacker, target)
# 游戏结束,输出最终结果
if player1['hp'] > 0:
print(f"{player1['name']} wins!")
elif player2['hp'] > 0:
print(f"{player2['name']} wins!")
else:
print(f"{player3['name']} wins!")
```
运行上述程序,可以看到三个角色交替攻击,直到只有一个角色存活为止。程序会输出最终胜者的名字。
阅读全文