我在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))
有没有办法让它显得“更短”?感谢
答案 0 :(得分:1)
使用列表和迭代:
git add -p
答案 1 :(得分: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))