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 −

Images Images

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'.

Screenshots

2. Game Play

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

Screenshots

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

Screenshots

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.

Screenshots
python_projects_from_basic_to_advanced.htm
Advertisements