如何在 PyGame 中加载多个图像? [英] How to load multiple images in PyGame?
问题描述
我需要在 pygame 中加载大约 200 张图像,以便在我的游戏中的各个点进行 blitted.我尝试为此编写一个函数,但一直返回 NameError: name 'tomato' is not defined
.
I need to load around 200 images in pygame to be blitted at various points in my game. I tried writing a function for this but kept coming back with NameError: name 'tomato' is not defined
.
所有图像名称都是加载图像的变量存储在:tomato = pygame.image.load("tomato.png")
All of the image names are what the variable of the loaded image is stored under: tomato = pygame.image.load("tomato.png")
使用数组会不会更好,如果是这样我该怎么做?
Would using an array be better, if so how would I do that?
代码:
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
位块传输的条件时才会发生 NameError:当我将鼠标悬停在番茄图像上时,即颜色为红色
The NameError occurs only when the condition leading to the blitting of tomato.png
is met: when I hover over the tomato image i.e. color red
如果我写 load(tomato)
而不是 ""
,一旦我运行代码就会出现 NameError,并突出显示 load(tomato)
而不是 gamedisplay.blit(tomato)
与 load("tomato")
一样.
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")
.
推荐答案
如果要加载这么多图片,请使用 os.listdir
并将目录中的所有图像放入字典中.此外,在加载图像后使用 convert
或 convert_alpha
以提高性能.
If you want to load so many images, use os.listdir
and put all the images in the directory into a dictionary. Also, use convert
or convert_alpha
after loading the images to improve the performance.
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
:
If you want to load all images from subdirectories as well, use 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
这篇关于如何在 PyGame 中加载多个图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!