简体   繁体   English

如何在PyGame中加载多个图像?

[英]How to load multiple images in PyGame?

I need to load around 200 images in pygame to be blitted at various points in my game. 我需要在pygame中加载大约200张图片,以便在游戏中的各个阶段被遮住。 I tried writing a function for this but kept coming back with NameError: name 'tomato' is not defined . 我尝试为此编写一个函数,但始终返回NameError: name 'tomato' is not defined

All of the image names are what the variable of the loaded image is stored under: tomato = pygame.image.load("tomato.png") 所有图像名称都是所加载图像的变量所存储的名称: tomato = pygame.image.load("tomato.png")

Would using an array be better, if so how would I do that? 使用数组会更好,如果可以的话我该怎么做?

The code: 编码:

def load(image):
    imagename = image
    imagetitle = str(imagename)+".png"
    image = pygame.image.load(imagetitle)
    return image

load("tomato")

def blit_f(fruit):
    gamedisplay.blit(fruit,(0,0))
    pygame.display.update()

fruitlist = []        

running = False
while not running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = True

        if event.type == pygame.MOUSEMOTION:
            mouse = pygame.mouse.get_pos()
            color = screen.get_at(mouse)

            if color == (209,0,0,255):
                blit_f(tomato)
                fruitlist.insert(0,"tomato")

        if event.type == pygame.MOUSEBUTTONDOWN:

            if fruitlist[0] == "tomato":
                gamedisplay.blit(tomato,(0,0))
                pygame.display.update()

The NameError occurs only when the condition leading to the blitting of tomato.png is met: when I hover over the tomato image ie color red 仅当满足导致tomato.png的条件时,才会发生NameError:当我将鼠标悬停在番茄图像上时,即颜色为红色

If I write load(tomato) instead of with "" , NameError comes up as soon as I run the code, and highlights load(tomato) instead of gamedisplay.blit(tomato) as for with load("tomato") . 如果我写load(tomato)而不是用"" ,那么我在运行代码时就会出现NameError,并与load("tomato")一样突出显示load(tomato)而不是gamedisplay.blit(tomato) load("tomato")

You do load the image by calling load("tomato") , but you ignore the return value. 您确实通过调用load("tomato")加载图像,但是忽略了返回值。 Try 尝试

tomato = load("tomato")

instead. 代替。

If you want to load so many images, use os.listdir and put all the images in the directory into a dictionary. 如果要加载这么多图像,请使用os.listdir并将目录中的所有图像放入字典中。 Also, use convert or convert_alpha after loading the images to improve the performance. 另外,在加载图像后使用convertconvert_alpha可以提高性能。

def load_images(path_to_directory):
    """Load images and return them as a dict."""
    image_dict = {}
    for filename in os.listdir(path_to_directory):
        if filename.endswith('.png'):
            path = os.path.join(path_to_directory, filename)
            key = filename[:-4]
            image_dict[key] = pygame.image.load(path).convert()
    return image_dict

If you want to load all images from subdirectories as well, use os.walk : 如果还要从子目录加载所有图像,请使用os.walk

def load_images(path_to_directory):
    """Load all images from subdirectories and return them as a dict."""
    images = {}
    for dirpath, dirnames, filenames in os.walk(path_to_directory):
        for name in filenames:
            if name.endswith('.png'):
                key = name[:-4]
                img = pygame.image.load(os.path.join(dirpath, name)).convert()
                images[key] = img
    return images

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM