使用 Pygame 在 Python 中開發 Flappy Bird 遊戲



在 Flappy Bird 遊戲中,玩家透過點選螢幕控制一隻鳥,使其在管道之間飛行,而不碰到它們。在這裡,我們將使用 pygame 庫設計一個 Flappy Bird 遊戲。

使用 pygame 設計 Flappy Bird 遊戲的步驟

1. 安裝 pygame 庫

要安裝 pygame 庫,請使用 PIP 命令。以下是安裝它的命令:

pip install pygame

2. 匯入庫

您需要使用 import 語句匯入 pygamerandom 庫。以下是匯入這些庫的程式碼語句:

import pygame
import random

3. 初始化 Pygame

要初始化 pygame,只需在匯入庫後呼叫 pygame.init() 方法。

pygame.init()

4. 設定螢幕

描述螢幕解析度並透過 pygame.display.set_mode() 方法建立遊戲視窗。

5. 定義顏色和屬性

您必須設定顏色併為鳥和管道定義屬性。

6. 建立繪圖函式

建立將在螢幕上為鳥和管道佈局的函式。

7. 實現碰撞檢測

現在,加入一個函式來確定鳥是否與管道或螢幕邊界發生碰撞。

8. 管理管道

開發一個函式,允許進行更改並新增可能需要的新的管道。

9. 運行遊戲迴圈

接收使用者的輸入,管理遊戲狀態,識別碰撞並重新繪製介面。

10. 結束遊戲

在檢測到與 `pygame.quit()` 的幫助下檢測到碰撞時退出遊戲視窗。

使用 Pygame 開發 Flappy Bird 遊戲的 Python 程式碼

import pygame
import random

# Initialize Pygame
pygame.init()

# Screen dimensions
SCREEN_WIDTH = 400
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Flappy Bird")

# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)

# Bird properties
BIRD_WIDTH = 40
BIRD_HEIGHT = 30
bird_x = 50
bird_y = SCREEN_HEIGHT // 2
bird_velocity = 0
gravity = 0.5  # Gravity
flap_strength = -7  # Moderate flap strength

# Pipe properties
PIPE_WIDTH = 70
PIPE_HEIGHT = 500
PIPE_GAP = 200  # Pipe gap
pipe_velocity = -2  # Pipe velocity
pipes = []

# Game variables
score = 0
clock = pygame.time.Clock()
flap_cooldown = 0  # Time before the bird can flap again

def draw_bird():
   pygame.draw.rect(screen, BLACK, (bird_x, bird_y, BIRD_WIDTH, BIRD_HEIGHT))

def draw_pipes():
   for pipe in pipes:
      pygame.draw.rect(screen, GREEN, pipe['top'])
      pygame.draw.rect(screen, GREEN, pipe['bottom'])

def check_collision():
   global score
   bird_rect = pygame.Rect(bird_x, bird_y, BIRD_WIDTH, BIRD_HEIGHT)
   for pipe in pipes:
      if bird_rect.colliderect(pipe['top']) or bird_rect.colliderect(pipe['bottom']):
         return True
   if bird_y > SCREEN_HEIGHT or bird_y < 0:
      return True
   return False

def update_pipes():
   global score
   for pipe in pipes:
      pipe['top'].x += pipe_velocity
      pipe['bottom'].x += pipe_velocity
      if pipe['top'].x + PIPE_WIDTH < 0:
         pipes.remove(pipe)
         score += 1
   if len(pipes) == 0 or pipes[-1]['top'].x < SCREEN_WIDTH - 300:
      pipe_height = random.randint(100, SCREEN_HEIGHT - PIPE_GAP - 100)
      pipes.append({
         'top': pygame.Rect(SCREEN_WIDTH, 0, PIPE_WIDTH, pipe_height),
         'bottom': pygame.Rect(SCREEN_WIDTH, pipe_height + PIPE_GAP, PIPE_WIDTH, SCREEN_HEIGHT - pipe_height - PIPE_GAP)
      })

# Game loop
running = True
while running:
   for event in pygame.event.get():
      if event.type == pygame.QUIT:
         running = False
      if event.type == pygame.KEYDOWN:
         if event.key == pygame.K_SPACE and flap_cooldown <= 0:
            bird_velocity = flap_strength
            flap_cooldown = 10  # Set cooldown to prevent rapid flapping
      if event.type == pygame.MOUSEBUTTONDOWN and flap_cooldown <= 0:
         bird_velocity = flap_strength
         flap_cooldown = 10  # Set cooldown to prevent rapid flapping
    
   # Update bird position
   bird_velocity += gravity
   bird_y += bird_velocity

   # Update pipes
   update_pipes()

   # Check for collision
   if check_collision():
      running = False

   # Manage flap cooldown
   if flap_cooldown > 0:
      flap_cooldown -= 1

   # Draw everything
   screen.fill(WHITE)
   draw_bird()
   draw_pipes()

   # Display the score
   font = pygame.font.SysFont(None, 36)
   score_text = font.render(f'Score: {score}', True, BLACK)
   screen.blit(score_text, (10, 10))

   pygame.display.flip()
   clock.tick(30)

pygame.quit()

輸出

Flappy Bird Flappy Bird

點選滑鼠右鍵,您將獲得分數並正確地玩遊戲。

Flappy Bird 遊戲總結

遊戲執行時,會彈出一個標題欄為“Flappy Bird”的視窗,並顯示小鳥和管道。小鳥會受到重力的影響,玩家需要使用空格鍵或滑鼠來使小鳥拍打翅膀。管道從螢幕右側出現並向左移動,玩家需要控制小鳥避免與管道接觸。分數位於畫素遊戲的左上角,隨著小鳥穿過管道而增加。

結論

這個使用pygame實現的Flappy Bird遊戲是一個簡單但非常實用的例子,展示了遊戲開發中的一些概念。如果開發者分析並將其應用到自己的遊戲中,可以學習到的技能包括精靈移動、碰撞檢測和遊戲狀態管理。還可以加入諸如音效、不同難度級別和改進的圖形等功能,使遊戲更有趣。

python_projects_from_basic_to_advanced.htm
廣告