Code Flappy Bird bằng Python sử dụng thư viện Pygame
1. Import thư viện
import pygame, time, random
import sys, os
Nhập thư viện Pygame, Random, System và OS dùng cho đóng gói
2. Hàm resource_path
def resource_path(path):
if hasattr(sys, "_MEIPASS"):
return os.path.join(sys._MEIPASS, path)
return os.path.join(os.path.abspath("."), path)
Dùng khi build .exe với PyInstaller để tìm đúng file asset
3. Khởi tạo game
pygame.mixer.pre_init(...)
pygame.init()
Chuẩn bị âm thanh và khởi tạo Pygame
4. Hàm vẽ mặt đất
def draw_floor():
screen.blit(floor, (floor_x_position, 530))
screen.blit(floor, (floor_x_position + 378, 530))
Vẽ mặt đất chạy ngang bằng 2 ảnh ghép lại
5. Hàm tạo ống
def create_pipe():
random_pipi_position = random.choice(pipe_height)
bottom = pipe.get_rect(midtop=(450, random_pipi_position))
top = pipe.get_rect(midtop=(450, random_pipi_position - 670))
return bottom, top
Tạo ống trên + dưới với khoảng cách 670px
6. Hàm di chuyển ống
def pipe_space(pipe_list):
for p in pipe_list:
p.centerx -= 5
return pipe_list
Cho ống trôi ngang sang trái
7. Va chạm
def check_collision(pipe_list):
for p in pipe_list:
if bird_rect.colliderect(p):
return True
if bird_rect.top <= -20 or bird_rect.bottom>= 530:
return True
return False
Kiểm tra chim va vào ống, mặt đất hoặc trần
8. Chim rơi & xoay
def rotate_bird(old_bird):
return pygame.transform.rotozoom(old_bird, -bird_movement*4, 1)
Quay chim theo vector rơi để nhìn tự nhiên