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

如何解决Pygame中Sprite绘制时的闪烁问题?

解决Pygame中移动精灵时对话文本闪烁的问题

问题根源

你的代码闪烁本质是渲染流程混乱:

  1. 多次局部调用pygame.display.update(),导致画面分块渲染不同步
  2. 每帧没有完整重绘背景,文本和精灵的绘制层叠逻辑出错
  3. 字体在draw_text()中每帧重复初始化,额外消耗性能

Pygame默认已经启用双缓冲,不需要手动实现,只要遵循一帧内完成所有绘制,最后一次性刷新屏幕的标准流程就能解决问题。

修正后的完整代码

# Pygame template - skeleton for a new pygame project
import pygame
import d
from os import path

img_dir = path.join(path.dirname(__file__), 'img')

# variables
WIDTH = 1300
HEIGHT = 800
FPS = 30

# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

# initialize pygame and create window
pygame.init()
pygame.mixer.init()
# 默认开启双缓冲,无需额外配置
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Lost In Time")
clock = pygame.time.Clock()

# load graphics
CLOUD = pygame.image.load(path.join(img_dir, 'cloud.png'))
CLOUD.set_colorkey(BLACK)
skyb = pygame.image.load(path.join(img_dir, 'skyb.png'))
bubble = pygame.image.load(path.join(img_dir, 'bubble.png'))
sky = pygame.image.load(path.join(img_dir, 'sky.png'))

# 提前初始化字体,避免每帧重复加载
retro_font = pygame.font.Font("Retro.ttf", 40)

def draw_text(message, y, x):
    newtext = retro_font.render(message, 0, BLACK)
    textrect = newtext.get_rect()
    textrect.topleft = (x, y)
    # 同步气泡位置到文本位置
    bubble_rect = bubble.get_rect(topleft=(x, y))
    screen.blit(bubble, bubble_rect)
    screen.blit(newtext, textrect)

class Cloud(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = CLOUD
        self.rect = self.image.get_rect()
        self.rect.bottomright = (0, 626)

    def update(self):
        self.rect.x += 5
        if self.rect.left > WIDTH:
            self.rect.right = 0

# 初始化精灵组
cloud = Cloud()
cloud_group = pygame.sprite.Group()
cloud_group.add(cloud)

running = True
while running:
    # 控制帧率
    clock.tick(FPS)

    # 事件处理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 1. 绘制背景(清除上一帧内容)
    screen.blit(skyb, (0, 0))
    screen.blit(sky, (0, 0))

    # 2. 更新并绘制精灵
    cloud_group.update()
    cloud_group.draw(screen)

    # 3. 绘制文本(最后绘制,确保在最上层)
    draw_text(d.d3, 650, 55)

    # 4. 一次性刷新整个屏幕(双缓冲生效)
    pygame.display.flip()

pygame.quit()

关键修改说明

  • 统一屏幕刷新:移除所有局部update(),每帧结束用pygame.display.flip()一次性刷新,保证双缓冲机制正常工作
  • 优化绘制顺序:每帧先画背景(覆盖上一帧所有内容),再画精灵,最后画文本,避免层叠混乱
  • 字体预加载:把字体初始化移到全局,避免每帧重复加载带来的性能损耗
  • 修正气泡位置:每次绘制文本时同步气泡的位置,确保和文本对齐
  • 帧率控制:将clock.tick(FPS)移到循环内部,保证游戏稳定在设定帧率

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 00:45:48