Search code examples
pythonpygame

Quit Algorithm pygame Not working properly


In this I want the program to close when they hit the quit button but if I enable my Check_Key_Press() function, the Close() function does not work however If I comment out the Check_Key_Press() function then it works again.

import pygame

pygame.init()
width, height = 500,500
win = pygame.display.set_mode((width, height))
pygame.display.set_caption("Tic Tac Toe(GUI)")
clock = pygame.time.Clock()

white = (255,255,255)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)

Tile_dime = 59
Diff = (Tile_dime+1)/2
board_det = [['-',(width/2-3*Diff,height/2-3*Diff)],['-',(width/2-Diff,height/2-3*Diff)],['-',(width/2+Diff,height/2-3*Diff)],
            ['-',(width/2-3*Diff,height/2-Diff)],['-',(width/2-Diff,height/2-Diff)],['-',(width/2+Diff,height/2-Diff)],
            ['-',(width/2-3*Diff,height/2+Diff)],['-',(width/2-Diff,height/2+Diff)],['-',(width/2+Diff,height/2+Diff)]]

def draw_board():
    for i in range(len(board_det)):
        pygame.draw.rect(win, white, [board_det[i][1], (Tile_dime, Tile_dime)])

def Close():
    global run
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

def Check_Key_Press():
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            pass
            if event.key == pygame.K_LEFT:
                pass

run = True
while run:
    clock.tick(60)
    draw_board()
    Check_Key_Press()
    Close()
    pygame.display.update()

Solution

  • pygame.event.get() get all the messages and remove them from the queue. If pygame.event.get () is called in multiple event loops, only one loop receives the events, but never all loops receive all events. As a result, some events appear to be missed.

    Get the events once and use them in multiple loops or pass the list or events to functions and methods where they are handled:

    def Close(event_list):
        global run
        for event in event_list:
            if event.type == pygame.QUIT:
                run = False
    
    def Check_Key_Press(event_list):
        for event in event_list:
            if event.type == pygame.KEYDOWN:
                pass
                if event.key == pygame.K_LEFT:
                    pass
    
    run = True
    while run:
        clock.tick(60)
        event_list = pygame.event.get()
        draw_board()
        Check_Key_Press(event_list)
        Close(event_list)
        pygame.display.update()