我似乎真的卡在了我程序的某个点上,希望你能提供帮助。
我基本上是在尝试创建一个简单的热门移动图像游戏。图像随机放置在一系列“向上点”中的一个,然后玩家需要在图像放置到新位置之前击中图像。
一切似乎都很顺利,但我似乎遇到了 pygame.tick 或 python time.sleep() 的奇怪延迟。
我只想说我是一个 python 和 pygame 新手,但我无法理解哪里出了问题。到目前为止,根据我的理解,图像应该以 1 秒的间隔定期移动到新位置。
但相反,程序有时似乎“挂起”或“延迟”,并且图像似乎停留在原地几秒钟然后来回奔波,好像试图 catch 一样,然后程序似乎可以正常工作几秒钟似乎还好(通常延迟 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)
如果我使用 time.sleep,游戏会以 1 秒间隔的正确速度运行。如果我省略 time.sleep() 并使用 .tick(60),图像会疯狂闪烁,但我确信我仍然可以看到某种延迟。
我试着做了一些谷歌搜索,发现有几页说 pygame 的 .tick() 方法和 python sleep() 方法都有问题,但无法确定这是不是真的。
老实说,我不知道我在这里做错了什么,所以希望你能帮忙:)
非常感谢!
请您参考如下方法:
您的 time.sleep 和 fpsclock.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)
# ...
