首页 > 解决方案 > 如何使用 pygame.time.get_ticks() 在不影响用户输入的情况下进行延迟

问题描述

所以我正在制作一个从(0,0)开始到我左键单击的星座,前一行应该在 2 秒延迟后消失。在 2 秒内,左键单击不会变成一条线,而是显示为白色圆圈。

现在我在代码上显示白色圆圈时遇到问题:

# left clicked lines were more than 1 & been less than 2 secs    
            if e.type == MOUSEBUTTONDOWN and time.get_ticks() - times <= 2000:   
                # Gets position of the mouse
                circleX, circleY = mouse.get_pos() 
                # the white circles appear 
                draw.circle (screen, WHITE, (circleX, circleY), 1)

标签: pythonwindowsloopsif-statementpygame

解决方案


您可以使用 pygames 事件机制并pygame.time.set_timer() 执行以下操作:

pygame.time.set_timer(pygame.USEREVENT, 2000)

然后在事件循环中查找事件类型。

if event.type == pygame.USEREVENT:

当您检测到该事件时,计时器已过期,您可以执行所需的操作。每当发生您想要延迟的事情时(例如左键单击),都可以设置一个新的计时器。

如果您需要多个计时器并需要将它们区分开来,您可以创建一个带有属性的事件,您可以将其设置为不同的值来跟踪它们。像这样的东西(虽然我没有运行这个特定的代码片段,所以可能有错字):

my_event = pygame.event.Event(pygame.USEREVENT, {"tracker": something})
pygame.time.set_timer(my_event , 2000)

推荐阅读