gpt4 book ai didi

python - 停止时间而不卡住程序

转载 作者:太空宇宙 更新时间:2023-11-04 03:55:01 27 4
gpt4 key购买 nike

在我的乒乓球游戏中,每当有人得分(球向左或向右出)时,球的位置都会重置到屏幕中间,并等待一秒钟再移动。在那一秒钟里,我有一个小动画在进行。

我的问题是:如果我在动画中间暂停游戏,即使没有任何对象更新并且只绘制了暂停文本,时间也会继续滚动。如果我等待的时间够长,在我取消暂停游戏后动画就停止了。这就是我的意思。这是球更新:

def update(self, dt):
now = pygame.time.get_ticks() / 1000
# if time elapsed since the ball got out >= BALL_WAIT_TIME
if now - self._spawn_time >= BALL_WAIT_TIME:
self.rect = self.calcnewpos(dt)
self.handle_collision()
# spawn animation
else:
step = 255 / (FPS * BALL_WAIT_TIME)
value = int(self._frame * step)
rgb = (value, value, value)
self._draw_ball(rgb)
self._frame += 1

来自 http://pygame.org/docs/ref/time.html#pygame.time.get_ticks :

pygame.time.get_ticks()

Return the number of millisconds since pygame.init() was called. Before pygame is initialized this will always be 0.

因此,即使在游戏暂停时没有绘制或更新任何内容,pygame.time.get_ticks() 仍会返回自 pygame.init 以来耗时。我该如何解决这个问题?抱歉,如果这有点难以理解,我会在需要时发布其余代码。

最佳答案

好吧,看起来您只是从当前时间中减去某个事件发生的时间。如果这是您检查事件发生后经过了多长时间的方法,那么游戏是否已暂停都无关紧要。如果事件发生后您将游戏暂停 10 分钟,则事件发生后始终是 10 分钟。

考虑到这一点,您需要一些方法来仅在游戏处于事件状态时计算时间。也许球可以有一个属性,说明球离开后经过了多长时间,并且只有在游戏没有暂停时才增加它。

编辑:类似于:

class Ball:
def spawn(self):
self.sinceSpawn = 0

def update(self, dt):
if not gamePaused:
self.sinceSpawn += dt
if self.sinceSpawn >= BALL_WAIT_TIME:
pass #Do something here

关于python - 停止时间而不卡住程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19091820/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com