以下是使用Pygame库实现Flappy Bird游戏的示例代码:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 设置游戏窗口大小和标题
screen_width = 288
screen_height = 512
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Flappy Bird')
# 加载游戏资源
bg_image = pygame.image.load('assets/background.png').convert()
bird_images = [pygame.image.load('assets/bird1.png').convert_alpha(),
pygame.image.load('assets/bird2.png').convert_alpha(),
pygame.image.load('assets/bird3.png').convert_alpha()]
pipe_image = pygame.image.load('assets/pipe.png').convert_alpha()
base_image = pygame.image.load('assets/base.png').convert_alpha()
# 定义常量
gravity = 0.25
jump_speed = -4
pipe_gap = 100
pipe_speed = -2
base_speed = -1
# 定义类:小鸟、水管、地面
class Bird:
def __init__(self):
self.x = 50
self.y = 200
self.speed = 0
self.image_index = 0
self.image = bird_images[self.image_index]
def jump(self):
self.speed = jump_speed
def update(self):
self.speed += gravity
self.y += self.speed
if self.y < 0:
self.y = 0
if self.y > screen_height - 50:
self.y = screen_height - 50
self.image_index += 1
if self.image_index >= len(bird_images):
self.image_index = 0
self.image = bird_images[self.image_index]
def draw(self):
screen.blit(self.image, (self.x, self.y))
class Pipe:
def __init__(self, x):
self.x = x
self.y = random.randint(-200, 0)
self.width = pipe_image.get_width()
self.height = pipe_image.get_height()
self.passed = False
def update(self):
self.x += pipe_speed
def draw(self):
screen.blit(pipe_image, (self.x, self.y))
screen.blit(pygame.transform.flip(pipe_image,