- 14th Dec 2023
- 19:45 pm
This code sets up a basic text-based RPG where the player faces an enemy. The player and enemy have health, attack, and defense attributes. Players can choose to attack or run away in each turn. The battle continues until either the player or the enemy runs out of health.
import random
class Character:
def __init__(self, name, health, attack, defense):
self.name = name
self.health = health
self.attack = attack
self.defense = defense
def take_damage(self, damage):
actual_damage = max(0, damage - self.defense)
self.health -= actual_damage
def is_alive(self):
return self.health > 0
def attack_enemy(self, enemy):
damage = random.randint(1, self.attack + 3)
enemy.take_damage(damage)
print(f"{self.name} attacks {enemy.name} and deals {damage} damage!")
def main():
print("Welcome to the Text-based RPG!")
player = Character("Player", 100, 15, 8)
enemy = Character("Enemy", 80, 12, 5)
while player.is_alive() and enemy.is_alive():
print(f"Player Health: {player.health}, Enemy Health: {enemy.health}")
print("1. Attack")
print("2. Run")
choice = input("Enter your choice: ")
if choice == "1":
player.attack_enemy(enemy)
elif choice == "2":
print("You ran away!")
break
else:
print("Invalid choice. Try again.")
if enemy.is_alive():
enemy.attack_enemy(player)
if player.is_alive():
print("Congratulations! You defeated the enemy!")
else:
print("Game Over. The enemy has defeated you.")
if __name__ == "__main__":
main()
About the Author - Jane Austin
Jane Austin is a 24-year-old programmer specializing in Java and Python. With a strong foundation in these programming languages, she possesses expertise in software development and application design. Jane has a knack for problem-solving and thrives in collaborative environments, where she contributes her skills to develop efficient and innovative solutions.