我对pygame还比较陌生,遇到了第一个找不到答案的问题。
在绘制文本后,更改相同变量的字符串。游戏没有用新文本替换原来的文本,而是重叠两个文本?
你首先需要清除旧的文本。使用Font.render
创建出来的表面是普通的表面。一旦对一个Surface
进行贴图,它的内容就成为目标表面的一部分,你需要操纵目标表面以清除从源表面上贴图的任何内容。
清除目标表面的一种方式是将一个背景表面贴图到它上面。背景表面是没有文本或者精灵等任何东西时目标表面的样子。另一种方式是用纯色填充表面:
# pygame initialization goes here
screen = pygame.display.get_surface()
font = pygame.font.Font(None, 40)
font_surface = font.render("original", True, pygame.Color("white"));
screen.blit(surface, (0, 0))
screen.fill(pygame.Color("black")) # erases the entire screen surface
font_surface = font.render("edited", True, pygame.Color("white"));
screen.blit(surface, (0, 0))
label = myfont.render("Text", 0, (255,255,0))
screen.blit(label, (100, 100))
if x: //Parameter you check before overwrite
label = myfont.render("Text", 0, BACKGROUND_COLOR)
screen.blit(label, (100, 100))
可能有另一种解决方案,即使它并不非常不同。之前的答案会擦除整个屏幕,但你可以只擦除你的文本。如果文本是写在图像上的,你可以通过获取文本大小并使用pygame.surface.subsurface函数来复制相应的图像部分,以替换其中的一部分。或者如果文本没有写在图像上,你可以只填充屏幕的一部分。在这种情况下,你只需要擦除你的文本。
对我来说,创建一个黑色矩形,并且只在特定任务满足时调用它是有效的:以下是一个示例,
我遍历变量中的值:
for j in str(value):
# Here I check if my target is met (if I clicked a button)
if event.type == mousepress and event.button == leftclick:
pygame.draw.rect(clicker, "black", pygame.Rect(650, 120, 350, 100))
break
# I then update the blit and font or text or whatever
font = pygame.font.SysFont("Times New Roman", 35)
numberdisplay = font.render('upgrade: ' + j, True, 'pink')
clicker.blit(display,(650 - display.get_width() // 2, 150 - display.get_height() // 2))
screen.fill(pygame.Color("black"), (0, 0, 110, 40))
。 - Jason Lv