使用 Pygame 模組在 Python 中構建簡單的遊戲
Pygame 是一款優秀的用於遊戲開發的庫,因為它包含各種內建工具和函式,可以用來建立各種型別的遊戲,從簡單的到複雜的。該庫包含圖形、聲音和輸入處理,所有這些對於任何遊戲都是必需的。
建立和修改精靈是 Pygame 最突出的功能之一。精靈是圖形物件,用於表示遊戲中的角色、物件和其他遊戲功能。Pygame 包含一個強大的精靈類,允許開發人員將圖形和動畫整合到遊戲中,移動和旋轉精靈,並檢測它們之間的碰撞。
Pygame 的另一個重要方面是碰撞檢測,它允許開發人員識別兩個遊戲物件何時發生碰撞。在遊戲中,這至關重要,因為它允許使用者與環境和其他遊戲元素進行互動。Pygame 包含一個碰撞檢測機制,用於檢測精靈和其他遊戲元素之間的碰撞。
除了精靈和碰撞檢測之外,Pygame 還包含聲音和音樂功能。這使得開發人員可以輕鬆地將音效和音樂融入他們的遊戲中,這可以極大地增強遊戲體驗。
總的來說,Pygame 是一款強大且適應性強的工具包,可用於構建各種遊戲和多媒體應用程式。它擁有簡單的 API、豐富的文件和龐大的使用者群。
我們將要構建的遊戲是一個簡單的 2D 遊戲,您可以在其中與環境互動,移動玩家以捕捉螢幕上的物體。每次玩家觸碰物體時,他的得分都會增加。
這是一個簡單的遊戲,但開發它將使您深入瞭解 Pygame 模組以及如何使用它來建立更高階的遊戲。
開始
在深入使用 pygame 庫之前,我們需要使用 pip 安裝該庫。
但是,由於它不是內建的,因此我們必須首先安裝 pygame 庫。這可以使用 pip 包管理器來完成。
要安裝 pygame 庫,請開啟您的終端並輸入以下命令:
pip install pygame
這將下載並安裝 pygame 庫及其依賴項。安裝完成後,我們可以使用以下語句在 Python 程式碼中匯入 pygame:
import pygame
使用 Pygame 模組構建簡單的遊戲
本文將與其他文章略有不同,因為在本文中,我們將首先編寫完整的指令碼,並新增快速簡便的註釋以供理解,最後再分解所有元件以及我們正在做什麼。這樣更容易理解,並且不會干擾學習過程!
完整程式碼
示例
以下是完整程式碼:
import pygame
import random
# Initialize pygame
pygame.init()
# Set the width and height of the screen (width, height)
screen = pygame.display.set_mode((800, 600))
# Set the title of the window
pygame.display.set_caption("Catch Game")
# Set the clock
clock = pygame.time.Clock()
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# Player class
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
selfelf.image = pygame.Surface([50, 50])
self.image.fill(RED)
self.rect = self.image.get_rect()
self.rect.x = 375
self.rect.y = 500
self.speed = 5
def update(self):
# Get the current key state
keys = pygame.key.get_pressed()
# Move the player
if keys[pygame.K_LEFT]:
self.rect.x -= self.speed
elif keys[pygame.K_RIGHT]:
self.rect.x += self.speed
# Object class
class Object(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface([25, 25])
self.image.fill(BLUE)
self.rect = self.image.get_rect()
self.rect.x = random.randrange(0, 750)
self.rect.y = random.randrange(-100, -40)
self.speed = random.randint(2, 8)
def update(self):
# Move the object down the screen
self.rect.y += self.speed
# If the object goes off the bottom of the screen, reset it
if self.rect.top > 600:
self.rect.x = random.randrange(0, 750)
self.rect.y = random.randrange(-100, -40)
self.speed = random.randint(2, 8)
# Create groups for all sprites and objects
all_sprites = pygame.sprite.Group()
objects = pygame.sprite.Group()
# Create the player
player = Player()
all_sprites.add(player)
# Create the objects
for i in range(10):
obj = Object()
all_sprites.add(obj)
objects.add(obj)
# Set the score
score = 0
# Set the font
font_name = pygame.font.match_font("arial")
# Function to draw text on the screen
def draw_text(surf, text, size, x, y):
font = pygame.font.Font(font_name, size)
text_surface = font.render(text, True, WHITE)
text_rect = text_surface.get_rect()
text_rect.midtop = (x, y)
surf.blit(text_surface, text_rect)
# Game loop
running = True
while running:
# Set the frame rate
clock.tick(60)
# Process events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Update all sprites
all_sprites.update()
# Check for collisions between the player and objects
hits = pygame.sprite.spritecollide(player, objects, True)
for hit in hits:
score += 1
obj = Object()
all_sprites.add(obj)
objects.add(obj)
# Draw everything on the screen
screen.fill(BLACK)
all_sprites.draw(screen)
draw_text(screen, "Score: {}".format(score), 18, 50, 10)
# Update the screen
pygame.display.update()
程式碼分解
此程式碼是 Pygame 遊戲的基本示例。以下是程式碼各部分的解釋:
pygame.init() - 這將初始化 Pygame。
screen = pygame.display.set_mode((800, 600)) - 這將建立一個解析度為 800x600 畫素的遊戲螢幕。
pygame.display.set_caption("Catch Game") - 這將視窗標題設定為“Catch Game”。
clock = pygame.time.Clock() - 這將建立一個 Pygame 時鐘,用於控制遊戲的幀率。
顏色 - 這些行定義了各種顏色常量,這些常量將在程式碼的後面使用。
Player 類 - 這是一個 Pygame 精靈類,用於定義玩家物件。它有一個名為“update”的方法,該方法在每一幀中都被呼叫,以根據使用者輸入更新玩家的位置。
Object 類 - 這是另一個 Pygame 精靈類,用於定義玩家需要捕捉的物件。它有一個名為“update”的方法,該方法在每一幀中都被呼叫,以更新物件的位置。
all_sprites = pygame.sprite.Group() - 這將建立一個 Pygame 精靈組,其中將包含遊戲中的所有精靈。
objects = pygame.sprite.Group() - 這將建立一個 Pygame 精靈組,其中將包含玩家需要捕捉的所有物件。
player = Player() - 這將建立一個 Player 類的例項,並將其新增到 all_sprites 組中。
for i in range(10) - 這將建立 10 個 Object 類的例項,並將它們新增到 all_sprites 組中,並將其新增到 objects 組中。
score = 0 - 這將分數初始化為 0。
font_name = pygame.font.match_font("arial") - 這將設定用於顯示分數的字型。
draw_text(surf, text, size, x, y) - 這是一個輔助函式,用於在螢幕上繪製文字。
遊戲迴圈 - 這是主要的遊戲迴圈。它將一直執行,直到“running”變數設定為 False。
clock.tick(60) - 這將幀率設定為每秒 60 幀。
for event in pygame.event.get() - 這將處理每一幀中發生的 Pygame 事件。
all_sprites.update() - 這將在 all_sprites 組中的所有精靈上呼叫“update”方法。
hits = pygame.sprite.spritecollide(player, objects, True) - 這將檢查玩家和物件之間的碰撞。如果檢測到碰撞,則該物件將從 objects 組中移除,並且得分將增加 1。
screen.fill(BLACK) - 這將螢幕填充為黑色。
all_sprites.draw(screen) - 這將在螢幕上繪製 all_sprites 組中的所有精靈。
draw_text(screen, "Score − {}".format(score), 18, 50, 10): 這將在螢幕上繪製得分。
pygame.display.update() - 這將更新螢幕,顯示當前幀中所做的所有更改。
輸出
這是一個示例輸出

結論
Pygame 是一個強大的開源軟體包,用於在 Python 中建立遊戲和多媒體應用程式。它功能多樣,工具齊全,可以用來建立各種型別的遊戲,從簡單的 2D 平臺遊戲到更復雜的 3D 遊戲。在本教程中,我們瞭解瞭如何使用 Pygame 建立一個簡單的遊戲,玩家可以在其中與環境互動、四處移動並捕捉螢幕上的物體。
完成本教程後,您應該已經瞭解了 Pygame 的工作原理以及如何使用它來建立更復雜的遊戲。總的來說,Pygame 對於想要構建基於 Python 的遊戲的開發者來說是一個極好的工具。
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP