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

Pygame点击器开发问题:分数更新渲染时出现文字重叠不刷新

问题原因

你只在pygame初始化阶段执行了一次screen.fill('lightblue')填充背景,后续游戏循环过程中没有清除上一帧的绘制内容,每次调用disp_score绘制新分数时,就会直接叠加在旧的分数文字之上,出现重叠显示的问题。

解决方法

最简单的方案是每帧绘制所有内容之前,先统一填充背景清空上一帧的内容,只需把背景填充的代码移到游戏循环的最开头即可。
如果你的游戏后续元素较多,不想整屏重绘提升性能,也可以在绘制新分数前,仅把上一次分数对应的矩形区域用背景色填充覆盖。

修改后可运行代码

import pygame
import button

SCREEN_WIDTH = 700
SCREEN_HEIGHT = 900

pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Cocaine Clicker')
clock = pygame.time.Clock()
font = pygame.font.Font('Pacifico-Regular.ttf', 100)

score = 0
score_increase_factor = 1
# 补充你原代码漏写的money_sprite实例化逻辑即可,例如 money_sprite = button.你的按钮类()

def disp_score(score):
    score_surf = font.render(f'${score}', False, (0,0,0))
    score_rect = score_surf.get_rect(center = (350, 50))
    screen.blit(score_surf, score_rect)

while True:
    # 每帧先填充背景清空上一帧内容
    screen.fill('lightblue')
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()

    disp_score(score)

    if money_sprite.draw(screen):
        score = score + score_increase_factor
        print(score)

    pygame.display.update()
    clock.tick(60)

可选优化方案(局部清屏)

如果不需要整屏重绘,可以单独清空分数区域,适合背景有复杂固定元素的场景:

last_score_rect = None
def disp_score(score):
    global last_score_rect
    # 先覆盖上一次的分数区域
    if last_score_rect:
        screen.fill('lightblue', last_score_rect)
    score_surf = font.render(f'${score}', False, (0,0,0))
    score_rect = score_surf.get_rect(center = (350, 50))
    screen.blit(score_surf, score_rect)
    last_score_rect = score_rect

使用这个方案就不需要每帧整屏填充背景。

内容的提问来源于stack exchange,提问作者Mr. Krouton

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 20:06:03