pygame.time.set_定时器混乱?

2024-06-06 18:02:23 发布

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

所以,我有一个问题,我不完全理解需要给计时器命令的事件,不管怎样,它没有说任何在线的地方,也没有说我搜索了几个小时的地方。所以我使用了大多数人似乎使用的“USEREVENT+1”。我不确定它是否正确,但我的计时器不工作。我用对了吗?这是我的代码:

nyansecond=462346
nyanint=0
spin=0
aftin=452345

def nyanmusic(nyansecond,nyanint,spin):
    if nyanint == 0:
        nyansound.play()
        nyanint= 1
    elif nyanint == 1:
        nyansecond = pygame.time.set_timer(USEREVENT+1,7000)
    if nyansecond < 200 and spin == 1:
        spin = 0
        nyansecond = pygame.time.set_timer(USEREVENT+1,7000)
    elif nyansecond > 6500 and nyansecond < 100000 and spin == 0:
        spin = 1
        nyansoundm.play()

    return nyansecond,nyanint,spin

然后,我在实现的第二页将其定义为我的代码(工作正常)。它运行nyansound,但在6.5秒(6500毫秒)后不运行nyansoundm。我制作这个程序是为了帮助我学习python和pygame的基础知识,然后再继续学习更复杂的东西。我也可以使用它,当我想听尼安猫或其他循环歌曲,而不必上youtube和浪费宝贵的带宽。不过,别担心。

哦,这是我放入循环中的代码,尽管我认为这并不太重要:

#music
        nyansecond,nyanint,spin = nyanmusic(nyansecond,nyanint,spin)

Tags: and代码playiftime地方pygame计时器
1条回答
网友
1楼 · 发布于 2024-06-06 18:02:23

让我们回顾一下^{}的作用:

pygame.time.set_timer(eventid, milliseconds): return None

Set an event type to appear on the event queue every given number of milliseconds. The first event will not appear until the amount of time has passed.
Every event type can have a separate timer attached to it. It is best to use the value between pygame.USEREVENT and pygame.NUMEVENTS.

pygame.USEREVENTpygame.NUMEVENTS是常量(2432),因此传递给pygame.time.set_timer的参数eventid应该是2432之间的任何整数。

pygame.USEREVENT+125,所以可以使用。

当您调用pygame.time.set_timer(USEREVENT+1,7000)时,eventid为25的事件将每隔7000毫秒出现在事件队列中。您没有显示事件处理代码,但我想您没有检查此事件,您应该这样做。

如您所见,pygame.time.set_timer返回None,因此您的行

nyansecond = pygame.time.set_timer(USEREVENT+1,7000)

没有意义,因为nyansecond始终是None,因此将其与整数进行比较

if nyansecond < 200 ...

毫无意义。


如果要使用事件队列每6.5秒播放一次声音,请简单调用pygame.time.set_timer一次(!)以下内容:

PLAYSOUNDEVENT = USEREVENT + 1
...
pygame.time.set_timer(PLAYSOUNDEVENT, 6500)

并在主循环中检查此事件的事件队列:

while whatever: # main loop
    ...
    # event handling
    if pygame.event.get(PLAYSOUNDEVENT): # check event queue contains PLAYSOUNDEVENT 
        nyansoundm.play() # play the sound

相关问题 更多 >