Write a simple text rpg game with ability to fight monsters and level up after getting enough exp points. Also monsters should drop items that will be added into inventory
Assistant
Sure! Below is a simple text-based RPG game written in Python. The game allows the player to fight monsters, earn experience points (XP), level up, and collect items dropped by defeated monsters. The game runs in the console, and you can interact with it by following the prompts.
Features:
Player Character: Has attributes like health, attack power, defense, level, experience, and an inventory to store items.
Monsters: Each monster has its own health, attack power, defense, experience yield, and possible item drops.
Combat System: Turn-based combat where the player and the monster take turns attacking each other.
Leveling Up: Gain experience points from defeating monsters. Level up when enough XP is accumulated, which increases the player's stats.
Inventory System: Collect items dropped by monsters and view them in the inventory.
How to Run:
Make sure you have Python installed on your system (Python 3.x recommended).
Copy the code below into a file named text_rpg.py.
Open your terminal or command prompt and navigate to the directory containing text_rpg.py.
Run the game with the command: python text_rpg.py
python
import random
# Define Item class
class Item:
def __init__(self, name, description, healing=0):
self.name = name
self.description = description
self.healing = healing
def __str__(self):
return f"{self.name}: {self.description}"
# Define Monster class
class Monster:
def __init__(self, name, health, attack, defense, exp, drop_items):
self.name = name
self.health = health
self.attack = attack
self.defense = defense
self.exp = exp
self.drop_items = drop_items # List of Item objects
def is_alive(self):
return self.health > 0
# Define Player class
class Player:
def __init__(self, name):
self.name = name
self.level = 1
self.exp = 0
self.exp_to_level = 100
self.max_health = 100
self.health = self.max_health
self.attack = 20
self.defense = 10
self.inventory = []
def is_alive(self):
return self.health > 0
def gain_exp(self, amount):
self.exp += amount
print(f"You gained {amount} XP.")
if self.exp >= self.exp_to_level:
self.level_up()
def level_up(self):
self.level += 1
self.exp -= self.exp_to_level
self.exp_to_level = int(self.exp_to_level * 1.5)
self.max_health += 20
self.health = self.max_health
self.attack += 5
self.defense += 3
print(f"\n*** Congratulations! You reached level {self.level}! ***")
print(f"Stats increased: Health: {self.max_health}, Attack: {self.attack}, Defense: {self.defense}\n")
def add_item(self, item):
self.inventory.append(item)
print(f"Added {item.name} to your inventory.")
def show_inventory(self):
if not self.inventory:
print("Your inventory is empty.")
else:
print("\n--- Inventory ---")
for idx, item in enumerate(self.inventory, 1):
print(f"{idx}. {item}")
print("-----------------\n")
def use_item(self):
if not self.inventory:
print("You have no items to use.")
return
self.show_inventory()
try:
choice = int(input("Select the number of the item you want to use (0 to cancel): "))
if choice == 0:
return
item = self.inventory[choice - 1]
if item.healing > 0:
self.health += item.healing
if self.health > self.max_health:
self.health = self.max_health
print(f"You used {item.name} and healed for {item.healing} HP.")
self.inventory.pop(choice - 1)
else:
print(f"{item.name} has no use.")
except (IndexError, ValueError):
print("Invalid choice.")
# Function to create random monsters
def generate_monster():
monsters = [
Monster("Goblin", 50, 10, 5, 50, [Item("Small Potion", "Heals 20 HP", healing=20)]),
Monster("Skeleton", 60, 12, 8, 60, [Item("Bone Shield", "Increases defense")]),
Monster("Orc", 80, 15, 10, 80, [Item("Orcish Axe", "A mighty axe that increases attack")]),
Monster("Troll", 120, 20, 15, 120, [Item("Troll Hide", "Can be used to craft armor")]),
Monster("Dragon", 200, 30, 20, 300, [Item("Dragon Scale", "Very rare and powerful")])
]
return random.choice(monsters)
# Combat system
def combat(player, monster):
print(f"\nA wild {monster.name} appears!")
while monster.is_alive() and player.is_alive():
print(f"\nYour Health: {player.health}/{player.max_health}")
print(f"{monster.name} Health: {monster.health}")
print("\nChoose your action:")
print("1. Attack")
print("2. Use Item")
print("3. Run")
choice = input("Enter your choice: ")
if choice == '1':
# Player attacks
damage = max(player.attack - monster.defense, 1)
monster.health -= damage
print(f"You attack the {monster.name} for {damage} damage.")
elif choice == '2':
player.use_item()
continue # Skip monster's turn if player uses an item
elif choice == '3':
if random.random() < 0.5:
print("You successfully ran away!")
return
else:
print("Failed to run away!")
else:
print("Invalid choice.")
continue
# Check if monster is defeated
if not monster.is_alive():
print(f"\nYou defeated the {monster.name}!")
player.gain_exp(monster.exp)
# Handle item drops
if monster.drop_items:
drop_chance = random.random()
if drop_chance < 0.7: # 70% chance to drop an item
dropped_item = random.choice(monster.drop_items)
print(f"The {monster.name} dropped a {dropped_item.name}!")
player.add_item(dropped_item)
break
# Monster's turn to attack
damage = max(monster.attack - player.defense, 1)
player.health -= damage
print(f"The {monster.name} attacks you for {damage} damage.")
if not player.is_alive():
print("\nYou have been defeated. Game Over.")
exit()
# Main game loop
def main():
print("=== Welcome to the Text RPG Game ===")
player_name = input("Enter your character's name: ")
player = Player(player_name)
print(f"\nWelcome, {player.name}! Your adventure begins...\n")
while player.is_alive():
print("Choose an action:")
print("1. Explore (Fight a monster)")
print("2. View Inventory")
print("3. View Stats")
print("4. Use Item")
print("5. Quit Game")
choice = input("Enter your choice: ")
if choice == '1':
monster = generate_monster()
combat(player, monster)
elif choice == '2':
player.show_inventory()
elif choice == '3':
print(f"\n--- {player.name}'s Stats ---")
print(f"Level: {player.level}")
print(f"EXP: {player.exp}/{player.exp_to_level}")
print(f"Health: {player.health}/{player.max_health}")
print(f"Attack: {player.attack}")
print(f"Defense: {player.defense}")
print("---------------------------\n")
elif choice == '4':
player.use_item()
elif choice == '5':
print("Thank you for playing! Goodbye.")
break
else:
print("Invalid choice. Please select a valid action.")
if not player.is_alive():
print("You have perished on your journey. Game Over.")
if __name__ == "__main__":
main()
Explanation of the Code:
Classes:
Item: Represents items that can be dropped by monsters. Items can have healing properties.
Monster: Represents monsters with attributes like health, attack, defense, experience points, and possible item drops.
Player: Represents the player character with attributes such as level, experience, health, attack, defense, and an inventory to hold items.
Gameplay Functions:
generate_monster(): Randomly selects and returns a monster from a predefined list.
combat(player, monster): Handles the combat between the player and a monster. The player can choose to attack, use an item, or attempt to run away. After each action, the monster may attack back.
main(): The main game loop where the player can choose to explore (fight monsters), view inventory, view stats, use items, or quit the game.
Leveling Up:
When the player gains enough experience (exp_to_level), they level up, increasing their stats and setting a new experience threshold.
Items and Inventory:
Monsters have a chance to drop items upon defeat. These items are added to the player's inventory, which can be viewed and used to gain benefits like healing.
User Interaction:
The game interacts with the player through the console, prompting for inputs to make decisions during exploration and combat.
Customization and Expansion:
This is a basic framework for a text-based RPG. You can expand upon it by adding more features such as:
Different Item Types: Weapons, armor, special items with unique effects.
Multiple Locations: Introduce different areas or maps to explore.
Quests and Storylines: Add quests to provide direction and objectives.
More Complex Combat Mechanics: Include special abilities, magic, or status effects.
Save and Load Functionality: Allow players to save their progress and continue later.
Feel free to modify and enhance the game to suit your preferences. Happy coding and adventuring!