【问题标题】:Pygame window freeze during large calculations in main loopPygame 窗口在主循环中的大型计算期间冻结
【发布时间】:2020-11-22 19:53:18
【问题描述】:

我有一个游戏,你要与 AI 对战。 pygame 的主循环如下所示:

def main():
    running = True
    while running:

        # Some code here.....

        if move_made == True:
            move = ai_make_move(gamestate)

这里的问题是ai_make_move() 需要大约 10-15 秒来计算。在此期间,pygame 窗口冻结,因为主循环在ai_make_move() 准备好之前不会更新。有没有办法在后台进行计算并保持主 pygame 循环以某种方式运行?这样我就可以例如在计算期间移动窗口。

【问题讨论】:

标签: python pygame


【解决方案1】:
import pygame
from pygame.locals import *
import threading
#your constants and more there
finished=True
def ai_make_move(args):
    global finished
    # do some stuff there
    finished=True
def main():
    global finished
    running=True
    while running:
        for event in pygame.event.get():
            if event.type == QUIT:
                running=False
        #do some stuff here
        if move_made and finished:
            thread=threading.Thread(target=lambda: ai_make_move(gamestate))
            thread.start()
            finished=False
        #also there
        pygame.display.update()

if __name__ == '__main__':
    main()

它允许您在 ai_make_move 函数工作时并行执行 pygame 代码

我不能保证它会起作用,只是你应该以某种方式更改你的代码(如果它不起作用)。我的意思是基地就在这里,但也许你应该在你的代码中改变一些东西来制作你想要的东西

希望我能帮到你!

【讨论】:

  • 谢谢。如何获取 ai_make_move 返回的变量?
  • 简单写var_name=ai_make_move(),但如果你的函数返回更多变量,你可以解压它们::var1, var,2,var3 (...) = ai_make_move()
猜你喜欢
  • 2020-03-26
  • 1970-01-01
  • 2017-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多