2

I'm trying to load all these images at once. Their all in the same directory so is there a way to load them all at once without being this repetitive?

bg = pygame.image.load('Desktop/Files/Dungeon Minigame/background.png')
f_zombie = pygame.image.load('Desktop/Files/Dungeon Minigame/f_zombie.png')
f_knight = pygame.image.load('Desktop/Files/Dungeon Minigame/f_knight.png')
b_knight = pygame.image.load('Desktop/Files/Dungeon Minigame/b_knight.png')
r_knight = pygame.image.load('Desktop/Files/Dungeon Minigame/r_knight.png')
heart = pygame.image.load('Desktop/Files/Dungeon Minigame/heart.png')
empty_heart = pygame.image.load('Desktop/Files/Dungeon Minigame/empty_heart.png')
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
Zelda
  • 39
  • 4

1 Answers1

1

Get a list of all the files in the directory (see os) and create a dictionary with the loaded files:

import os
path = 'Desktop/Files/Dungeon Minigame/'
filenames = [f for f in os.listdir(path) if f.endswith('.png')]
images = {}
for name in filenames:
    imagename = os.path.splitext(name)[0] 
    images[imagename] = pygame.image.load(os.path.join(path, name)).convert_alpha()

You can access the images in the dictionary by its name:

screen.blit(images['background'], (0, 0))

Alternatively you can add variables to global namespace, using globals():

path = 'Desktop/Files/Dungeon Minigame/'
filenames = [f for f in os.listdir(path) if f.endswith('.png')]
for name in filenames:
    imagename = os.path.splitext(name)[0] 
    globals()[imagename] =  pygame.image.load(os.path.join(path, name)).convert_alpha()
screen.blit(background, (0, 0))
Rabbid76
  • 202,892
  • 27
  • 131
  • 174