我想在10秒钟后完成动画。为此,我将计时器添加到动画start_ticks = pygame.time.get_ticks()
中,并在for
循环seconds > max_simulation_time
中检查了此计时器。
但是,该窗口不会在10秒内关闭。仅当我在屏幕上移动鼠标时,它才会关闭。有点奇怪的行为。我究竟做错了什么? 如果可能很重要,我可以在Jupyter笔记本中运行代码。
class Environment():
def __init__(self, title):
pygame.init()
self.screen = pygame.display.set_mode((800, 800))
pygame.display.set_caption(title)
# ...
def run(self):
carryOn = True
max_simulation_time = 10
start_ticks = pygame.time.get_ticks()
while carryOn:
seconds=(pygame.time.get_ticks()-start_ticks)/1000
for event in pygame.event.get():
if (seconds > max_simulation_time):
carryOn = False
pygame.display.quit()
pygame.quit()
quit()
agent_action = 1
self.all_sprites.update(self.screen, agent_action)
self.screen.fill((0, 40, 0))
self.all_sprites.draw(self.screen)
pygame.display.flip()
if __name__ == "__main__":
env = Environment("TEST")
env.run()
还可以在10秒钟后break
动画并从头开始进行所有操作(进行重置)(不关闭窗口)吗?
更新:
如果我这样做:
class Environment():
def __init__(self, title):
pygame.init()
self.screen = pygame.display.set_mode((800, 800))
pygame.display.set_caption(title)
# ...
def run(self):
carryOn = True
max_simulation_time = 10
start_ticks = pygame.time.get_ticks()
while carryOn:
seconds=(pygame.time.get_ticks()-start_ticks)/1000
if (seconds > max_simulation_time):
carryOn = False
pygame.display.quit()
pygame.quit()
quit()
for event in pygame.event.get():
if (event.type == pygame.QUIT):
carryOn = False
pygame.display.quit()
pygame.quit()
quit()
# ...
if __name__ == "__main__":
env = Environment("TEST")
for epochs in range(1,3):
env.run()
<...>然后出现以下错误:
-------------------------------------------------------------------
error Traceback (most recent call last)
<ipython-input-1-102fa6124bbf> in <module>()
515 #env.run()
516 for epochs in range(1,3):
--> 517 env.run()
<ipython-input-1-102fa6124bbf> in run(self)
471 pygame.quit()
472 quit()
--> 473 for event in pygame.event.get():
474 if (event.type == pygame.QUIT):
475 carry_on = False
error: video system not initialized
答案 0 :(得分:3)
我认为这可能与检查是否仅在max_simulation_time
循环内超出了for event in pygame.event.get()
有关。
这就是为什么仅在移动鼠标时才会发生。在分支到for循环之前,请检查是否已超过该时间。
答案 1 :(得分:2)
要重新启动模拟,您只需创建一个Environment
的新实例并调用其run
方法。之所以出现error: video system not initialized
是因为您在调用pygame.quit()
之后会继续使用pygame函数(这会初始化所有模块)。您必须再次致电pygame.init()
以防止这种情况。
实际上没有必要调用pygame.display.quit()
,pygame.quit()
和quit()
(使用IDLE的人和其他基于tkinter的IDE除外),您可以让Python与其他任何游戏一样关闭游戏在while循环结束后编写程序。
class Environment:
def __init__(self, title):
pygame.init()
self.screen = pygame.display.set_mode((800, 800))
pygame.display.set_caption(title)
# ...
def run(self):
carryOn = True
max_simulation_time = 10
start_ticks = pygame.time.get_ticks()
while carryOn:
seconds = (pygame.time.get_ticks()-start_ticks) / 1000
if seconds > max_simulation_time:
carryOn = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
carryOn = False
# ...
if __name__ == "__main__":
for epochs in range(1,3):
Environment("TEST").run()
如果您不想创建新实例,还可以为Environment
类提供一个reset
方法,您可以在其中重新设置所有相关属性,然后在模拟时间到时调用它上。