[英]Pygame window freeze during large calculations in main loop
我有一款游戲,您可以與 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 循環以某種方式運行? 這樣我就可以在計算期間移動窗口。
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 代碼
我不能保證它有效,但只能保證您應該以某種方式更改您的代碼(如果它不起作用)。 我的意思是基礎就在這里,但也許您應該更改代碼中的某些內容以制作您想要的內容
希望我能幫到你!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.