如何在Python中重复执行事件?
How to execute event repeatedly in Python?
我是 pygame 编程新手。我需要使用 'self.vel+=1' 每 10 秒增加角色的速度(在屏幕上表示为移动图像)的操作。可能 pygame.time.set_timer) 会这样做,但我不知道如何使用它。因为我将 window 用于移动图像,所以 time.sleep 不是个好主意,因为那样 window 会冻结。
什么应该是最好的选择以及如何使用它?
使用 Python 的 time 模块,您可以在代码为 运行 时计时十秒,并在十秒后加快速度。
这是一个使用计时器的简单示例。屏幕充满了每 0.4 秒变化一次的颜色。
import pygame
import itertools
CUSTOM_TIMER_EVENT = pygame.USEREVENT + 1
my_colors = ["red", "orange", "yellow", "green", "blue", "purple"]
# create an iterator that will repeat these colours forever
color_cycler = itertools.cycle([pygame.color.Color(c) for c in my_colors])
pygame.init()
pygame.font.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode([320,240])
pygame.display.set_caption("Timer for Dino Gržinić")
done = False
background_color = next(color_cycler)
pygame.time.set_timer(CUSTOM_TIMER_EVENT, 400)
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == CUSTOM_TIMER_EVENT:
background_color = next(color_cycler)
#Graphics
screen.fill(background_color)
#Frame Change
pygame.display.update()
clock.tick(30)
pygame.quit()
创建计时器的代码是pygame.time.set_timer(CUSTOM_TIMER_EVENT, 400)
。这会导致每 400 毫秒生成一个事件。因此,为了您的目的,您需要将其更改为 10000
。请注意,您可以在数字常量中包含下划线以使其更加明显,因此您可以使用 10_000
.
事件生成后,需要对其进行处理,因此在 elif event.type == CUSTOM_TIMER_EVENT:
语句中。这就是您要提高精灵速度的地方。
最后,如果你想取消定时器,例如游戏结束时,您提供零作为计时器持续时间:pygame.time.set_timer(CUSTOM_TIMER_EVENT, 0)
.
如果您需要任何说明,请告诉我。
我是 pygame 编程新手。我需要使用 'self.vel+=1' 每 10 秒增加角色的速度(在屏幕上表示为移动图像)的操作。可能 pygame.time.set_timer) 会这样做,但我不知道如何使用它。因为我将 window 用于移动图像,所以 time.sleep 不是个好主意,因为那样 window 会冻结。 什么应该是最好的选择以及如何使用它?
使用 Python 的 time 模块,您可以在代码为 运行 时计时十秒,并在十秒后加快速度。
这是一个使用计时器的简单示例。屏幕充满了每 0.4 秒变化一次的颜色。
import pygame
import itertools
CUSTOM_TIMER_EVENT = pygame.USEREVENT + 1
my_colors = ["red", "orange", "yellow", "green", "blue", "purple"]
# create an iterator that will repeat these colours forever
color_cycler = itertools.cycle([pygame.color.Color(c) for c in my_colors])
pygame.init()
pygame.font.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode([320,240])
pygame.display.set_caption("Timer for Dino Gržinić")
done = False
background_color = next(color_cycler)
pygame.time.set_timer(CUSTOM_TIMER_EVENT, 400)
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == CUSTOM_TIMER_EVENT:
background_color = next(color_cycler)
#Graphics
screen.fill(background_color)
#Frame Change
pygame.display.update()
clock.tick(30)
pygame.quit()
创建计时器的代码是pygame.time.set_timer(CUSTOM_TIMER_EVENT, 400)
。这会导致每 400 毫秒生成一个事件。因此,为了您的目的,您需要将其更改为 10000
。请注意,您可以在数字常量中包含下划线以使其更加明显,因此您可以使用 10_000
.
事件生成后,需要对其进行处理,因此在 elif event.type == CUSTOM_TIMER_EVENT:
语句中。这就是您要提高精灵速度的地方。
最后,如果你想取消定时器,例如游戏结束时,您提供零作为计时器持续时间:pygame.time.set_timer(CUSTOM_TIMER_EVENT, 0)
.
如果您需要任何说明,请告诉我。