Search code examples
pythonexceptionpygamemainloop

Pygame mainloop qiuting exception handling


Hi I am writing a simple chess program, unfortunately I have run in some unexpected problems, namely. After I added a list which keeps track of all the figures positions, I cannot close the window using the method which I till now used. which was:

  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

After adding the list, this stopped working, so I use now:

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

I tried to add some exception handling:

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

However the except statement is not reached and an error is printed: (pygame.error: video system not initialized)

Can You please tell me how to handle this exception properly, or suggest a different way of braking the mainloop.


Solution

  • I acctually figured it out on my own, so just in case someone is looking for the anwser. The issue was that I was trying to call the redraw function after pygame.display.quit(). Thus after moving both the redraw call and the keys = pygame.key.get_pressed() [wich also utilises the module pygame] the program terminates without any error call. The code should look as follows:

    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()