在运行主循环时读取tmx文件(用于pygame)



所以我正在用pygame制作一个游戏,我有一些相当大的tmx文件用于地图数据。我想知道是否有A,一种加快速度的方法,或者B,我是否可以同时运行主循环并加载映射。这样我就可以有一个加载屏幕。我试过使用多处理,但它说它不能抓取pygame对象。谢谢

您的代码可以在线程中加载TMX映射。这将允许主循环等待"已完成加载"事件,并在等待时执行其他操作。

下面的示例代码使用pytmx库。通常需要更多的代码来将地图渲染成图像,但为了缩短答案,我省略了这一点。也许在加载过程中还可以发布更多的状态信息事件。这将允许主循环显示进度指示器等。

显然,这个示例除了将窗口填充为蓝色之外,对窗口没有任何作用。

import pygame
import threading
import pytmx
WINDOW_WIDTH    = 400
WINDOW_HEIGHT   = 400
WINDOW_SURFACE  = pygame.HWSURFACE|pygame.DOUBLEBUF|pygame.RESIZABLE
DARK_BLUE = (   3,   5,  54 )
CREAM     = ( 255, 254, 224 )
MAP_LOAD_DONE  = pygame.USEREVENT + 1
MAP_LOAD_ERROR = pygame.USEREVENT + 2
# global to hold map
global_tmx_map = None
# Thread function to load map in the background
class MapLoadThread( threading.Thread ):
def __init__( self, map_name ):
threading.Thread.__init__(self)
self.daemon = True # exit with parent
self.map_name = map_name
def run( self ):
global global_tmx_map
new_event_args = {}
try:
global_tmx_map = pytmx.load_pygame( self.map_name, pixelalpha=True )
# TODO: do more TMX operations in the thread here.
new_event      = pygame.event.Event( MAP_LOAD_DONE, new_event_args )
except Exception as e:
new_event_args[ 'exception' ] = e
new_event = pygame.event.Event( MAP_LOAD_ERROR, new_event_args )
# send the load/fail event to the main loop
pygame.event.post( new_event )
# ...
### Window initialisation
pygame.init()
pygame.mixer.init()
window = pygame.display.set_mode( ( WINDOW_WIDTH, WINDOW_HEIGHT ), WINDOW_SURFACE )
pygame.display.set_caption( "TMX Loader Thread Example" )
# Start the Map Loading thread
thread1 = MapLoadThread( "my_map.tmx" )
thread1.start()

### Main Loop
clock = pygame.time.Clock()
done = False
while not done:
# Handle user-input
for event in pygame.event.get():
if ( event.type == pygame.QUIT ):
done = True
elif ( event.type == MAP_LOAD_DONE ):
print( "MAP LOADED OK" );
elif ( event.type == MAP_LOAD_ERROR ):
print( "MAP LOAD FAILED" );
print( "EXCEPTION WAS " + str( event.exception ) )
# Update the window, but not more than 60 FPS
window.fill( DARK_BLUE )
pygame.display.flip()
# Clamp FPS
clock.tick_busy_loop(60)
pygame.quit()

相关内容

  • 没有找到相关文章