Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Certainly! I'll expand the code to include more features, such as a map system, additional player stats, a level-up mechanism, and a simple quest system. Here's a longer version of the text-based adventure game:
- ```python
- import random
- import time
- import json
- class Player:
- def __init__(self, name):
- self.name = name
- self.level = 1
- self.exp = 0
- self.max_health = 100
- self.health = self.max_health
- self.strength = 10
- self.defense = 5
- self.inventory = {}
- self.location = "Town Square"
- self.quests = []
- class Enemy:
- def __init__(self, name, level, health, damage, exp_reward):
- self.name = name
- self.level = level
- self.health = health
- self.max_health = health
- self.damage = damage
- self.exp_reward = exp_reward
- class Item:
- def __init__(self, name, description, effect, value):
- self.name = name
- self.description = description
- self.effect = effect
- self.value = value
- class Quest:
- def __init__(self, name, description, objective, reward):
- self.name = name
- self.description = description
- self.objective = objective
- self.reward = reward
- self.completed = False
- class Map:
- def __init__(self):
- self.locations = {
- "Town Square": ["Merchant's Shop", "Tavern", "Forest Path"],
- "Merchant's Shop": ["Town Square"],
- "Tavern": ["Town Square"],
- "Forest Path": ["Town Square", "Dark Cave", "River Bank"],
- "Dark Cave": ["Forest Path"],
- "River Bank": ["Forest Path", "Mountain Trail"],
- "Mountain Trail": ["River Bank", "Mountain Peak"],
- "Mountain Peak": ["Mountain Trail"]
- }
- def print_slowly(text):
- for char in text:
- print(char, end='', flush=True)
- time.sleep(0.02)
- print()
- def create_enemies():
- return [
- Enemy("Goblin", 1, 30, 5, 10),
- Enemy("Wolf", 2, 40, 8, 15),
- Enemy("Orc", 3, 60, 12, 25),
- Enemy("Troll", 4, 100, 18, 40),
- Enemy("Dragon", 10, 200, 30, 100)
- ]
- def create_items():
- return {
- "Health Potion": Item("Health Potion", "Restores 50 HP", lambda player: heal(player, 50), 20),
- "Strength Potion": Item("Strength Potion", "Increases strength by 5", lambda player: buff_stat(player, "strength", 5), 30),
- "Iron Sword": Item("Iron Sword", "A sturdy iron sword", lambda player: equip_weapon(player, "Iron Sword", 5), 50),
- "Steel Armor": Item("Steel Armor", "Protective steel armor", lambda player: equip_armor(player, "Steel Armor", 10), 80),
- "Magic Scroll": Item("Magic Scroll", "A scroll with mysterious runes", lambda player: add_to_inventory(player, "Magic Scroll"), 100)
- }
- def create_quests():
- return [
- Quest("Goblin Slayer", "Defeat 5 Goblins", {"Goblin": 5}, {"exp": 50, "gold": 100}),
- Quest("Wolf Hunter", "Defeat 3 Wolves", {"Wolf": 3}, {"exp": 75, "gold": 150}),
- Quest("Orc Chieftain", "Defeat the Orc leader", {"Orc": 1}, {"exp": 100, "gold": 200}),
- ]
- def heal(player, amount):
- player.health = min(player.health + amount, player.max_health)
- print_slowly(f"You restored {amount} HP. Current HP: {player.health}/{player.max_health}")
- def buff_stat(player, stat, amount):
- if stat == "strength":
- player.strength += amount
- print_slowly(f"Your strength increased by {amount}. Current strength: {player.strength}")
- elif stat == "defense":
- player.defense += amount
- print_slowly(f"Your defense increased by {amount}. Current defense: {player.defense}")
- def equip_weapon(player, weapon_name, strength_bonus):
- player.strength += strength_bonus
- print_slowly(f"You equipped {weapon_name}. Strength increased by {strength_bonus}.")
- def equip_armor(player, armor_name, defense_bonus):
- player.defense += defense_bonus
- print_slowly(f"You equipped {armor_name}. Defense increased by {defense_bonus}.")
- def add_to_inventory(player, item_name):
- if item_name in player.inventory:
- player.inventory[item_name] += 1
- else:
- player.inventory[item_name] = 1
- print_slowly(f"{item_name} added to your inventory.")
- def level_up(player):
- player.level += 1
- player.max_health += 20
- player.health = player.max_health
- player.strength += 2
- player.defense += 1
- print_slowly(f"Congratulations! You've reached level {player.level}!")
- print_slowly(f"Your stats have increased:")
- print_slowly(f"Max Health: {player.max_health}")
- print_slowly(f"Strength: {player.strength}")
- print_slowly(f"Defense: {player.defense}")
- def check_level_up(player):
- exp_required = player.level * 100
- if player.exp >= exp_required:
- player.exp -= exp_required
- level_up(player)
- check_level_up(player)
- def explore(player, game_map, enemies, items):
- print_slowly(f"\n{player.name} is exploring {player.location}...")
- time.sleep(1)
- if random.random() < 0.6:
- enemy = random.choice([e for e in enemies if e.level <= player.level + 2])
- print_slowly(f"You encounter a level {enemy.level} {enemy.name}!")
- combat(player, enemy)
- elif random.random() < 0.3:
- item_name = random.choice(list(items.keys()))
- item = items[item_name]
- print_slowly(f"You found a {item.name}!")
- print_slowly(item.description)
- add_to_inventory(player, item.name)
- else:
- print_slowly("You find nothing of interest.")
- def combat(player, enemy):
- print_slowly(f"\nCombat with level {enemy.level} {enemy.name} begins!")
- while player.health > 0 and enemy.health > 0:
- print_slowly(f"\n{player.name}'s Health: {player.health}/{player.max_health}")
- print_slowly(f"{enemy.name}'s Health: {enemy.health}/{enemy.max_health}")
- action = input("Do you want to (A)ttack, (U)se item, or (R)un? ").lower()
- if action == 'a':
- damage = max(0, player.strength - enemy.level)
- enemy.health -= damage
- print_slowly(f"You deal {damage} damage to the {enemy.name}.")
- if enemy.health <= 0:
- print_slowly(f"You have defeated the {enemy.name}!")
- player.exp += enemy.exp_reward
- print_slowly(f"You gained {enemy.exp_reward} experience points.")
- check_level_up(player)
- update_quests(player, enemy.name)
- return
- player_damage = max(0, enemy.damage - player.defense)
- player.health -= player_damage
- print_slowly(f"The {enemy.name} deals {player_damage} damage to you.")
- elif action == 'u':
- use_item(player)
- elif action == 'r':
- if random.random() < 0.5:
- print_slowly("You successfully flee from the battle!")
- return
- else:
- print_slowly("You failed to escape!")
- player_damage = max(0, enemy.damage - player.defense)
- player.health -= player_damage
- print_slowly(f"The {enemy.name} deals {player_damage} damage to you.")
- else:
- print_slowly("Invalid action. You hesitate and lose your turn!")
- player_damage = max(0, enemy.damage - player.defense)
- player.health -= player_damage
- print_slowly(f"The {enemy.name} deals {player_damage} damage to you.")
- if player.health <= 0:
- print_slowly("You have been defeated. Game Over.")
- else:
- print_slowly(f"You have defeated the {enemy.name}!")
- def use_item(player):
- if not player.inventory:
- print_slowly("Your inventory is empty.")
- return
- print_slowly("Your inventory:")
- for item, count in player.inventory.items():
- print_slowly(f"{item}: {count}")
- item_choice = input("Enter the name of the item you want to use (or 'cancel'): ")
- if item_choice.lower() == 'cancel':
- return
- if item_choice in player.inventory and player.inventory[item_choice] > 0:
- item = items[item_choice]
- item.effect(player)
- player.inventory[item_choice] -= 1
- if player.inventory[item_choice] == 0:
- del player.inventory[item_choice]
- else:
- print_slowly("Invalid item or you don't have any of that item.")
- def update_quests(player, enemy_name):
- for quest in player.quests:
- if not quest.completed and enemy_name in quest.objective:
- quest.objective[enemy_name] -= 1
- if quest.objective[enemy_name] == 0:
- del quest.objective[enemy_name]
- if not quest.objective:
- quest.completed = True
- print_slowly(f"Quest completed: {quest.name}")
- player.exp += quest.reward["exp"]
- print_slowly(f"You gained {quest.reward['exp']} experience points.")
- check_level_up(player)
- # Add gold or other rewards here
- def show_quests(player):
- if not player.quests:
- print_slowly("You have no active quests.")
- return
- print_slowly("Your active quests:")
- for quest in player.quests:
- print_slowly(f"- {quest.name}: {quest.description}")
- if not quest.completed:
- for enemy, count in quest.objective.items():
- print_slowly(f" Defeat {count} {enemy}(s)")
- else:
- print_slowly(" Completed!")
- def travel(player, game_map):
- print_slowly(f"You are currently in {player.location}.")
- print_slowly("You can travel to:")
- for i, location in enumerate(game_map.locations[player.location], 1):
- print_slowly(f"{i}. {location}")
- choice = input("Enter the number of your destination (or 'cancel'): ")
- if choice.lower() == 'cancel':
- return
- try:
- new_location = game_map.locations[player.location][int(choice) - 1]
- player.location = new_location
- print_slowly(f"You have traveled to {new_location}.")
- except (ValueError, IndexError):
- print_slowly("Invalid choice. You stay where you are.")
- def save_game(player):
- save_data = {
- "name": player.name,
- "level": player.level,
- "exp": player.exp,
- "max_health": player.max_health,
- "health": player.health,
- "strength": player.strength,
- "defense": player.defense,
- "inventory": player.inventory,
- "location": player.location,
- "quests": [
- {
- "name": quest.name,
- "description": quest.description,
- "objective": quest.objective,
- "reward": quest.reward,
- "completed": quest.completed
- }
- for quest in player.quests
- ]
- }
- with open(f"{player.name}_save.json", "w") as f:
- json.dump(save_data, f)
- print_slowly("Game saved successfully.")
- def load_game():
- name = input("Enter the name of the saved game to load: ")
- try:
- with open(f"{name}_save.json", "r") as f:
- save_data = json.load(f)
- player = Player(save_data["name"])
- player.level = save_data["level"]
- player.exp = save_data["exp"]
- player.max_health = save_data["max_health"]
- player.health = save_data["health"]
- player.strength = save_data["strength"]
- player.defense = save_data["defense"]
- player.inventory = save_data["inventory"]
- player.location = save_data["location"]
- player.quests = [
- Quest(q["name"], q["description"], q["objective"], q["reward"])
- for q in save_data["quests"]
- ]
- for i, quest in enumerate(player.quests):
- quest.completed = save_data["quests"][i]["completed"]
- print_slowly("Game loaded successfully.")
- return player
- except FileNotFoundError:
- print_slowly("Save file not found. Starting a new game.")
- return None
- def main():
- print_slowly("Welcome to the Extended Text Adventure Game!")
- load_choice = input("Do you want to (N)ew Game or (L)oad Game? ").lower()
- if load_choice == 'l':
- player = load_game()
- if player is None:
- player_name = input("Enter your character's name: ")
- player = Player(player_name)
- game_map = Map()
- enemies = create_enemies()
- global items
- items = create_items()
- quests = create_quests()
- print_slowly(f"\nWelcome, {player.name}! Your adventure begins now.")
- while player.health > 0:
- print_slowly(f"\nLocation: {player.location}")
- print_slowly(f"Level: {player.level} | Exp: {player.exp}/{player.level * 100}")
- print_slowly(f"Health: {player.health}/{player.max_health}")
- print_slowly(f"Strength: {player.strength} | Defense: {player.defense}")
- action = input("\nWhat would you like to do? (E)xplore, (T)ravel, (R)est, (Q)uests, (I)nventory, (S)ave, or (Quit): ").lower()
- if action == 'e':
- explore(player, game_map, enemies, items)
- elif action == 't':
- travel(player, game_map)
- elif action == 'r':
- heal_amount = random.randint(10, 20)
- heal(player, heal_amount)
- elif action == 'q':
- show_quests(player)
- elif action == 'i':
- use_item(player)
- elif action == 's':
- save_game(player)
- elif action == 'quit':
- save_choice = input("Do you want to save before quitting? (Y/N): ").lower()
- if save_choice == 'y':
- save_game(player)
- print_slowly("Thank you for playing. Goodbye!")
- break
- else:
- print_slowly("Invalid action. Please try again.")
- if player.health <= 0:
- print_slowly("Game Over. Your adventure has come to an end.")
- if __name__ == "__main__":
- main()
- ```
- Would you like me to explain or break down this expanded code?
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement