Pygame项目:buy函数无法更新屏幕,in_city等函数功能正常
Pygame中buy函数屏幕不更新的解决方法
问题原因分析
- 屏幕对象不一致:
in_city函数中直接使用screen变量,而buy函数中使用self.screen,若两者指向不同的Pygame表面对象,buy中的绘制操作无法显示到窗口上。 - 重复的显示更新调用:
buy中同时调用pygame.display.update()和pygame.display.flip(),这两个方法均用于更新屏幕显示,重复调用可能导致异常。 - QUIT事件处理不完整:
buy中触发QUIT事件时仅设置self.running = False,未主动退出循环,可能导致程序卡死。
修复步骤
1. 统一屏幕对象引用
将in_city函数中所有screen替换为self.screen,确保和buy函数操作同一个窗口表面:
def in_city(self): while self.running: stop = False for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False if event.type == pygame.MOUSEMOTION: all_sprites.update(pygame.mouse.get_pos()) if event.type == pygame.MOUSEBUTTONDOWN: mouse_pos = pygame.mouse.get_pos() button_right.click(mouse_pos) button_left.click(mouse_pos) button_next.click(mouse_pos) button_prev.click(mouse_pos) if button_close.on_button(mouse_pos): stop = True if event.type == pygame.KEYDOWN: self.buy() if stop: self.player.route = [(0, 0)] self.player.next_move(self.maps) self.camera.update(self.player) return self.screen.fill('WHITE') city.render(self.screen) current_text = city.enemies[city.current_enemy] window.show(self.screen, current_text.get_text()) print(current_text.goods) all_sprites.draw(self.screen) pygame.display.flip()
2. 简化buy函数的显示更新逻辑
去掉重复的pygame.display.update(),仅保留一个屏幕更新方法,同时完善QUIT事件的退出逻辑:
def buy(self): while self.running: for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False return # 触发退出时直接跳出buy循环 if event.type == pygame.KEYDOWN: return self.screen.fill('BLACK') pygame.display.flip()
额外优化建议
- 避免嵌套事件循环(
in_city调用buy形成嵌套),可以用状态机管理游戏状态(比如self.game_state = 'in_city'或'buy'),在主循环中根据状态执行对应逻辑,更易维护。 - 尽量减少全局变量使用,统一通过实例属性(如
self.screen)访问游戏资源。
内容的提问来源于stack exchange,提问作者Chingis Bagdatov
相关产品推荐
相关产品推荐

