Python Creative Project: Build a Text-Based Adventure Game Your task is to create a…
- User
Python Creative Project: Build a Text-Based Adventure Game
Your task is to create a simple text-based adventure game in Python. The game should:
- Have at least 3 different rooms/locations the player can navigate between
- Include items that can be picked up and used
- Feature at least one puzzle or challenge the player must solve
- Track the player's inventory and status
- Have a clear win condition
Be creative with your theme and story! Implementation should demonstrate:
- Object-oriented programming concepts
- Game state management
- User input handling
- Conditional logic for game progression
You can use only the standard library (no external dependencies required).
Assistant
import sys import time import textwrap # --- Helper Functions --- def print_slow(text, delay=0.03): """Prints text character by character for a typewriter effect.""" for char in textwrap.fill(text, width=80): # Wrap text nicely print(char, end='', flush=True) time.sleep(delay) print() # Newline at the end def get_input(prompt="> "): """Gets standardized user input.""" return input(prompt).strip().lower() # --- Game Objects --- class Item: """Represents an item in the game.""" def __init__(self, name, description, can_pickup=True): self.name = name self.description = description self.can_pickup = can_pickup def __str__(self): return self.name class Room: """Represents a location in the game.""" def __init__(self, name, description): self.name = name self.description = description self.exits = {} # {direction: room_object} self.items = {} # {item_name: item_object} self.features = {} # {feature_name: description_or_callable} self.visited = False def add_exit(self, direction, room): """Adds an exit to another room.""" self.exits[direction.lower()] = room def add_item(self, item): """Adds an item to the room.""" self.items[item.name.lower()] = item def remove_item(self, item_name): """Removes an item from the room.""" if item_name.lower() in self.items: return self.items.pop(item_name.lower()) return None def add_feature(self, name, description_or_callable): """Adds an examinable feature to the room.""" self.features[name.lower()] = description_or_callable def describe(self): """Prints the full description of the room.""" print_slow(f"\n--- {self.name} ---") if not self.visited: print_slow(self.description) self.visited = True else: print_slow(f"You are back in the {self.name}.") # Show items if self.items: print_slow("You see here:") for item_name in self.items: print_slow(f"- {item_name.capitalize()}") else: print_slow("The room seems empty of loose items.") # Show features if self.features: print_slow("Notable features:") for feature_name in self.features: print_slow(f"- {feature_name.capitalize()}") # Show exits if self.exits: print_slow("Available exits:") for direction in self.exits: print_slow(f"- {direction.capitalize()}") else: print_slow("There are no obvious exits.") def get_exit(self, direction): """Returns the room object for a given direction, or None.""" return self.exits.get(direction.lower()) def examine_feature(self, feature_name): """Examines a feature in the room.""" feature = self.features.get(feature_name.lower()) if feature: if callable(feature): # If the feature has special logic feature() else: print_slow(feature) else: print_slow(f"You don't see anything special about the {feature_name}.") class Player: """Represents the player.""" def __init__(self, start_room): self.current_room = start_room self.inventory = {} # {item_name: item_object} self.has_light = False # Example status def move(self, direction): """Moves the player to a different room.""" next_room = self.current_room.get_exit(direction) if next_room: # --- Room Specific Logic Example --- if next_room.name == "Dark Cave" and not self.has_light: print_slow("You try to enter the cave, but it's pitch black. You need a light source.") return False # Movement failed self.current_room = next_room self.current_room.describe() return True else: print_slow("You can't go that way.") return False def take_item(self, item_name): """Takes an item from the current room.""" item = self.current_room.remove_item(item_name) if item: if item.can_pickup: self.inventory[item.name.lower()] = item print_slow(f"You picked up the {item.name}.") # --- Item Specific Logic Example --- if item.name.lower() == "lantern": print_slow("Its wick looks usable. Maybe you can light it?") else: print_slow(f"You can't pick up the {item.name}.") # Put it back if it can't be picked up self.current_room.add_item(item) else: print_slow(f"You don't see a {item_name} here.") def use_item(self, item_name, target_name=None): """Uses an item from the inventory.""" item = self.inventory.get(item_name.lower()) if not item: print_slow(f"You don't have a {item_name}.") return # --- Specific Item Usage Logic --- if item.name.lower() == "lantern": if not self.has_light: print_slow("You successfully light the lantern! Its warm glow pushes back the shadows.") self.has_light = True else: print_slow("The lantern is already lit.") elif item.name.lower() == "strange key": if self.current_room.name == "Ancient Study" and target_name == "ornate door": print_slow("You insert the Strange Key into the lock of the Ornate Door. With a satisfying *click*, it unlocks!") # --- WIN CONDITION MET --- game.win_game() elif target_name: print_slow(f"You can't use the {item_name} on the {target_name}.") else: print_slow(f"Where do you want to use the {item_name}?") elif item.name.lower() == "crumpled note": print_slow("You smooth out the Crumpled Note. It reads: 'Four legs in the morning, two at noon, three in the evening. What am I?'") else: print_slow(f"You can't figure out how to use the {item.name} right now.") def examine(self, target_name): """Examines an item in inventory or a feature in the room.""" # Check inventory first item = self.inventory.get(target_name.lower()) if item: print_slow(item.description) # Special examine text for items? if item.name.lower() == "crumpled note": print_slow("Maybe you should try 'use note' to read it properly.") return # Check items in the room item_in_room = self.current_room.items.get(target_name.lower()) if item_in_room: print_slow(item_in_room.description) return # Check features in the room if target_name.lower() in self.current_room.features: self.current_room.examine_feature(target_name) return print_slow(f"You don't see anything special about '{target_name}'.") def show_inventory(self): """Displays the player's inventory.""" if not self.inventory: print_slow("Your inventory is empty.") else: print_slow("\nYou are carrying:") for item_name in self.inventory: print_slow(f"- {item_name.capitalize()}") # --- Game Class --- class Game: """Manages the game state and main loop.""" def __init__(self): self.player = None self.rooms = {} self.is_over = False self.riddle_solved = False # Puzzle state def setup(self): """Creates rooms, items, and the player.""" # Create Items lantern = Item("Lantern", "An old, brass lantern. It seems sturdy but lacks fuel.", True) note = Item("Crumpled Note", "A piece of parchment, tightly crumpled.", True) key = Item("Strange Key", "A heavy iron key with intricate carvings. It feels important.", False) # Cannot be picked up initially sphinx_statue = Item("Sphinx Statue", "A stone statue of a sphinx. Its eyes seem to follow you.", False) # Not pickupable # Create Rooms cell = Room("Dusty Cell", "You are in a small, dusty cell. Cobwebs hang thick in the corners. A single wooden door leads north.") hallway = Room("Echoing Hallway", "A long hallway stretches before you, east and west. The air is damp and cool. You hear a faint dripping sound.") cave = Room("Dark Cave", "It's pitch black inside. You can't see a thing without a light source.") study = Room("Ancient Study", "This room is filled with bookshelves lining the walls, covered in dust. A large wooden desk sits in the center. An ornate door is set into the south wall.") # Add items to rooms cell.add_item(note) hallway.add_item(lantern) cave.add_item(sphinx_statue) # The puzzle holder # Link rooms cell.add_exit("north", hallway) hallway.add_exit("south", cell) hallway.add_exit("west", cave) hallway.add_exit("east", study) cave.add_exit("east", hallway) study.add_exit("west", hallway) # The Ornate Door in the study is the exit, handled by 'use key' # Add features study.add_feature("bookshelves", "Mostly filled with crumbling tomes on forgotten lore. Nothing seems immediately useful.") study.add_feature("wooden desk", "A large, imposing desk. The drawers are locked or stuck.") study.add_feature("ornate door", "A heavy wooden door reinforced with iron bands. It has a large, complex lock.") # Puzzle feature in the cave def examine_sphinx(): if not self.player.has_light: print_slow("You reach out in the darkness and feel cold stone... something large.") return print_slow(sphinx_statue.description) if not self.riddle_solved: print_slow("The sphinx speaks, its voice like grinding stones: 'Answer my riddle, seeker, and gain a reward. Fail, and remain lost.'") print_slow("'What has four legs in the morning, two at noon, and three in the evening?'") elif key.name.lower() not in self.player.inventory and key.name.lower() not in cave.items: print_slow("The sphinx remains silent, but you notice a compartment opening at its base!") cave.add_item(key) # Key appears after solving cave.items[key.name.lower()].can_pickup = True # Make it pickupable print_slow(f"A {key.name} is revealed!") else: print_slow("The sphinx remains silent, its riddle already answered.") cave.add_feature("sphinx statue", examine_sphinx) cave.add_feature("sphinx", examine_sphinx) # Allow examining 'sphinx' too # Store rooms self.rooms = { "Dusty Cell": cell, "Echoing Hallway": hallway, "Dark Cave": cave, "Ancient Study": study } # Create Player self.player = Player(cell) def display_help(self): """Prints available commands.""" print_slow("\nAvailable Commands:") print_slow("- go [north, south, east, west]") print_slow("- look / l (describe the current room)") print_slow("- examine [item/feature]") print_slow("- take [item]") print_slow("- use [item] / use [item] on [target]") print_slow("- inventory / inv / i") print_slow("- answer [riddle answer] (when prompted)") print_slow("- help / h") print_slow("- quit / q") def handle_input(self, user_input): """Parses user input and executes the command.""" parts = user_input.split(maxsplit=2) verb = parts[0] if parts else "" noun1 = parts[1] if len(parts) > 1 else None noun2 = parts[2] if len(parts) > 2 else None # For "use item on target" if verb in ["quit", "q"]: self.is_over = True print_slow("Quitting game. Goodbye!") elif verb in ["help", "h"]: self.display_help() elif verb in ["look", "l"]: self.player.current_room.describe() elif verb in ["inventory", "inv", "i"]: self.player.show_inventory() elif verb == "go": if noun1: self.player.move(noun1) else: print_slow("Go where? (e.g., go north)") elif verb == "take": if noun1: self.player.take_item(noun1) else: print_slow("Take what?") elif verb == "use": if noun1: target = None # Check for "use item on target" format if noun2 and len(parts) > 2 and parts[1] == "on": # Incorrect split, maybe 'use lantern on darkness'? Let's simplify print_slow("Try 'use [item]' or 'use [item] on [feature/object]'.") return elif noun2: # This assumes "use item target" like "use key door" target = noun2 elif len(noun1.split()) > 1 and " on " in noun1: # Handles "use key on door" item_name, target_name = noun1.split(" on ", 1) self.player.use_item(item_name, target_name) return # Handled the 'on' case # Simple "use item" or "use item target" self.player.use_item(noun1, target) else: print_slow("Use what?") elif verb == "examine": if noun1: self.player.examine(noun1) else: print_slow("Examine what?") # --- Puzzle Specific Command --- elif verb == "answer": if self.player.current_room.name == "Dark Cave" and "sphinx statue" in self.player.current_room.features and not self.riddle_solved: if noun1 and noun1 == "man": # The answer to the riddle print_slow("The sphinx nods slowly. 'Correct.' A low grinding sound echoes as a hidden compartment opens at its base.") self.riddle_solved = True # The key will appear when the sphinx is examined again self.player.current_room.examine_feature("sphinx statue") elif noun1: print_slow(f"The sphinx stares blankly. '{noun1.capitalize()}...' it rumbles, 'Incorrect.'") else: print_slow("Answer with what?") else: print_slow("There's nothing here asking for an answer right now.") else: print_slow("I don't understand that command. Try 'help'.") def win_game(self): """Handles the win condition.""" print_slow("\n******************************************************") print_slow("With the door unlocked, you push it open. Fresh air and sunlight stream in!") print_slow("You've escaped the ancient ruins!") print_slow("Congratulations, you win!") print_slow("******************************************************") self.is_over = True def start(self): """Starts the main game loop.""" self.setup() print_slow("Welcome to The Forgotten Crypt!") print_slow("--------------------------------") print_slow("(Type 'help' for commands)") self.player.current_room.describe() while not self.is_over: try: command = get_input() if command: # Ignore empty input self.handle_input(command) # Win condition is checked within handle_input (use key on door) except (EOFError, KeyboardInterrupt): print_slow("\nInterrupting game. Goodbye!") self.is_over = True except Exception as e: print_slow(f"\nAn unexpected error occurred: {e}") print_slow("It might be a bug! Please report it.") # Optionally log the error here self.is_over = True # Stop game on unexpected error # --- Main Execution --- if __name__ == "__main__": game = Game() game.start()How to Play:
- Save the code as a Python file (e.g.,
adventure.py). - Run it from your terminal:
python adventure.py - Follow the prompts and type commands like:
lookgo northtake crumpled noteinventoryexamine note(oruse note)go westtake lanternuse lanternexamine sphinx statueanswer manexamine sphinx statue(again, to see the key appear)take strange keygo east(back to hallway)go east(to study)examine ornate dooruse strange key on ornate door
Explanation and Features:
-
OOP Concepts:
Room,Item,Player, andGameclasses encapsulate data and behavior.- Rooms hold items, exits, and features.
- The Player holds inventory and current location.
- The Game class manages the overall state and game loop.
-
Rooms (4 total):
- Dusty Cell (Start)
- Echoing Hallway (Hub)
- Dark Cave (Requires light, contains puzzle)
- Ancient Study (Contains exit door)
-
Items:
Crumpled Note: Provides the riddle text when used/examined.Lantern: Can be taken and used to light the Dark Cave (player.has_lightstatus).Strange Key: Reward for the puzzle, needed to unlock the exit door. Initially not pickupable.Sphinx Statue: A non-pickupable item acting as the puzzle interface.
-
Puzzle/Challenge:
- The
Dark Caveis initially inaccessible without light (use lanternrequired). - Inside the cave, examining the
Sphinx Statuepresents a classic riddle. - The player must use the
answer [solution]command (solution: "man"). - Solving the riddle makes the
Strange Keyappear (by adding it to the room's items) and become pickupable.
- The
-
Inventory and Status:
Player.inventory(a dictionary) tracks items.Player.has_light(a boolean) tracks whether the lantern is lit, affecting movement into the Dark Cave.
-
Win Condition:
- The player must solve the riddle, get the
Strange Key, go to theAncient Study, and use the commanduse strange key on ornate door. This triggers thegame.win_game()method.
- The player must solve the riddle, get the
-
Game State Management:
- The
Gameclass holds references to all rooms and the player. - The
Player.current_roomattribute tracks the player's location. - Room items change as the player takes them.
- Puzzle state (
game.riddle_solved) tracks progress. game.is_overcontrols the main loop.
- The
-
User Input Handling:
get_input()normalizes input (lowercase, stripped whitespace).handle_input()parses commands usingsplit()and directs actions usingif/elif/else. It handles simple verbs, verb+noun, and "use item on target".
-
Standard Library Only: Uses
sys,time, andtextwrap, all part of Python's standard library.time.sleepis used inprint_slowfor effect.textwraphelps format descriptions neatly.
- Save the code as a Python file (e.g.,
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.