python - 退出算法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()
解决方案
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()
推荐阅读
- gcc - 短路评估是 C/C++ 或编译器实现中的语言特性吗
- python - Pandas 数据框 - 将具有多个元素的时间序列转换为以元素为列的扁平数据框
- python - 创建一个示例计时器并受到 TypeError 的欢迎
- reactjs - reactjs中的子类组件是如何调用的。谁能告诉我以下程序的流程
- mongodb - 使用 $pull 和 $cond 运算符从数组中删除元素
- javascript - 如何从 Node.js 应用程序连接 AWS elasticache redis?
- webrtc - WebRTC:有多个轨道(或流)并在另一侧识别它们
- powershell - 移动基于今天日期创建的文件 - powershell
- r - 在R中使用igraph绘制谱系/家谱
- minecraft-forge - forge 在启动时不断崩溃