用python代码做一个双人格斗小游戏
时间: 2023-09-05 15:11:36 浏览: 165
使用Python写一个小游戏
好的,这是一个简单的双人格斗小游戏的Python代码:
```python
import random
class Player:
def __init__(self, name, health, attack):
self.name = name
self.health = health
self.attack = attack
def is_alive(self):
return self.health > 0
def attack_player(self, other_player):
damage = random.randint(1, self.attack)
other_player.health -= damage
print(f"{self.name} attacks {other_player.name} and deals {damage} damage.")
def __str__(self):
return f"{self.name} ({self.health} health)"
# 创建两个玩家
player1 = Player("Player 1", 100, 20)
player2 = Player("Player 2", 100, 20)
# 游戏循环
while player1.is_alive() and player2.is_alive():
# 玩家1攻击
player1.attack_player(player2)
# 玩家2攻击
if player2.is_alive():
player2.attack_player(player1)
# 游戏结束
if player1.is_alive():
print(f"{player1.name} wins!")
else:
print(f"{player2.name} wins!")
```
这个游戏有两个玩家,每个玩家有100点健康值和20点攻击力。每个玩家轮流攻击对方,攻击力是随机的1到自己的攻击力之间。当一个玩家的健康值小于等于0时,游戏结束,另一个玩家获胜。
阅读全文