如何导入随机,所以我可以在我的函数中使用random.choice

时间:2017-11-19 00:58:17

标签: python function import

我的朋友和我正在制作基于文本的冒险游戏。

我们试图制作一个使用random.choice的掉落功能来选择掉落的装备是常见的,不常见的还是罕见的。

我一直在研究这个问题,但是当我打电话时,我似乎无法让它工作。

from random import *
def drop_get():
com_boots = 2 #speed
com_sword = 3 #attack
com_chest = 3 #health
uncom_boots = 4 #speed
uncom_sword = 6 #attack
uncom_chest = 6 #health
rare_boots = 6 #speed
rare_sword = 9 #attack
rare_chest = 9 #health

drop = random.choice(['Common','Common','Common','Common','Common','Common','Common','Common','Common','Common','Uncommon','Uncommon',
                  'Uncommon','Uncommon','Uncommon','Rare'])

print(drop)
if drop == "Common":
    print("Dang u got bad drop")
elif drop == "Uncommon":
        print("This drop aight")
else:
            print("Noicer u got good drop")

if drop == "Common":
    receive_drop = random.choice(["CommonChest", "CommonSword", "CommonBoots"])
elif drop == "Uncommon":
    receive_drop = random.choice(["UncommonChest", "UncommonSword", "UncommonBoots"])
else:
    receive_drop = random.choice(["RareChest", "RareSword", "RareBoots"])
    print("You have gotten", receive_drop)

    if receive_drop == "CommonChest":
        return com_chest
    elif receive_drop == "CommonBoots":
        return com_boots
    elif receive_drop == "CommonSword":
        return com_sword
    elif receive_drop == "UncommonSword":
        return uncom_sword
    elif receive_drop == "UncommonChest":
        return uncom_chest
    elif receive_drop == "UncommonBoots":
        return uncom_boots
    elif receive_drop == "RareBoots":
        return rare_boots
    elif receive_drop == "RareSword":
        return rare_sword
    elif receive_drop == "RareChest":
        return rare_chest
    drop_get(receive_drop)
drop_get()

1 个答案:

答案 0 :(得分:0)

有可能无法理解缩进,请尝试:

from random import choice

然后总是像这个例子一样调用选择函数:

drop = choice(['Common','Common','Common','Common','Common','Common','Common','Common','Common','Common','Uncommon','Uncommon', 'Uncommon','Uncommon','Uncommon','Rare'])

<强>解释
当您使用from random import choice时,您只需导入choice和许多其他功能。它不会同时导入模块的名称(例如random.choice),它只导入函数的名称,因此调用random.choice失败,但只调用choice有效。

使用关键字导入时会发生这种情况。如果您只是import random,那么您可以调用random.choice

之类的内容

<强>加成: 完全可以使用from random import *工作,但这是一个不好的做法。如果可能的话,尽量保持简单,只需导入您正在使用的方法。如果您不需要choice以外的任何内容,则不要导入任何其他内容(*会导入randintrandrange以及许多不需要的内容。