You need to enable JavaScript to run this app. 进入碰撞检测If语句后Pygame窗口无响应问题求助
优惠活动
大模型
产品
解决方案
定价
更多

进入碰撞检测If语句后Pygame窗口无响应问题求助

Pygame游戏结束界面无响应问题解决方案

故障根本原因

  • 游戏结束后的while True死循环未调用Pygame事件处理接口,操作系统检测到程序长期不处理事件队列,就会判定为无响应
  • 死循环内没有实时更新鼠标坐标mouse的值,使用的是进入碰撞分支那一刻的旧坐标,按钮点击判定永远无法触发,循环无法退出
  • 没有帧率控制逻辑,无意义占用过高CPU资源,进一步加剧无响应问题

修正后代码

if pygame.Rect.colliderect(ast1.objrect, jetrect):
    ending_num = 1
    end_text = font1.render("Game Over : " + str(score), True, "red")
    end_textrect = end_text.get_rect()
    font2 = pygame.font.Font('freesansbold.ttf', 50)
    text2 = font2.render("Home", True, "dark red", "white")
    mov[1] = 80
    text2rect = text2.get_rect()
    text2rect = text2rect.move(mov)
    font3 = pygame.font.Font('freesansbold.ttf', 50)
    text3 = font3.render("Play", True, "dark red", "white")
    mov[1] = 150
    text3rect = text3.get_rect()
    text3rect = text3rect.move(mov)
    o_speed[1] = 0
    # 初始化时钟控制帧率
    clock = pygame.time.Clock()

    while True:
        # 处理事件队列,避免无响应,同时可支持窗口关闭操作
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                exit()
        # 实时更新鼠标坐标
        mouse = pygame.mouse.get_pos()

        if 10 < mouse[0] < 149 and 80 < mouse[1] < 130 and pygame.mouse.get_pressed()[0]:
            pygame.time.wait(70)
            home_num = 0
            ending_num = 0
            break
        if 10 < mouse[0] < 116 and 150 < mouse[1] < 200 and pygame.mouse.get_pressed()[0]:
            pygame.time.wait(70)
            home_num = 1
            ending_num = 0
            break
        
        # 绘制逻辑放在循环内,避免画面刷新异常
        screen.blit(background, backgroundrect)
        screen.blit(end_text, end_textrect)
        screen.blit(text2, text2rect)
        screen.blit(text3, text3rect)
        pygame.display.flip()
        # 限制帧率为60,降低CPU占用
        clock.tick(60)

额外优化建议

  • 不要在碰撞分支内重复加载字体,把font2、font3的初始化放到程序全局初始化部分,避免重复IO读取降低性能
  • 按钮点击判定推荐使用pygame.MOUSEBUTTONDOWN事件判断,比持续检测pygame.mouse.get_pressed()的误触率更低

内容的提问来源于stack exchange,提问作者Sina Aghily

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 11:27:02