python - pygame.display.update() 在线程上无法正常工作
问题描述
我正在用 pygame 为我的学校项目制作游戏。我想使用另一个线程(不包括主线程)运行pygame.display.update()
来更新我的游戏屏幕。
这是代码:
def display_update():
while running: # running is declared before as True for the game loop
pygame.display.update()
dis = Thread(target=display_update)
dis.start()
但是,代码运行后,屏幕中的图像会闪烁。
解决方案
你不应该使用这样的线程,因为 pygame 可以很容易地在主线程中更新,并且使用带有 pygame 的线程可能会导致未定义的行为
问题是线程没有同步。如果绝对有必要使用线程,那么这样的事情应该可以工作:
running = True
do_update = False
def display_update():
while running: # running is declared before as True for the game loop
if do_update:
pygame.display.update()
do_update = False
dis = Thread(target=display_update)
dis.start()
while running:
if not do_update:
#Code
#Code
#Code
do_update = True
display_update
这基本上会在更新屏幕时停止主线程。
对此进行编码的更好方法是:
while running:
#Code
#Code
#Code
pygame.display.update()
推荐阅读
- powershell - 通过调用变量初始化谷歌浏览器
- angular - 如何将相同的表单控件名称用于角度的多个下拉列表
- sql - 将数据从一个表移动到另一个表,同时在不存在相应行时创建条目
- java - 如何使用@autowired在springboot中做一个简单的“失败”主?
- c - 有没有办法在不使用 strupr 函数的情况下以大写字母打印所有字符串,因为它不是标准库函数?
- java - 如何向按钮添加新位置?
- visual-studio - 每次我在 Visual Studio [2019] [NuGet] 中重建项目时如何关闭 DocFX 构建
- python - 如何在 python-twitter 中获取数据
- r - 用脚注中的特殊字符在 kable 中创建表格
- amazon-web-services - 使用 Lambda 在 AWS 中自动轮换密钥和访问密钥