我如何使用一个变量的值在 python 中调用另一个变量?

How can i use the value of one variable to call another in python?

所以我在 pygame 工作,现在,确保一切都在屏幕上正确位置的唯一方法是检查每个可能的位置,直到找到适合图片的位置我正在尝试。然后它对下一张图片执行相同的操作,直到所有内容都加载完毕。

因为pygame每秒运行几行,我的代码需要尽可能短。

我想知道我是否可以使用我的 dessert_rand 变量,并根据它的值直接在语句中使用它来调用某个变量。例如:

screen.blit(wood, (spot_(wood_rand)x, spot_(wood_rand)y).

我知道格式不正确,但这是我想做的事情的总体思路。它可以让我将目前需要 12 行的内容缩短到 1 行。

    wood_rand = randint(1,6)

    spot_1x = 0
    spot_1y = 200

    spot_2x = 100
    spot_2y = 350

    spot_3x = 300
    spot_3y = 350

    spot_4x = 400
    spot_4y = 200

    spot_5x = 300
    spot_5y = 50

    spot_6x = 100
    spot_6y = 50

    spot_7x = 200
    spot_7y = 200

    #Wondering if there's a way to make this all shorter...

    #Somthing like this would work.
    #screen.blit(dessert, (spot_(dessert_rand)x, spot_(dessert_rand)y)

    if wood_rand == 1:
        screen.blit(wood, (spot_1x, spot_1y))
    elif wood_rand == 2:
        screen.blit(wood, (spot_2x, spot_2y))
    elif wood_rand == 3:
        screen.blit(wood, (spot_3x, spot_3y))
    elif wood_rand == 4:
        screen.blit(wood, (spot_4x, spot_4y))
    elif wood_rand == 5:
        screen.blit(wood, (spot_5x, spot_5y))
    elif wood_rand == 6:
        screen.blit(wood, (spot_6x, spot_6y))

你知道列表吗?看起来你可以有一个包含元组的 spot 列表:

spot = [(0, 200), (100, 350), ...]

然后您可以将整个 if-elseif 链替换为:

screen.blit(wood, spot[wood_rand - 1])

注意 - 1:Python 中的列表是从 0 开始的。随机化时最好考虑到这一点:

wood_rand = randint(0,5)
screen.blit(wood, spot[wood_rand])

(顺便说一下,dessert vs. desert,有些东西告诉我你指的是后者。)

如果您有七张图片并且您想将它们随机分配到七个不同的屏幕位置,请将您的位置放入列表中的元组中,然后使用 random.shuffle 将它们随机化:

import random
spots = [(0, 200), (100, 350), (300, 350), (400, 200), (300, 50), (100, 50), (200, 200)]
spots = random.shuffle(spots)

然后你可以简单地将图像一个接一个地放置在它们的位置:

screen.blit(wood, spots[0]) 
screen.blit(brick, spots[1])
screen.blit(wheat, spots[2])

等等

或更简洁(更多'Pythonic'):

images = [wood, brick, wheat, image4, image5, image6, image7]

for i, image in enumerate(images):
    screen.blit(image, spots[i])