我有一个Lives的显示,上面写着"Lives:0"。当你按下任何键时,Lives都会下降1,我将其称为print self.lives -= 1
,这样控制台就会确认Lives是-=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
最初的内容。您需要更新它,但只有在触发事件时才需要更新。