试着做一次奇幻的邂逅

2024-04-18 16:20:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一个随机的奇幻邂逅。如果从主列表中随机选择,将带您进入第二个列表,这将带您进入第三个列表:

  • 废墟->;废墟->;庄园->;小屋

  • 废墟->;废墟->;乡村->;4-24间小屋:

大类=[“遗址”、“遗迹”等]

ruins = ['manor', 'village', 'city', etc]

manor = ['hut', 'hovel', 'hall', etc]
village = ['2-12 huts', '4-24 hovels', '6-36 cottages', etc]
city = ['7-42 huts and a citadel', '8-48 houses', etc]

所以我写了这个:

a = random.randint(0, 1)
b = random.randint(0, 5)
c = random.randint(0, 5)

    def place():
        if a == 0 and b == 0 and c == 0:
            result = 'the ruins of hut'
        elif a == 0 and b == 0 and c == 1:
            result = 'the ruins of a hovel'
        elif a == 0 and b == 0 and c == 2:
            result = 'the ruins of a hall'
        elif a == 0 and b == 0 and c == 3:
            result = 'the ruins of a villa'
        elif a == 0 and b == 0 and c == 4:
            result = 'the ruins of a cottage'
        elif a == 0 and b == 0 and c == 5:
            result = 'the ruins of a palace'

等等

它是有效的,我只有一百万条elif语句,我正在手工遍历每一个列表。是否有更好的方法自动生成结果?所以,当“废墟”被随机挑选时,它会进入“废墟”列表,然后随机挑选“庄园村庄或城市”,然后根据选择从这些子列表中挑选


1条回答
网友
1楼 · 发布于 2024-04-18 16:20:18

使用字典来做这件事。这里有一个例子

import random

places = {
    "ruins": {
        "manor": ["hut", "hovel", "hall"],
        "vilage": ["2-12 huts", "4-24 hovels", "6-36 cottages"],
        "city": ["7-42 huts and a  citadel", "8-48 houses"],
    },
    # Add other places.
}

place = random.choice(list(places.values()))
# {'manor': ['hut', 'hovel', 'hall'],
#  'vilage': ['2-12 huts', '4-24 hovels', '6-36 cottages'],
#  'city': ['7-42 huts and a  citadel', '8-48 houses']}

place = random.choice(list(place.values()))
# ['2-12 huts', '4-24 hovels', '6-36 cottages']

place = random.choice(place)
# '8-48 houses'

获取带有随机位置的消息的函数可能如下所示:

def place():
    place = random.choice(list(places.values()))
    place = random.choice(list(place.values()))
    place = random.choice(place)
    return "the ruins of {}".format(place)

还请记住,如果希望place在每次调用中获得一个随机位置,则需要在函数中使用一个随机值。在您的代码示例中,您会在函数之外获得随机值,因此place()函数将在每次调用时为您提供相同的消息

相关问题 更多 >