如何使用pygame.time.get_ticks()进行延迟而不影响用户输入

2024-06-03 02:10:28 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我制作了一个星座图,从(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)

Tags: the代码get地方left左键than消失
2条回答

您可以使用设置开始时间

start = pygame.time.get_ticks()

然后每一帧,检查是否有2秒

if pygame.time.get_ticks() - start > 2000:
    #been 2 seconds
    start = pygame.time.get_ticks() #reset the timer

您可以使用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)

相关问题 更多 >