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
廣告