如何通过一个简单的方式来加载大量Pygame的图像?

问题描述 投票:0回答:1

我目前正在对pygame的游戏。最近,有人帮助我,使我的加载条本网站(神,Rabbid76是个天才)上。更为严重的是,我需要所以我用下面的代码加载所有的照片在我的计划! (我用“图像”作为一个占位符,在我真正的目录,它的“hero_left0.png”或“box.png”或“Torch.png”,等):

Image=picture.image.load(sprite/picture.png).convert_alpha
bar_load=bar_load - 1

我需要这样做,以适应任何图片。这意味着350 * 2元,所以700行代码!

有没有办法来优化呢?所有的图片都在同一个文件夹名“精灵”。

python pygame python-3.7 converters
1个回答
1
投票

据我了解,你想获得的所有加载到你的代码的图像。你应该存储在一个字典或一些其他结构中的所有图像对象。做这样的事情:

import os

# If using windows make sure to convert all the '\' in the path to '/'
# like so: sprites_folder_path.replace('\', '/')
sprites_folder_path = 'path_to_sprites_folder'
# Make sure there is a '/' at the end of the path 

def image_loader(path) -> str:
    for i in os.listdir(path):
        yield (os.path.splitext(i)[0]),
               picture.image.load(path + i).concert_alpha)


images = dict(image_loader(sprite_folder_ path))

这产生所有的图像对象作为值和文件名作为密钥的一个字典。你可以参考每个图像:images[filename].

或者,如果你想成为真正的简洁一下即可;

def image_loader(path) -> str:
    return dict((os.path.splitext(i)[0]), picture.image.load(path + i).concert_alpha) for i in os.listdir(path))

注意:这种方法仅是所有的文件名是有效的Python变量名,如果不是用别的东西作为字典的键或重命名无效的那些

© www.soinside.com 2019 - 2024. All rights reserved.