如何在pygam中编辑屏幕上的文本

2024-10-01 09:34:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个生命展览,上面写着生命:0。“当你按任何键时,生命值将下降1,我将其称为printself.lives -= 1,这样控制台就确认生命值为-=1,但显示保持不变。我要在荧幕上表演长袍。你知道吗

self.lives = 5

sysfont = pygame.font.SysFont(None, 25)
self.text = sysfont.render("Lives: %d" % self.lives, True, (255, 255, 255))

While running:

if event.type == pygame.KEYDOWN:    
  print "Ouch"
  self.lives -= 1
  print self.lives

rect = self.text.get_rect()
    rect = rect.move(500,500)
    self.screen.blit(self.text, rect)

Tags: textrectselfnonerenderpygameprintfont
2条回答

每次lives更改时都需要重新呈现文本。下面是一个快速演示:

import sys
import pygame

pygame.init()

def main():
    screen = pygame.display.set_mode((400, 400))
    font = pygame.font.SysFont('Arial', 200, False, False)

    lives = 5

    while True:
        event = pygame.event.poll()
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.KEYDOWN:
            lives -= 1

        screen.fill((255, 255, 255))
        text = font.render(str(lives), True, (0,0,0))

        screen.blit(text, (25, 25))
        pygame.display.flip()

main()

为了提高效率,您可以尝试仅在按下键时重新渲染,而不是每次迭代一次。你知道吗

我认为您需要做的就是将:
self.text = sysfont.render("Lives: %d" % self.lives, True, (255, 255, 255))
添加到您的if中,如下所示:

if event.type == pygame.KEYDOWN:    
  print "Ouch"
  self.lives -= 1
  print self.lives
  self.text = sysfont.render("Lives: %d" % self.lives, True, (255, 255, 255))

如果您只在开头有这一行,那么您总是要打印self.lives最初的内容。您需要更新它,但您只需要在触发事件时更新它。你知道吗

相关问题 更多 >