You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pygame调用draw.rect无法绘制矩形,开发Flappy Bird时管道不显示

Pygame Flappy Bird管道不显示问题修复方案

问题原因

  • 管道初始横向位置pole_x = 320刚好等于窗口宽度,管道完全在可视区域右侧外部,且你注释了管道位移代码,管道始终停留在窗口外无法被观测到
  • 注释掉的位移代码pole_x = pole_x - 500数值设置不合理,若放开会导致管道每帧位移500像素,瞬间移出屏幕
  • 同时调用pygame.display.flip()和pygame.display.update()属于重复操作,虽然不直接导致绘制失败,但属于不规范写法
  • 当前仅编写了上半部分管道的绘制逻辑,缺少下半部分管道的绘制代码
  • 缺少窗口关闭事件处理逻辑,程序无法正常退出

修复方案

  • 调整管道初始位置,或者修正位移代码,将位移量改为2~3的小数值,适配60帧的运行速度
  • 删掉重复的画面更新调用,仅保留pygame.display.update()或者pygame.display.flip()其中一个即可
  • 补充下半部分管道的绘制逻辑
  • 新增窗口关闭事件处理逻辑

注意:如果使用自定义图片资源,需确保bg.png和player.png文件放在代码同目录下,否则图片加载失败会导致程序报错退出。如果测试时没有对应图片,可以先用参考代码里的纯色Surface替代测试。


修复后可运行参考代码

import pygame
import random
pygame.init()
surface = pygame.display.set_mode((320, 568))
# 无自定义图片可取消下面两行注释,用纯色替代资源测试
# bg = pygame.Surface((320,568))
# bg.fill((135,206,235))
# bird = pygame.Surface((30,20))
# bird.fill((255,255,0))
bg = pygame.image.load('bg.png')
bird = pygame.image.load('player.png')

pole_width = 70
pole_gap = 100
pole_x = 320
top_pole_height = random.randint(100, 300)
pole_color = (220, 85, 57)
bird_x = 20
bird_y = 200
score = 0
clock = pygame.time.Clock()

while True:
    # 窗口关闭事件处理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()
            
    keys = pygame.key.get_pressed()
    if keys[pygame.K_DOWN]:
        bird_y += 3
    elif keys[pygame.K_UP]:
        bird_y -= 3
    
    # 管道自动移动+移出重置逻辑
    pole_x -= 2
    if pole_x < -pole_width:
        pole_x = 320
        top_pole_height = random.randint(100, 300)
    
    surface.blit(bg, (0, 0))
    surface.blit(bird, (bird_x, bird_y))
    # 绘制上下管道
    pygame.draw.rect(surface, pole_color, pygame.Rect(pole_x, 0, pole_width, top_pole_height))
    bottom_pole_y = top_pole_height + pole_gap
    bottom_pole_height = 568 - bottom_pole_y
    pygame.draw.rect(surface, pole_color, pygame.Rect(pole_x, bottom_pole_y, pole_width, bottom_pole_height))
    
    pygame.display.update()
    clock.tick(60)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 21:45:04