我需要在pygame中加载大约200个图像,以便在我的游戏中的不同点进行blitted。我试着为此编写了一个函数,但总是返回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()只有当我将鼠标悬停在番茄图像上时(即红色),NameError才会发生,这会导致tomato.png的闪光
如果我编写load(tomato)而不是"",那么只要我运行代码,NameError就会出现,并突出显示load(tomato)而不是gamedisplay.blit(tomato),就像使用load("tomato")一样。
发布于 2017-05-02 16:35:13
您可以通过调用load("tomato")加载图像,但忽略返回值。试一试
tomato = load("tomato")而不是。
发布于 2017-05-02 20:20:24
如果您想加载这么多图像,请使用os.listdir并将目录中的所有图像放入字典中。此外,请在加载图像后使用convert或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 imageshttps://stackoverflow.com/questions/43732487
复制相似问题