Search code examples
pythonpygamepython-3.7converters

How to load a large number of images in Pygame by a simple way?


I'm currently working on a game on Pygame. Recently, someone helped me to make my loading bar on this website (god, Rabbid76 is a genius). More seriously, I need to load all the pictures in my program so I've used the following code : ! (I've used 'picture' as a placeholder, in my real directory, it's 'hero_left0.png' or 'box.png' or 'Torch.png', and so on):

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

And I need to do this to fit any picture. Which means 350*2 elements, so 700 lines of code!

Is there a way to optimize this? All pictures are in the same folder name 'sprites'.


Solution

  • As I understand it you want to get all of your images loaded into your code. You should store all your image objects in a dict or some other structure. Do it something like this:

    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))
    

    This generates a dict of all the image objects as the values and the filenames as the keys. You can refer to each image: images[filename].

    Or if you wanted to be really concise about it then;

    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))
    

    NOTE: This will work only is all your filenames are valid python variable names, if not use something else as the keys of the dict or rename the ones that are not valid