Python - 基于文本的冒险游戏(使用 pygame)



开发一个简单的文本冒险游戏是教授 Python 基础知识的好方法,尤其是在使用 pygame 库设计时。

本教程将包含有关如何构建游戏的详细分步说明,其中包括在一个房间中搜索钥匙并打开图书馆门的步骤。在本教程中,您将学习有关 pygame 的安装、代码每个步骤的解释以及如何运行游戏及其输出的方法。

安装

首先,检查您的计算机上是否安装了 Python。这就是 **pygame** 发挥作用的地方,它是 Python 的一个开源游戏和多媒体开发库。

要安装 **pygame**,您需要在计算机上打开 cmd 或终端,然后输入以下指令:

pip install pygame

基于文本的冒险游戏的代码

以下是我们基于文本的冒险游戏的完整代码。游戏包含几个房间:大厅、花园、餐厅和图书馆。玩家可以访问两个房间以尝试找到隐藏的钥匙。如果他们找到钥匙,他们就可以进入图书馆房间。如果玩家在允许的尝试次数内未能找到钥匙,游戏将结束。

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 Images

这些是我们使用的图片。您也可以从 Google 下载随机图片并使用它们。

运行游戏的步骤

  • **设置** - 首先确保您已安装 Python 以及 Pygame。
  • **准备图片** - 将所需的房间图片(hall.png、garden.png、dining_room.png 和 library.png)放在与 Python 脚本相同的目录中。
  • **运行脚本** - 通过在您的终端或命令提示符中运行 python your_script_name.py 来执行脚本。

输出截图

1. 初始屏幕

游戏开始时会显示一个屏幕,提供“开始”或“退出”选项。

Screenshots

2. 游戏玩法

点击“开始”后,您将进入游戏画面,在这里您可以选择房间以搜索钥匙。

Screenshots

您可以随意前往大厅、花园、餐厅等任何房间。我们点击大厅房间:

Screenshots

3. 找到钥匙

如果您找到钥匙,顶部会出现一条消息,指示您现在可以进入图书馆。

4. 访问图书馆

找到钥匙后,点击“图书馆”房间以访问它并完成游戏。

Screenshots
python_projects_from_basic_to_advanced.htm
广告

© . All rights reserved.