在字典中存储多个图像文件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在字典中存储多个图像文件相关的知识,希望对你有一定的参考价值。

我在python方面相对缺乏经验,并且正在为学校项目编写射击游戏。我试图去除一些保存图像的变量:

wavetransition=pygame.image.load("TransitionScreen.png")
wavetransition=pygame.transform.scale(wavetransition,(WIDTH,HEIGHT))
wavetransition2=pygame.image.load("TransitionScreen1.png")
wavetransition2=pygame.transform.scale(wavetransition2,(WIDTH,HEIGHT))
wavetransition3=pygame.image.load("TransitionScreen2.png")
wavetransition3=pygame.transform.scale(wavetransition3,(WIDTH,HEIGHT))
wavetransition4=pygame.image.load("TransitionScreen3.png")
wavetransition4=pygame.transform.scale(wavetransition4,(WIDTH,HEIGHT))
wavetransition5=pygame.image.load("TransitionScreen4.png")
wavetransition5=pygame.transform.scale(wavetransition5,(WIDTH,HEIGHT))

这些图像用作游戏中各级之间的过渡屏幕。然后在random.randrange()变量中调用它们:

rander=random.randrange(1,4)#Just For These Numbers To Redefine
if rander2==1:#The Random Backgrounds Displayed On The Wave Screen
      screen2.blit(wavetransition,(0,0))
if rander2==2:
      screen2.blit(wavetransition2,(0,0))
if rander2==3:
      screen2.blit(wavetransition3,(0,0))
if rander2==4:
      screen2.blit(wavetransition4,(0,0))
if rander2==5:
      screen2.blit(wavetransition5,(0,0))

有没有办法让它看起来“更短”?谢谢

答案

使用列表和迭代:

# image paths
img_paths = ["TransitionScreen.png", "TransitionScreen1.png", ...]

wavetransitions = []
for img_path in img_paths:
    # loads, resizes and adds image to wavetransitions list
    img = pygame.image.load(img_path)
    img = pygame.transform.scale(img, (WIDTH, HEIGHT))
    wavetransitions.append(img)

# as rander2 is the index+1 of the image, you can simply do
screen2.blit(wavetransitions[rander2 - 1], (0, 0))
另一答案

您可以使用list用于图像,使用dict用于wavetransitions

import re
import random

images = ["TransitionScreen0.png",  # Note, added 0 to the filename
          "TransitionScreen1.png",
          "TransitionScreen2.png",
          "TransitionScreen3.png",
          "TransitionScreen4.png"]

wavetransitions = dict()

for image in images:
    m = re.search(r'(\d+)$', image.split('.')[0]).group(0)
    key = "wavetransition" + m  # m is the number that ends the name of image
    value = pygame.image.load(image)
    value = pygame.transform.scale(value, (WIDTH, HEIGHT))
    wavetransitions[key] = value

wavetransitions_keys = wavetransitions.keys()

screen2.blit(wavetransitions[random.choice(wavetransitions_keys)], (0, 0))

以上是关于在字典中存储多个图像文件的主要内容,如果未能解决你的问题,请参考以下文章

Python代码阅读(第19篇):合并多个字典

将多个数据文件组合成 np.arrays,存储在字典中

如何在来自 Firebase 存储的片段 ImageView 中显示图像

如何将 r ggplot 图存储为 html 代码片段

在python中将多个边界框存储为列表

如何使用 phalcon 上传多个图像并将其名称存储在数据库中?