5.14记录 实现flappy bird

一、加载资源

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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值