
- Python - Home
- Python - Overview
- Python - History
- Python - Features
- Python vs C++
- Python - Hello World Program
- Python - Application Areas
- Python - Interpreter
- Python - Environment Setup
- Python - Virtual Environment
- Python - Basic Syntax
- Python - Variables
- Python - Data Types
- Python - Type Casting
- Python - Unicode System
- Python - Literals
- Python - Operators
- Python - Arithmetic Operators
- Python - Comparison Operators
- Python - Assignment Operators
- Python - Logical Operators
- Python - Bitwise Operators
- Python - Membership Operators
- Python - Identity Operators
- Python - Operator Precedence
- Python - Comments
- Python - User Input
- Python - Numbers
- Python - Booleans
- Python - Control Flow
- Python - Decision Making
- Python - If Statement
- Python - If else
- Python - Nested If
- Python - Match-Case Statement
- Python - Loops
- Python - for Loops
- Python - for-else Loops
- Python - While Loops
- Python - break Statement
- Python - continue Statement
- Python - pass Statement
- Python - Nested Loops
- Python Functions & Modules
- Python - Functions
- Python - Default Arguments
- Python - Keyword Arguments
- Python - Keyword-Only Arguments
- Python - Positional Arguments
- Python - Positional-Only Arguments
- Python - Arbitrary Arguments
- Python - Variables Scope
- Python - Function Annotations
- Python - Modules
- Python - Built in Functions
- Python Strings
- Python - Strings
- Python - Slicing Strings
- Python - Modify Strings
- Python - String Concatenation
- Python - String Formatting
- Python - Escape Characters
- Python - String Methods
- Python - String Exercises
- Python Lists
- Python - Lists
- Python - Access List Items
- Python - Change List Items
- Python - Add List Items
- Python - Remove List Items
- Python - Loop Lists
- Python - List Comprehension
- Python - Sort Lists
- Python - Copy Lists
- Python - Join Lists
- Python - List Methods
- Python - List Exercises
- Python Tuples
- Python - Tuples
- Python - Access Tuple Items
- Python - Update Tuples
- Python - Unpack Tuples
- Python - Loop Tuples
- Python - Join Tuples
- Python - Tuple Methods
- Python - Tuple Exercises
- Python Sets
- Python - Sets
- Python - Access Set Items
- Python - Add Set Items
- Python - Remove Set Items
- Python - Loop Sets
- Python - Join Sets
- Python - Copy Sets
- Python - Set Operators
- Python - Set Methods
- Python - Set Exercises
- Python Dictionaries
- Python - Dictionaries
- Python - Access Dictionary Items
- Python - Change Dictionary Items
- Python - Add Dictionary Items
- Python - Remove Dictionary Items
- Python - Dictionary View Objects
- Python - Loop Dictionaries
- Python - Copy Dictionaries
- Python - Nested Dictionaries
- Python - Dictionary Methods
- Python - Dictionary Exercises
- Python Arrays
- Python - Arrays
- Python - Access Array Items
- Python - Add Array Items
- Python - Remove Array Items
- Python - Loop Arrays
- Python - Copy Arrays
- Python - Reverse Arrays
- Python - Sort Arrays
- Python - Join Arrays
- Python - Array Methods
- Python - Array Exercises
- Python File Handling
- Python - File Handling
- Python - Write to File
- Python - Read Files
- Python - Renaming and Deleting Files
- Python - Directories
- Python - File Methods
- Python - OS File/Directory Methods
- Python - OS Path Methods
- Object Oriented Programming
- Python - OOPs Concepts
- Python - Classes & Objects
- Python - Class Attributes
- Python - Class Methods
- Python - Static Methods
- Python - Constructors
- Python - Access Modifiers
- Python - Inheritance
- Python - Polymorphism
- Python - Method Overriding
- Python - Method Overloading
- Python - Dynamic Binding
- Python - Dynamic Typing
- Python - Abstraction
- Python - Encapsulation
- Python - Interfaces
- Python - Packages
- Python - Inner Classes
- Python - Anonymous Class and Objects
- Python - Singleton Class
- Python - Wrapper Classes
- Python - Enums
- Python - Reflection
- Python Errors & Exceptions
- Python - Syntax Errors
- Python - Exceptions
- Python - try-except Block
- Python - try-finally Block
- Python - Raising Exceptions
- Python - Exception Chaining
- Python - Nested try Block
- Python - User-defined Exception
- Python - Logging
- Python - Assertions
- Python - Built-in Exceptions
- Python Multithreading
- Python - Multithreading
- Python - Thread Life Cycle
- Python - Creating a Thread
- Python - Starting a Thread
- Python - Joining Threads
- Python - Naming Thread
- Python - Thread Scheduling
- Python - Thread Pools
- Python - Main Thread
- Python - Thread Priority
- Python - Daemon Threads
- Python - Synchronizing Threads
- Python Synchronization
- Python - Inter-thread Communication
- Python - Thread Deadlock
- Python - Interrupting a Thread
- Python Networking
- Python - Networking
- Python - Socket Programming
- Python - URL Processing
- Python - Generics
- Python Libraries
- NumPy Tutorial
- Pandas Tutorial
- SciPy Tutorial
- Matplotlib Tutorial
- Django Tutorial
- OpenCV Tutorial
- Python Miscellenous
- Python - Date & Time
- Python - Maths
- Python - Iterators
- Python - Generators
- Python - Closures
- Python - Decorators
- Python - Recursion
- Python - Reg Expressions
- Python - PIP
- Python - Database Access
- Python - Weak References
- Python - Serialization
- Python - Templating
- Python - Output Formatting
- Python - Performance Measurement
- Python - Data Compression
- Python - CGI Programming
- Python - XML Processing
- Python - GUI Programming
- Python - Command-Line Arguments
- Python - Docstrings
- Python - JSON
- Python - Sending Email
- Python - Further Extensions
- Python - Tools/Utilities
- Python - GUIs
- Python Advanced Concepts
- Python - Abstract Base Classes
- Python - Custom Exceptions
- Python - Higher Order Functions
- Python - Object Internals
- Python - Memory Management
- Python - Metaclasses
- Python - Metaprogramming with Metaclasses
- Python - Mocking and Stubbing
- Python - Monkey Patching
- Python - Signal Handling
- Python - Type Hints
- Python - Automation Tutorial
- Python - Humanize Package
- Python - Context Managers
- Python - Coroutines
- Python - Descriptors
- Python - Diagnosing and Fixing Memory Leaks
- Python - Immutable Data Structures
- Python Useful Resources
- Python - Questions & Answers
- Python - Interview Questions & Answers
- Python - Online Quiz
- Python - Quick Guide
- Python - Reference
- Python - Cheatsheet
- Python - Projects
- Python - Useful Resources
- Python - Discussion
- Python Compiler
- NumPy Compiler
- Matplotlib Compiler
- SciPy Compiler
Python - Text-Based Adventure Game using pygame
The act of developing a simple text adventure game is a great method for teaching the fundamentals of Python especially when it is designed with the use of pygame library.
This tutorial will contain the detailed step by step instructions on how to build a game that includes searching for the key in one of the rooms and opening the door to the library. In this tutorial you will learn about the installation of pygame, explanation of every step of the code and the way to run the game with the output.
Installations
First, check Whether you have Python installed on your computer or not. This is where pygame comes into play which is an open source of game and multimedia development for Python.
To install pygame, you have to open the cmd or the terminal on your computer and type in the following instruction −
pip install pygame
Code for Text-Based Adventure Game
Below is the complete code for our text-based adventure game. The game consists of several rooms: a Hall, Garden, Dining Room, and Library. The player can visit two rooms in an attempt to find a hidden key. If they find the key, they can access the library room. The game ends if the player fails to find the key within the allowed number of attempts.
import pygame import sys import random # Initialize pygame pygame.init() # Set up the display width, height = 800, 600 screen = pygame.display.set_mode((width, height)) pygame.display.set_caption('Text Adventure Game') # Define colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) # Set up fonts font = pygame.font.Font(None, 36) # Load images for different rooms room_images = { 'Start': pygame.Surface((width, height)), 'Hall': pygame.transform.scale(pygame.image.load('hall.png'), (width, height)), 'Garden': pygame.transform.scale(pygame.image.load('garden.png'), (width, height)), 'Dining Room': pygame.transform.scale(pygame.image.load('dining_room.png'), (width, height)), 'Library': pygame.transform.scale(pygame.image.load('library.png'), (width, height)), 'Game': pygame.Surface((width, height)) # Blank surface for the Game screen } # Fill the blank surface with black room_images['Game'].fill(BLACK) # Define room choices and chances room_choices = ['Hall', 'Garden', 'Dining Room'] key_room = random.choice(room_choices) # Randomly select which room contains the key chances_left = 2 # Define starting state current_screen = 'Start' current_room = None found_key = False # Define a function to draw the screen def draw_screen(screen_name): screen.blit(room_images[screen_name], (0, 0)) if screen_name == 'Start': start_text = font.render('WELCOME TO THE GAME', True, WHITE) instructions_text = font.render('LOOK: You have only two chances to access the Library room.', True, WHITE) start_button_text = font.render('Start', True, BLACK) exit_button_text = font.render('Exit', True, BLACK) screen.blit(start_text, (20, 20)) screen.blit(instructions_text, (20, 60)) pygame.draw.rect(screen, WHITE, pygame.Rect(300, 200, 200, 50)) screen.blit(start_button_text, (375, 215)) pygame.draw.rect(screen, WHITE, pygame.Rect(300, 300, 200, 50)) screen.blit(exit_button_text, (375, 315)) elif screen_name == 'Game': if current_room: screen.blit(room_images[current_room], (0, 0)) game_text = font.render(f'You have {chances_left} chances left to find the key.', True, WHITE) screen.blit(game_text, (20, 20)) if found_key: key_found_text = font.render('You successfully found the key! Now you can go to the Library room.', True, WHITE) screen.blit(key_found_text, (20, 60)) # Draw the navigation buttons for room, rect in button_rects.items(): if room in room_choices or room == 'Library': pygame.draw.rect(screen, WHITE, rect) text_surface = font.render(button_texts[room], True, BLACK) screen.blit(text_surface, (rect.x + 10, rect.y + 10)) elif screen_name == 'Library': screen.blit(room_images['Library'], (0, 0)) library_text = font.render('Welcome to the Library!', True, WHITE) screen.blit(library_text, (20, 20)) # Define buttons for navigation and initial screen button_rects = { 'Start': pygame.Rect(300, 200, 200, 50), 'Exit': pygame.Rect(300, 300, 200, 50), 'Hall': pygame.Rect(50, 500, 150, 50), 'Garden': pygame.Rect(225, 500, 150, 50), 'Dining Room': pygame.Rect(400, 500, 150, 50), 'Library': pygame.Rect(575, 500, 150, 50), } # Define button text button_texts = { 'Start': 'Start', 'Exit': 'Exit', 'Hall': 'Go to Hall', 'Garden': 'Go to Garden', 'Dining Room': 'Go to Dining Room', 'Library': 'Go to Library', } # Main loop running = True while running: # Clear the screen screen.fill(BLACK) # Draw the current screen draw_screen(current_screen) # Event handling for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: running = False elif event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: # Left mouse button if current_screen == 'Start': if button_rects['Start'].collidepoint(event.pos): current_screen = 'Game' elif button_rects['Exit'].collidepoint(event.pos): running = False elif current_screen == 'Game': for room, rect in button_rects.items(): if rect.collidepoint(event.pos): if room in room_choices: current_room = room if room == key_room: found_key = True else: chances_left -= 1 if chances_left <= 0 and not found_key: current_screen = 'Start' # Game over if no chances left elif room == 'Library': if found_key: current_screen = 'Library' else: current_screen = 'Game' # Can't access Library without the key # Update the display pygame.display.flip() # Quit pygame pygame.quit() sys.exit()
Images Used
The following are the images that we used in the above code to design the text-based adventure game −


Those are the images we used. You can also download random image from Google and used them.
Steps to Run the Game
- Set Up − First esure that you have Python installed along with Pygame.
- Prepare Images − Place the required room images (hall.png, garden.png, dining_room.png, and library.png) in the same directory as your Python script.
- Run the Script − Execute the script by running python your_script_name.py in your terminal or command prompt.
Output Screenshots
1. Initial Screen
The game starts with a screen giving you the option to 'Start' or 'Exit'.

2. Game Play
After clicking 'Start', you will be taken to the gameplay screen, where you can choose rooms to search for the key.

You can go any room if you want from hall, garden dining, go as your wish. We click hall room −

3. Key Found
If you find the key, a message will appear at the top, indicating that you can now access the library.
4. Library Access
After finding the key, click the 'Library' room to access it and complete the game.
