gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:52:29 25 4
gpt4 key购买 nike

我在 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))

关于python - 在字典中存储多个图像文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47885897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com