Python飞机大战,一直按着键不放问题(持续按键)

该博客主要展示了使用Pygame库开发游戏的代码。设置了游戏时钟,定义了画面中飞机、背景等组件的初始位置。在无限循环中,以每秒60帧的速度运行,修改组件位置,处理退出和按键事件,最后更新屏幕显示,实现组件移动效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

看红色代码

# 游戏时钟
clock = pygame.time.Clock()

# 定义画面中各组件的初始位置
plane_rect = pygame.Rect(0, 168, 64, 64)
bg_rect = pygame.Rect(0, 10, 600, 400)
foreground_rect = pygame.Rect(0, 302, 1018, 98)
foreground_light_rect = pygame.Rect(580, 302, 1018, 98)

pygame.key.set_repeat(1, 1)    # 表示每隔1毫秒发送一个pygame.KEYDOWN,事件间隔1毫秒

# 无限循环,窗口不关闭,(游戏循环)

while True:

    # 一秒钟60帧
    clock.tick(60)
    # 修改初始位置的x,y坐标
    foreground_rect.x -= 1
    # plane_rect.x += 1
    bg_rect.x -= 1

    # 获取事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            # 直接退出系统
            exit()
        if event.type == pygame.KEYDOWN and event.key == pygame.K_DOWN :
            plane_rect.y += 5
            if plane_rect.bottom >=464 :
                plane_rect.y = 0

        if event.type == pygame.KEYDOWN and event.key == pygame.K_UP :
            plane_rect.y -= 5
            if plane_rect.bottom <= 0:
                plane_rect.y = 400
        # break

    surface.blit(bg, bg_rect)
    surface.blit(plane1, plane_rect)
    surface.blit(foreground, foreground_rect)
    # 屏幕更新才能看到图片
    if foreground_rect.x == -438:
        foreground_rect.x = 0
    if bg_rect.x == -638:
        bg_rect.x = 0

    pygame.display.update()

    print(event)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值