一、加载资源
import pygame
import random
# 初始化Pygame
pygame.init()
# 设置窗口大小和标题
width, height = 288, 512
window = pygame.display.set_mode((width, height))
pygame.display.set_caption("Flappy Bird")
# 加载背景图像
background = pygame.image.load("resourse/background.webp")
# 加载鸟的图像
bird = pygame.image.load("resourse/bird.webp")
# 加载管道图像
pipe = pygame.image.load("resourse/pipe.webp")
二、设置游戏
# 小鸟的位置和速度
bird_x = 100
bird_y = 200
bird_speed = 0
# 管道列表
pipes = []
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
bird_speed = -2 # 每按一次空格,鸟的速度减2,相当于上升
# 更新游戏状态
bird_y += bird_speed
bird_speed += 0.02 # 鸟在逐渐下降,也说明整个窗口坐标是左上为0向下和向右为正
# 生成管道
if len(pipes) == 0 or pipes[-1][0] < width - 200: # 没有障碍或者障碍已经移动到指定位置后生成,这里设置为width - 200
pipe_x = width # 最开始管道生成在最右边,所以x坐标就是窗口大小
pipe_y = random.randint(100, height - 200) # 管道的y轴,因为生成管道图像时也用到此坐标,所以坐标为管道左上角点,范围在100到312之间
pipes.append((pipe_x, pipe_y))
# 移动管道
for i in range(len(pipes)):
pipes[i] = (pipes[i][0] - 0.2, pipes[i][1]) # 障碍坐标左移0.2单位,这里的数决定游戏的难度
# 移除离开屏幕的管道
if pipes[0][0] < -pipe.get_width():
pipes.pop(0)
for one_pipe in pipes:
# 遍历每一根管道,
# 第一个条件,bird_x + bird.get_width() > one_pipe[0] 表示鸟的当前x位置加上鸟这个图像的宽度超过了管道的x轴坐标,
# 这里的坐标都是图像左上点,左上为坐标原点
# 第二个条件,bird_y + bird.get_height() > pipe.get_height() 鸟图像左上角y坐标加鸟的图像高度(这里坐标系向下为正)
# 大于管道的左上角y坐标,两个条件结合相当于发生了碰撞
# 然后还要考虑一下鸟左边碰到管道右边的情况,同理,这里就不写了
if bird_x + bird.get_width() > one_pipe[0] and bird_y + bird.get_height() > pipe.get_height():
running = False
# 绘制游戏画面
window.blit(background, (0, 0))
window.blit(bird, (bird_x, bird_y))
for one_pipe in pipes:
window.blit(pipe, one_pipe) # 坐标为图像左上角点
# 刷新屏幕
pygame.display.flip()
# 退出游戏
pygame.quit()