Python游戏开发:用Pygame制作Flappy Bird
在当今快节奏的世界里,游戏不仅是娱乐的工具,更是学习编程的绝佳途径。今天,我们将探讨如何使用Python的Pygame库制作经典游戏Flappy Bird。这不仅是一次技术实践,更是一次创意与逻辑的碰撞。

准备工作
首先,确保你已经安装了Python和Pygame库。如果还没有安装,可以通过以下命令进行安装:
pip install pygame
项目结构
一个清晰的项目结构有助于我们更好地管理代码。建议创建以下文件和文件夹:
FlappyBird/
│
├── main.py
├── assets/
│ ├── bird.png
│ ├── background.png
│ ├── pipe.png
│ └── ...
└── utils.py
导入必要的库
在main.py中,首先导入Pygame库和其他必要的模块:
import pygame
import sys
import random
from utils import load_image
初始化Pygame
接下来,初始化Pygame并设置窗口:
pygame.init()
screen_width = 400
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Flappy Bird")
加载资源
在utils.py中,创建一个函数来加载图像:
def load_image(name):
return pygame.image.load(f'assets/{name}')
然后在main.py中加载所需的图像:
bird_image = load_image('bird.png')
background_image = load_image('background.png')
pipe_image = load_image('pipe.png')
创建游戏对象
定义鸟类、管道和背景类:
class Bird(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = bird_image
self.rect = self.image.get_rect(center=(50, screen_height // 2))
self.gravity = 0.5
self.velocity = 0
def update(self):
self.velocity += self.gravity
self.rect.y += self.velocity
class Pipe(pygame.sprite.Sprite):
def __init__(self, position):
super().__init__()
self.image = pipe_image
self.rect = self.image.get_rect(midtop=position)
class Background(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = background_image
self.rect = self.image.get_rect(topleft=(0, 0))
游戏主循环
在main.py中,创建游戏的主循环:
def main():
clock = pygame.time.Clock()
bird = Bird()
pipes = pygame.sprite.Group()
all_sprites = pygame.sprite.Group(bird)
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:
bird.velocity = -10
screen.blit(background_image, (0, 0))
all_sprites.update()
all_sprites.draw(screen)
pygame.display.flip()
clock.tick(60)
pygame.quit()
sys.exit()
if __name__ == "__main__":
main()
添加管道生成逻辑
为了使游戏更具挑战性,我们需要不断生成新的管道:
def create_pipe():
pipe_height = random.randint(100, 400)
bottom_pipe = Pipe((screen_width, pipe_height))
top_pipe = Pipe((screen_width, pipe_height - 700))
pipes.add(bottom_pipe, top_pipe)
all_sprites.add(bottom_pipe, top_pipe)
PIPE SPAWN = pygame.USEREVENT
pygame.time.set_timer(PIPE SPAWN, 1200)
while running:
# ... 其他代码
if event.type == PIPE SPAWN:
create_pipe()
碰撞检测与得分
最后,添加碰撞检测和得分逻辑:
def check_collision():
if pygame.sprite.spritecollideany(bird, pipes) or bird.rect.top <= 0 or bird.rect.bottom >= screen_height:
return True
return False
score = 0
font = pygame.font.Font(None, 36)
while running:
# ... 其他代码
if check_collision():
running = False
screen.blit(font.render(f'Score: {score}', True, (255, 255, 255)), (10, 10))
score += 1
通过以上步骤,我们成功制作了一个简易版的Flappy Bird游戏。这不仅是一次编程实践,更是对游戏逻辑和创意思维的锻炼。希望你能在此基础上,加入更多创意元素,制作出独一无二的游戏作品。编程的乐趣,正藏在这些不断探索和创造的过程中。
« 上一篇
Python打造简易在线购物车
下一篇 »
Python打造简易邮件发送系统