我可以在显示屏上显示数字“ 1”。现在,我的目标是显示数字1 ... 4。这意味着首先显示“ 1”,然后显示1“ 2”,依此类推。如何解决该问题?
这是我的代码:
import pygame
import time
pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
done = False
font = pygame.font.SysFont("comicsansms", 72)
text = font.render("1", True, (0, 128, 0))
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
done = True
screen.fill((255, 255, 255))
screen.blit(text,
(320 - text.get_width() // 2, 240 - text.get_height() // 2))
pygame.display.flip()
clock.tick(60)
答案 0 :(得分:2)
创建一个计数器,然后我们用str()
将值转换为字符串:
counter = 1
text = font.render(str(counter), True, (0, 128, 0))
以一定的时间间隔添加计时器事件(请参见pygame.event
)。计时器事件由pygame.time.set_timer()
mytimerevent = pygame.USEREVENT + 1
pygame.time.set_timer(mytimerevent, 1000) # 1000 milliseconds = 1 socond
增加计数器并更改事件上的文字:
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
done = True
if event.type == mytimerevent: # timer event
counter += 1
text = font.render(str(counter), True, (0, 128, 0))
# [...]
答案 1 :(得分:1)
每帧更新text
如下:
# Setup stuff
number = 1
text = font.render(str(number), True, (0, 128, 0))
while not done:
# Show stuff on screen
number += 1
text = font.render(str(number), True, (0, 128, 0))