我有一个Lives的显示器,上面写着“生命:0”。按任意键时,生命将减少1,我将其称为打印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)
答案 0 :(得分:1)
每次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()
为了提高效率,您可以尝试仅在按下键时重新渲染,而不是每次迭代都重复渲染。
答案 1 :(得分:0)
我认为您需要做的就是添加: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
原来的内容。您需要更新它,但只有在触发事件时才需要这样做。