我需要在 pygame 中加载大约 200 个图像,以便在游戏中的各个点进行位块传输。我尝试为此编写一个函数,但总是回来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()
仅当导致位块传送的条件时,才会发生 NameErrortomato.png
满足:当我将鼠标悬停在番茄图像上时,即红色
如果我写load(tomato)
而不是与""
,当我运行代码时,NameError 就会出现,并突出显示load(tomato)
代替gamedisplay.blit(tomato)
至于与load("tomato")
.
如果你想加载这么多图像,请使用os.listdir https://docs.python.org/3/library/os.html#os.listdir并将目录中的所有图像放入字典中。另外,使用convert
or convert_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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)