Pygame main loop求ting exception handling

Pygame mainloop qiuting exception handling

您好,我正在编写一个简单的国际象棋程序,不幸的是我 运行 遇到了一些意想不到的问题,即。在我添加了一个跟踪所有图形位置的列表之后,我无法使用我现在使用的方法关闭 window。这是:

  for event in pygame.event.get():
    # print(event)
    # Checking if the user clicks the red quit cross
    if event.type == pygame.QUIT:
        # run control the mainloop, wheather True or not 
        run = False

添加列表后,它停止工作,所以我现在使用:

for event in pygame.event.get():
    # print(event)
    if event.type == pygame.QUIT:
        pygame.display.quit()
        pygame.quit()

我尝试添加一些异常处理:

try:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.display.quit()
except pygame.error():
    print('Program closed')

但是没有到达except语句并打印错误:(pygame.error:视频系统未初始化)

你能告诉我如何正确处理这个异常,或者建议一种不同的方法来阻止主循环。

去掉异常捕获中的(),即: except pygame.error 而不是 except pygame.error()

我实际上是自己想出来的,以防万一有人在寻找答案。问题是我试图在 pygame.display.quit() 之后调用重绘函数。因此,在移动重绘调用和键 = pygame.key.get_pressed() [也使用模块 pygame] 之后,程序终止而没有任何错误调用。代码应如下所示:

while run:
    pygame.time.delay(100)
    window_redrawing()

    # Gathering user keyboard input
    keys = pygame.key.get_pressed()

    # making sure the window can be closed
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.display.quit()
            run = False

    fig_pos.clear()