Python Pygame循环异常延迟

2024-05-14 18:34:22 发布

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

我似乎真的被困在我的程序的某个点上,希望你能帮助我。你知道吗

我基本上是想创造一个简单的击中移动图像游戏。图像被随机放置在一系列“上升点”中的一个,然后玩家需要在图像被放置到新位置之前点击图像。你知道吗

一切似乎都很顺利,但我似乎有一个奇怪的延迟pygame.tick公司或者Python时间。睡眠(). 你知道吗

我只想说我是一个相当的python和pygame新手,但对于我的生活不能理解什么是错的。根据我目前的理解,图像应该每隔1秒移动到新的位置。你知道吗

但相反,程序有时似乎“挂起”或“被延迟”,图像似乎停留在原地好几秒钟,然后来回奔波,好像在努力追赶,然后程序似乎会工作几秒钟(正常的1秒延迟),然后回到努力移动或跟上。你知道吗

希望这是有道理的:) 她的代码带有循环,所以你可以看到我认为我有问题的地方:

# The values are tuples which hold the top-left x, y co-ordinates at which the  
# rabbit image is to be blitted...

uppoints = {1: (70, 70), 2: (250, 70), 3: (430, 70), 4: (600, 70),
        5: (70, 250), 6: (250, 250), 7: (430, 250), 8: (600, 250),
        9: (70, 430), 10: (250, 430), 11: (430, 430), 12: (600, 430)}


# Get a random location to pop up...
def getpos(ups):
    x = random.randint(1, 2)
    if x == 1:
        up = ups[1]
        return up
    elif x == 2:
        up = ups[2]
        return up

uppos = ()

while gamerunning:
    uppos = getpos(uppoints)

        for event in pygame.event.get():
            if event.type == QUIT:
            gamerunning = False

            if event.type == pygame.MOUSEMOTION:
                mpos = pygame.mouse.get_pos()

            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:
                    if rabbits.rect.collidepoint(event.pos):
                        score += 10

    mainwin.fill((0, 0, 0))
    scoretxt2 = basefont.render(str(score), True, (0, 0, 0))
    mainwin.blit(mainback, (0, 0))
    mainwin.blit(rabbits.image, uppos)
    mainwin.blit(scoretxt, (70, 30))
    mainwin.blit(scoretxt2, (160, 32))
    mainwin.blit(livestxt, (600, 30))
    mainwin.blit(livestxt2, (690, 32))

    pygame.display.flip()

    time.sleep(1)

    # Check which level the user is by score, and increase the speed of the rabbits  as needed...
    fpsclock.tick(60)

如果我使用时间。睡眠,游戏运行的速度似乎是正确的,每1s一次。如果我同意的话时间。睡眠()并使用.tick(60),图像会疯狂地闪烁,但我相信我仍然可以看到某种延迟。你知道吗

我试着在google上搜索了一下,发现有几页说pygame的.tick()方法和python sleep()方法都有问题,但没有发现这是不是真的。你知道吗

我真的不知道我做错了什么,所以希望你能帮我:)

多谢了!你知道吗


Tags: the图像程序eventwhichiftype时间
1条回答
网友
1楼 · 发布于 2024-05-14 18:34:22

你的time.sleepfpsclock.tick调用有些矛盾。对sleep的调用告诉Python停止整整一秒钟,什么也不做。另一方面,tick调用表示您希望以每秒60帧的速度运行。你知道吗

我怀疑您不想使用sleep。当程序处于休眠状态时,不会处理IO事件,程序将显示为挂起。相反,您需要更改代码的其余部分,以便它在每秒更新一次以上时正常运行。你知道吗

我想你可能想把你叫getpos的地方改成一秒钟只叫一次。我建议如下:

ms = 0

while gamerunning:
    ms += fpsclock.get_time()
    if ms > 1000: # 1000 ms is one second
        ms -= 1000
        uppos = getpos(uppoints)

    # ...

相关问题 更多 >

    热门问题