python - Python 线程在 PyGame 中的资产加载时崩溃
问题描述
我已经构建了一些代码来将资产加载到字符类中。这在单个线程中工作正常,但我希望在加载资产时有一个加载屏幕。
我把资产加载到一个函数中,并试图让它在一个单独的线程中运行。问题是它现在挂起,似乎甚至没有执行主线程。
我一直关注内存使用情况,并且内存表现良好(从 1976M 中永远不会超过 500M,位或字节我不确定,这是 PyCharm 报告的任何内容)。
import threading
import os
import pygame
from pygame.locals import *
def load_assets(screen: pygame.Surface, results: List):
print("thread: started to load assets in thread")
appearances1 = {} # some dictionary, Dict[str, Dict[str, str]]
default_outfit = "office_wear"
print("thread: instance of game class to be created")
game = Game("lmao", screen) # crashes somewhere here when running multithreaded
print("thread: game initialized") # this is never achieved
# rest of function not relevant
results.append(game)
def main():
# ====== INITIALIZE PYGAME ======
pygame.init()
pygame.font.init()
screen = pygame.display.set_mode((1024, 768))
clock = pygame.time.Clock()
loading = create_loading_screen(screen)
loading.display(screen)
pygame.display.flip()
# ====== START OTHER THREAD FOR LOADING ASSETS ======
results = []
x = threading.Thread(
target=load_assets, args=(screen, results), daemon=True
)
x.start()
while x.is_alive():
# never see this print statement!
print("x is fine") # want to blit loading screen here
# if I comment out the threading, and run the following instead, my game boots up just fine
# in under 3-4 seconds of waiting for the assets to load
# load_assets(screen, results)
game = results[0]
# other code here to render the game, no more threading after this point
while 1:
for event in pygame.event.get():
if event.type == QUIT:
return -1
game.main()
pygame.display.flip()
clock.tick(game.fps)
if __name__ == '__main__':
main()
解决方案
我弄清楚了这个问题。我现在感觉真的很愚蠢......问题是我的游戏初始化程序正在触摸 pygame.display() 我已经知道它不应该......我需要小睡......
推荐阅读
- firebase - 有条件地在反应导航 v5 中为身份验证流选择屏幕而不更新
- sql - 将脚本视为动态的
- android - 由于 android 目标,Kotlin Multiplatform 构建失败
- python - NotADirectoryError: [WinError 267] Nom de répertoire non valide:
- javascript - 如何使用 ramda 表达式编辑数组内的对象?
- r - 识别序列变化中的第一行,以便在 r 中的另一个变量中找到滞后值
- node.js - cordova 将文件集成到项目中
- r - 根据两列中的值从两个现有数据框创建新数据框
- typescript - 打字稿找不到条带模块
- javascript - 如何在管理员批准的情况下访问 Firestore 数据库中的所有数据?