Python Pygame随机迷宫生成程序运行时退出按钮无响应解决求助
问题根因
核心问题是程序执行迷宫生成、路径展示、休眠逻辑时阻塞了Pygame的事件队列处理,导致退出按钮的点击事件无法被捕获响应,具体问题点如下:
start()函数逻辑顺序错误,将迷宫生成逻辑放在事件循环内部,执行后会长时间阻塞,无法回到事件处理逻辑mazemaker()、solutionroute()函数中的sleep()调用会直接阻塞整个程序线程,期间完全不处理任何UI事件- 迷宫生成和路径展示的全流程没有插入事件检查逻辑,用户点击操作无法被响应
修复方案
第一步:新增公共事件检查函数
新增通用的退出事件检查函数,所有可能阻塞的流程中都调用该函数处理事件、检查退出操作:
def check_quit_event(): for ev in pygame.event.get(): # 处理窗口关闭按钮 if ev.type == pygame.QUIT: pygame.quit() sys.exit() # 处理右下角退出按钮点击 if ev.type == pygame.MOUSEBUTTONDOWN: mouse = pygame.mouse.get_pos() if 300 <= mouse[0] <= 440 and 425 <= mouse[1] <= 445: pygame.quit() sys.exit()
第二步:修改迷宫生成函数mazemaker()
在每次循环中加入事件检查,同时保留动画延迟逻辑:
def mazemaker(x,y): visited.append((x,y)) cellstack.append((x,y)) while len(cellstack) > 0: # 每次循环先检查退出事件 check_quit_event() pygame.time.delay(50) pickmovecell = [] if (x+w,y) not in visited and (x+w,y) in cell_list: pickmovecell.append("right") if (x-w,y) not in visited and (x-w,y) in cell_list: pickmovecell.append("left") if (x,y-w) not in visited and (x,y-w) in cell_list: pickmovecell.append("up") if (x,y+w) not in visited and (x,y+w) in cell_list: pickmovecell.append("down") if len(pickmovecell) > 0: choice = randint(0,len(pickmovecell)-1) directionmove = pickmovecell[choice] if directionmove == "up": solution[x,y-w] = x,y moveup(x,y) y = y-w visited.append((x,y)) cellstack.append((x,y)) elif directionmove == "down": solution[x,y+w] = x,y movedown(x,y) y = y+w visited.append((x,y)) cellstack.append((x,y)) elif directionmove == "left": solution[x-w,y] = x,y moveleft(x,y) x = x-w visited.append((x,y)) cellstack.append((x,y)) elif directionmove == "right": solution[x+w,y] = x,y moveright(x,y) x = x+w visited.append((x,y)) cellstack.append((x,y)) else: x,y = cellstack.pop() singlecell(x,y) pygame.time.delay(40) backtrack(x,y)
第三步:修改路径展示函数solutionroute()
同样加入事件检查逻辑:
def solutionroute(x,y): solutionchange(x,y) while (x,y) != (20,20): check_quit_event() x,y = solution[x,y] solutionchange(x,y) pygame.time.delay(100)
第四步:修改start()函数逻辑
调整逻辑顺序,迷宫只生成一次,后续循环等待期间持续处理事件:
def start(): SCREEN = pygame.display.set_mode((width,height)) SCREEN.fill(black) smallfont = pygame.font.SysFont('Corbel',25) quittext = smallfont.render("Quit",True,white) # 仅生成一次迷宫 x,y = 20,20 drawgrid(40,0,20) mazemaker(x,y) solutionroute(400,400) # 记录结束时间,等待30秒返回菜单 end_time = pygame.time.get_ticks() + 30000 while True: check_quit_event() # 30秒到了返回菜单 if pygame.time.get_ticks() >= end_time: menu() # 绘制退出按钮 mouse = pygame.mouse.get_pos() if 300 <= mouse[0] <= 440 and 425 <= mouse[1] <= 445: pygame.draw.rect(SCREEN,lightgrey,[300,425,140,20]) else: pygame.draw.rect(SCREEN,darkgrey,[300,425,140,20]) SCREEN.blit(quittext , (350,425)) pygame.display.update() pygame.time.delay(10)
第五步:修复代码中的HTML转义字符
把原代码里所有的>替换为>,"替换为"即可。
修改后程序在迷宫生成、路径展示、等待返回菜单的全流程中,都会持续检查用户的退出操作,点击右下角退出按钮可以随时终止程序运行。
内容的提问来源于stack exchange,提问作者kaneaston
相关产品推荐
相关产品推荐

