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

时间:2017-05-02 07:33:46

标签: python pygame

我需要在pygame中加载大约200张图片,以便在我的游戏中的各个点进行blitting。我尝试为此编写一个函数,但不断回复NameError: name 'tomato' is not defined

所有图像名称都是加载图像的变量存储在tomato = pygame.image.load("tomato.png")

下的内容

使用数组会更好吗,如果是这样,我该怎么做?

代码:

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

只有在满足导致tomato.png blitting的条件时才会出现NameError:当我将鼠标悬停在番茄图像上时,即红色

如果我写load(tomato)而不是"",我会在运行代码后立即出现NameError,并使用{{load(tomato)而不是gamedisplay.blit(tomato)突出显示load("tomato") 1}}。

2 个答案:

答案 0 :(得分:0)

您通过调用load("tomato")加载图像,但忽略了返回值。尝试

tomato = load("tomato")

代替。

答案 1 :(得分:0)

如果要加载这么多图像,请使用os.listdir并将目录中的所有图像放入字典中。此外,请在加载图片后使用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

如果您还要加载子目录中的所有图像,请使用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