我对 pygame 相当陌生,我遇到了我的第一个难题,我找不到答案..
在位图传输文本后,然后更改同一变量的字符串,游戏不是用新文本替换原始文本,而是重叠两个文本..?
您必须先删除旧文本。由
Font.render
创建的曲面是普通曲面。一旦 Surface
被 blit,它的内容就会成为目标表面的一部分,并且您必须操纵 destination 表面以擦除从源表面中 blit 的任何内容。
擦除目标表面的一种方法是将背景表面传输到其上。背景表面是目标表面的样子,上面没有任何文本或精灵之类的东西。另一种方法是用纯色填充表面:
# 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((255, 255, 255))
############################
screen.blit(font.render(textVar, True, (255, 255, 0)), (10, 10))
pygame.display.update()
如果您不想填充所有表面,您可以在本文中创建矩形:
textVar = ""
screen = pygame.display.set_mode((500, 500))
rect = pygame.Rect(0, 0, 0, 0)
font = pygame.font.Font(None, 36)
while True:
###################################################################
pygame.draw.rect(screen, (255, 255, 255), rect) # filling this text
rect = font.render(textVar, True, (255, 255, 0)) # get surface with text
rect = screen.blit(rect, (10, 10)) # get rectangle of your text
###################################################################
pygame.display.update() # Update screen;