python rpg游戏代码
时间: 2023-08-28 20:06:27 浏览: 529
以下是一个简单的Python RPG游戏代码示例:
```
import random
class Player:
def __init__(self, name, health, attack, defense):
self.name = name
self.health = health
self.attack = attack
self.defense = defense
def attack_enemy(self, enemy):
damage = self.attack - enemy.defense
if damage > 0:
enemy.health -= damage
print(f"{self.name} did {damage} damage to {enemy.name}.")
else:
print(f"{self.name} did no damage to {enemy.name}.")
def is_alive(self):
return self.health > 0
class Enemy:
def __init__(self, name, health, attack, defense):
self.name = name
self.health = health
self.attack = attack
self.defense = defense
def attack_player(self, player):
damage = self.attack - player.defense
if damage > 0:
player.health -= damage
print(f"{self.name} did {damage} damage to {player.name}.")
else:
print(f"{self.name} did no damage to {player.name}.")
def is_alive(self):
return self.health > 0
class Game:
def __init__(self):
self.player = Player("Player", 100, 20, 10)
self.enemies = [
Enemy("Goblin", 50, 10, 5),
Enemy("Orc", 75, 15, 8),
Enemy("Dragon", 200, 30, 20)
]
def start(self):
print("Welcome to the RPG game!")
print("You will face various enemies and must defeat them to win.")
while self.player.is_alive() and self.enemies:
enemy = random.choice(self.enemies)
print(f"A {enemy.name} has appeared!")
while enemy.is_alive() and self.player.is_alive():
print(f"{self.player.name} (Health: {self.player.health})")
print(f"{enemy.name} (Health: {enemy.health})")
print("What do you want to do?")
print("1. Attack enemy")
print("2. Run away")
choice = input("Enter your choice (1 or 2): ")
if choice == "1":
self.player.attack_enemy(enemy)
elif choice == "2":
print("You ran away!")
break
else:
print("Invalid choice!")
if enemy.is_alive():
enemy.attack_player(self.player)
if not enemy.is_alive():
print(f"You defeated the {enemy.name}!")
self.enemies.remove(enemy)
if not self.enemies:
print("Congratulations! You have defeated all the enemies and won the game!")
else:
print("Game over. You have been defeated by an enemy.")
game = Game()
game.start()
```
这个游戏有一个玩家和多个敌人。玩家和敌人都有名字、生命值、攻击力和防御力。玩家可以选择攻击敌人或逃跑。如果玩家选择攻击,他们会造成攻击力减去敌人防御力的伤害。如果玩家选择逃跑,游戏将结束。如果敌人死亡,它将从可用敌人列表中删除。如果所有敌人都被击败,玩家就赢了游戏。
阅读全文