繁体   English   中英

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

[英]How do I edit onscreen text in pygame

我有一个“ Lives”显示,显示“ Lives:0”。 当您按任意键时,寿命将下降1,我将其称为print self.lives -= 1以便控制台确认寿命为-=1 ,但显示保持不变。 我希望Lives在屏幕上做礼服。

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)

每当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最初的内容。 您需要更新它,但是仅在事件触发时才需要更新。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM