首页 > 解决方案 > 退出算法pygame无法正常工作

问题描述

在此我希望程序在他们按下退出按钮时关闭,但如果我启用我的Check_Key_Press()功能,该Close()功能将不起作用但是如果我注释掉该Check_Key_Press()功能,那么它会再次起作用。

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

标签: pythonpygame

解决方案


pygame.event.get()获取所有消息并将它们从队列中删除。如果pygame.event.get ()在多个事件循环中调用,则只有一个循环接收事件,但绝不会所有循环都接收所有事件。结果,似乎错过了一些事件。

获取事件一次并在多个循环中使用它们,或者将列表或事件传递给处理它们的函数和方法:

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

推荐阅读