首頁 > 後端開發 > Python教學 > 如何創建具有多個關卡和主選單的 Pygame 遊戲?

如何創建具有多個關卡和主選單的 Pygame 遊戲?

Susan Sarandon
發布: 2024-11-28 15:41:14
原創
742 人瀏覽過

How to Create a Pygame Game with Multiple Levels and a Main Menu?

Pygame 關卡/選單狀態

Pygame 是一個用於建立 2D 遊戲的熱門 Python 函式庫。它提供了各種用於處理圖形、聲音、輸入等的模組。

在本文中,我們將討論如何使用 Pygame 創建具有多個關卡和選單的遊戲。我們將從創建一個具有單一關卡的簡單遊戲開始,然後我們將對此進行擴展以創建具有多個關卡和主選單的遊戲。

創建一個具有單一關卡的簡單遊戲

要創建一個具有單一關卡的簡單遊戲,我們需要創建一個 Pygame 窗口,加載一些圖形,並創建一個遊戲循環。

這是一段程式碼顯示如何執行此操作的程式碼片段:

import pygame

# Initialize the Pygame library
pygame.init()

# Set the window size
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

# Create the Pygame window
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

# Set the window title
pygame.display.set_caption("My Game")

# Load the background image
background_image = pygame.image.load("background.png").convert()

# Create the player sprite
player = pygame.sprite.Sprite()
player.image = pygame.image.load("player.png").convert()
player.rect = player.image.get_rect()
player.rect.center = (SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)

# Create the enemy sprite
enemy = pygame.sprite.Sprite()
enemy.image = pygame.image.load("enemy.png").convert()
enemy.rect = enemy.image.get_rect()
enemy.rect.center = (SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 + 100)

# Create a group to hold all the sprites
all_sprites = pygame.sprite.Group()
all_sprites.add(player)
all_sprites.add(enemy)

# Create a clock to control the game loop
clock = pygame.time.Clock()

# Run the game loop
running = True
while running:

    # Process events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Update the game state
    all_sprites.update()

    # Draw the game画面
    screen.blit(background_image, (0, 0))
    all_sprites.draw(screen)

    # Flip the display
    pygame.display.flip()

    # Cap the frame rate at 60 FPS
    clock.tick(60)

# Quit the game
pygame.quit()
登入後複製

此程式碼建立一個帶有背景圖像和兩個精靈的 Pygame 視窗:一個玩家和一個敵人。遊戲循環一直運行,直到玩家退出遊戲,並且在循環的每次迭代期間,遊戲狀態都會更新,螢幕會被繪製,並且顯示會被翻轉。

將遊戲擴展到包含多個關卡和主選單

要擴展遊戲以包含多個層級和主選單,我們需要建立一個新的 Scene 類別。場景代表遊戲的特定部分,例如關卡或選單。

以下程式碼片段展示如何建立場景類別:

class Scene:

    def __init__(self):
        self.next = None

    def update(self):
        pass

    def draw(self, screen):
        pass

    def handle_events(self, events):
        pass
登入後複製

場景類別有三個方法:update、draw 和handle_events。每個畫面呼叫update方法來更新遊戲狀態,每幀呼叫draw方法來繪製遊戲畫面,每幀呼叫handle_events方法來處理使用者輸入。

我們現在可以建立一個每個層級和主選單的新場景。下面的程式碼片段展示瞭如何執行此操作:

class Level1(Scene):

    def __init__(self):
        super().__init__()

        # Create the player sprite
        self.player = pygame.sprite.Sprite()
        self.player.image = pygame.image.load("player.png").convert()
        self.player.rect = self.player.image.get_rect()
        self.player.rect.center = (SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)

        # Create the enemy sprite
        self.enemy = pygame.sprite.Sprite()
        self.enemy.image = pygame.image.load("enemy.png").convert()
        self.enemy.rect = self.enemy.image.get_rect()
        self.enemy.rect.center = (SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 + 100)

        # Create a group to hold all the sprites
        self.all_sprites = pygame.sprite.Group()
        self.all_sprites.add(self.player)
        self.all_sprites.add(self.enemy)

    def update(self):
        # Update the game state
        self.all_sprites.update()

    def draw(self, screen):
        # Draw the game画面
        screen.blit(background_image, (0, 0))
        self.all_sprites.draw(screen)

    def handle_events(self, events):
        # Handle user input
        for event in events:
            if event.type == pygame.QUIT:
                # The user has quit the game
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    # The user has pressed the left arrow key
                    self.player.rect.x -= 10
                elif event.key == pygame.K_RIGHT:
                    # The user has pressed the right arrow key
                    self.player.rect.x += 10
                elif event.key == pygame.K_UP:
                    # The user has pressed the up arrow key
                    self.player.rect.y -= 10
                elif event.key == pygame.K_DOWN:
                    # The user has pressed the down arrow key
                    self.player.rect.y += 10

class MainMenu(Scene):

    def __init__(self):
        super().__init__()

        # Create the title text
        self.title_text = pygame.font.Font(None, 50)
        self.title_text_image = self.title_text.render("My Game", True, (255, 255, 255))
        self.title_text_rect = self.title_text_image.get_rect()
        self.title_text_rect.center = (SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)

        # Create the start button
        self.start_button = pygame.draw.rect(screen, (0, 255, 0), (SCREEN_WIDTH / 2 - 50, SCREEN_HEIGHT / 2 + 100, 100, 50))

    def update(self):
        pass

    def draw(self, screen):
        # Draw the game画面
        screen.blit(background_image, (0, 0))
        screen.blit(self.title_text_image, self.title_text_rect)
        pygame.draw.rect(screen, (0, 255, 0), self.start_button)

    def handle_events(self, events):
        # Handle user input
        for event in events:
            if event.type == pygame.QUIT:
                # The user has quit the game
                pygame.quit()
                sys.exit()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                # The user has clicked the start button
                if self.start_button.collidepoint(event.pos):
                    # Set the next scene to Level1
                    self.next = Level1()
登入後複製

我們現在可以建立一個新的 SceneManager 類別來管理不同的場景。 SceneManager 追蹤目前場景,並在目前場景完成時切換到下一個場景。

以下程式碼片段顯示如何建立 SceneManager 類別:

class SceneManager:

    def __init__(self):
        self.current_scene = MainMenu()

    def run(self):
        # Run the game loop
        running = True
        while running:

            # Process events
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    # The user has quit the game
                    running = False

            # Update the current scene
            self.current_scene.update()

            # Draw the current scene
            self.current_scene.draw(screen)

            # Flip the display
            pygame.display.flip()

            # Check if the current scene is finished
            if self.current_scene.next is not None:
登入後複製

以上是如何創建具有多個關卡和主選單的 Pygame 遊戲?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板