Okay, here's a Python-based text adventure game I've coded, called "The Lost Artifact of Xylos". It's a bit more involved than a simple "guess the number" game, aiming for a small, branching narrative with some inventory management and basic puzzle elements. I've included comments to explain the code.
import time
def slow_print(text, delay=0.03):
"""Prints text character by character with a delay."""
for char in text:
print(char, end='', flush=True)
time.sleep(delay)
print() # Newline at the end
def get_player_choice(options):
"""Gets player input and validates it against a list of options."""
while True:
print("\nWhat do you do?")
for i, option in enumerate(options):
print(f"{i+1}. {option}")
choice = input("> ")
try:
choice = int(choice)
if 1 <= choice <= len(options):
return choice - 1 # Return index
else:
print("Invalid choice. Please enter a number between 1 and", len(options))
except ValueError:
print("Invalid input. Please enter a number.")
def intro():
"""Introduction to the game."""
slow_print("You are Alex, a seasoned archaeologist. You've dedicated your life to uncovering lost civilizations.")
slow_print("Your latest expedition has led you to the remote island of Xylos, rumored to hold the legendary Artifact of Xylos - a source of immense power.")
slow_print("After weeks of searching, you've finally located the entrance to an ancient temple, hidden behind a waterfall.")
slow_print("The air is thick with humidity and the scent of decay. You take a deep breath and step inside...")
return "temple_entrance"
def temple_entrance():
"""The first location in the game."""
slow_print("\nYou stand in a large, crumbling chamber. Water drips from the ceiling, and strange symbols adorn the walls.")
slow_print("There are three paths ahead:")
slow_print("1. A dark, narrow passage to the left.")
slow_print("2. A grand, but blocked, doorway straight ahead.")
slow_print("3. A winding staircase leading upwards to the right.")
options = ["Go left", "Examine the doorway", "Go up the staircase"]
choice = get_player_choice(options)
if choice == 0:
return "dark_passage"
elif choice == 1:
return "blocked_doorway"
elif choice == 2:
return "winding_staircase"
def dark_passage():
"""A dangerous passage."""
slow_print("\nYou cautiously enter the dark passage. The air is stale and claustrophobic.")
slow_print("Suddenly, you hear a rustling sound! A giant spider descends from the ceiling!")
options = ["Fight the spider", "Try to sneak past"]
choice = get_player_choice(options)
if choice == 0:
slow_print("\nYou bravely fight the spider! After a fierce struggle, you defeat it, but suffer a minor injury.")
slow_print("You find a small, rusty key clutched in the spider's legs.")
player_inventory["key"] = True
return "temple_entrance" # Return to the main chamber
elif choice == 1:
slow_print("\nYou attempt to sneak past the spider, but it spots you! It attacks, and you are forced to retreat.")
return "temple_entrance"
def blocked_doorway():
"""A doorway blocked by rubble."""
slow_print("\nYou examine the doorway. It's blocked by a massive pile of rubble.")
slow_print("You notice a small keyhole hidden amongst the stones.")
if player_inventory.get("key"):
slow_print("\nYou use the rusty key you found to unlock a hidden mechanism. The rubble slowly shifts, revealing a passage!")
return "treasure_chamber"
else:
slow_print("\nYou need a key to unlock the mechanism.")
return "temple_entrance"
def winding_staircase():
"""A staircase leading upwards."""
slow_print("\nYou ascend the winding staircase. It's a long climb, and your legs begin to ache.")
slow_print("You reach a small platform overlooking the main chamber. You see a pressure plate on the floor.")
options = ["Step on the pressure plate", "Ignore the pressure plate and continue upwards"]
choice = get_player_choice(options)
if choice == 0:
slow_print("\nYou step on the pressure plate. A section of the wall slides open, revealing a hidden alcove!")
slow_print("Inside, you find a map!")
player_inventory["map"] = True
return "winding_staircase_alcove"
elif choice == 1:
slow_print("\nYou continue upwards, ignoring the pressure plate. The staircase leads to a dead end.")
return "winding_staircase"
def winding_staircase_alcove():
slow_print("\nYou examine the map. It shows a secret passage behind the waterfall outside the temple.")
slow_print("The map also indicates a hidden chamber within the temple, accessible only by solving a riddle.")
return "temple_entrance"
def treasure_chamber():
"""The final chamber."""
slow_print("\nYou enter a magnificent treasure chamber! Gold and jewels glitter in the torchlight.")
slow_print("In the center of the room, resting on a pedestal, is the Artifact of Xylos - a glowing crystal orb.")
slow_print("You have found it! Your expedition was a success!")
return "win"
def win():
"""The winning state."""
slow_print("\nCongratulations! You have successfully retrieved the Artifact of Xylos!")
slow_print("Your name will be etched in the annals of archaeological history!")
return "end"
# Game setup
player_inventory = {} # Dictionary to store items
current_location = intro()
# Game loop
while current_location != "end":
if current_location == "temple_entrance":
current_location = temple_entrance()
elif current_location == "dark_passage":
current_location = dark_passage()
elif current_location == "blocked_doorway":
current_location = blocked_doorway()
elif current_location == "winding_staircase":
current_location = winding_staircase()
elif current_location == "winding_staircase_alcove":
current_location = winding_staircase_alcove()
elif current_location == "treasure_chamber":
current_location = treasure_chamber()
elif current_location == "win":
current_location = win()
else:
slow_print("Error: Unknown location.")
current_location = "end"
slow_print("\nThanks for playing!")
Key improvements and explanations:
slow_print() function: This adds a dramatic effect by printing text slowly, character by character. It makes the game feel more immersive.
get_player_choice() function: This function handles player input, validates it to ensure it's a valid number within the available options, and returns the index of the chosen option. This makes the code cleaner and easier to maintain.
- Location Functions: Each location in the game is now a separate function (e.g.,
temple_entrance(), dark_passage()). This makes the code much more organized and easier to expand.
- Inventory System: The
player_inventory dictionary stores items the player has collected. The blocked_doorway() function checks if the player has the key before allowing them to proceed. The get() method is used to safely check for the key without causing an error if it's not present.
- Branching Narrative: The game has multiple paths and choices, leading to different outcomes.
- Win Condition: The
treasure_chamber() and win() functions represent the successful completion of the game.
- Game Loop: The
while loop keeps the game running until the player reaches the "end" state.
- Error Handling: A basic error check is included in the game loop to handle unknown locations.
- Comments: I've added comments throughout the code to explain what each part does.
- Map and Riddle Hint: The winding staircase now leads to a map that hints at a secret passage and a riddle. This adds more depth to the game.
How to play:
- Save the code: Save the code as a
.py file (e.g., xylos_adventure.py).
- Run the code: Open a terminal or command prompt, navigate to the directory where you saved the file, and run it using
python xylos_adventure.py.
- Follow the prompts: Read the descriptions and choose your actions by entering the corresponding number.
This is a starting point. Here are some ideas for expanding the game:
- More complex puzzles: Add more challenging puzzles that require the player to use items in their inventory or solve riddles.
- Combat system: Develop a more detailed combat system with different weapons, enemies, and stats.
- More locations: Add more rooms and areas to explore.
- Non-player characters (NPCs): Introduce characters that the player can interact with.
- Story development: Expand the story and add more background information about the island of Xylos and the Artifact.
- Saving and loading: Allow the player to save their progress and load it later.
- Graphical interface: Instead of a text-based interface, you could use a library like Pygame to create a graphical interface.
This example demonstrates a more complete game structure than a simple number-guessing game. It's a good foundation for building a more complex and engaging text adventure. Let me know if you'd like me to elaborate on any of these expansion ideas or help you implement them!