问题描述
我有一个使用 pygame 制作的游戏,但显然文字不起作用。控制台也没有错误。这是我的代码:
font = pygame.font.SysFont("monospace",55)
def text_screen(text,color,x,y):
screen_text = font.render(text,True,color)
gameWindow.blit(screen_text,(x,y))
# rest of code [...]
# then where i need text;
if abs(snake_x - food_x) < 5 and abs(snake_y - food_y) < 5:
score +=1*10
print("score: ",score)
text_screen("score: " + str(score * 10),red,5,5)
pygame.display.update()
food_x = random.randint(20,screen_width / 2)
food_y = random.randint(20,screen_height / 2)
解决方法
要使文本永久化,您需要在每一帧绘制它,而不仅仅是在检测到碰撞时绘制一次。检测到碰撞时渲染文本并设置变量 (score_surf
)。设置变量后,在应用程序循环中绘制文本:
score_surf = None
while True:
# [...]
if abs(snake_x - food_x) < 5 and abs(snake_y - food_y) < 5:
score += 10
print("Score: ",score)
score_surf = font.render("Score: " + str(score),True,red)
food_x = random.randint(20,screen_width / 2)
food_y = random.randint(20,screen_height / 2)
# [...]
if score_surf != None:
gameWindow.blit(score_surf,(5,5))
# [...]
pygame.display.update()