首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Pygame窗口在主循环中进行大型计算时冻结

Pygame窗口在主循环中进行大型计算时冻结
EN

Stack Overflow用户
提问于 2020-11-22 18:21:36
回答 1查看 65关注 0票数 0

我有一个游戏,你和一个AI对战。主要的pygame循环看起来像这样:

代码语言:javascript
运行
复制
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循环运行?这样我就可以在计算期间移动窗口。

EN

回答 1

Stack Overflow用户

发布于 2020-11-22 19:53:18

代码语言:javascript
运行
复制
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代码

我不能保证它能工作,但只能说你应该以某种方式改变你的代码(如果它不能工作)。我的意思是基础在这里,但是也许你应该在你的代码中改变一些东西来实现你想要的。

希望我能帮到你!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64952998

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档