![](/img/trans.png)
[英]Python threading - How to repeatedly execute a function in a separate thread?
[英]How to execute event repeatedly in Python?
我是 pygame 編程的新手。 我需要該操作使用“self.vel+=1”每 10 秒增加一次角色的速度(在屏幕上表示為移動圖像)。 可能 pygame.time.set_timer) 會這樣做,但我不知道如何使用它。 因為我使用帶有移動圖像的窗口,所以 time.sleep 不是一個好主意,因為那樣窗口會凍結。 什么應該是最好的選擇以及如何使用它?
使用 Python 的time模塊,您可以在代碼運行時計時 10 秒,並在 10 秒過去后提高速度。
這是一個使用計時器的簡單示例。 屏幕上充滿了每 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)
。
如果您需要任何說明,請告訴我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.