每次调用时,如何让 Python 3 从列表中随机选择一个项目?我有两个需要执行此操作的功能。我已经尝试过 item = random.randint() 和 item = random.choice(),但那些只会将其随机化一次然后将其存储到 item 中。
这是两个函数。使用函数 1,我需要在每次调用它时随机化该项目,因此玩家每次都会获得一个随机项目。对于功能 2,我需要玩家和老鼠的攻击在我选择的数字内随机化。所以每当玩家攻击时,它在 10 到 30 之间,而当老鼠攻击时,它在 10 到 15 之间。它必须每回合都这样做。
这可能吗?
功能 1。
def chest(sector):
item = random.choice(items)
print("You see a chest, you unlock it and inside is '{0}'".format(item))
print()
if item in inventory:
print("You already have a {0}".format(item))
item_take = input("Do you wish to take the '{0}'?: ".format(item)).lower()
if item_take == ("yes"):
inventory.append(item)
if item == "Armor":
player["hp"] = 150
print("The {0} has been added to your inventory!".format(item))
sector()
else:
print("You don't take the '{0}'!".format(item))
print()
sector()
功能2。
player = dict(
name = " ",
att = random.randint(10, 30),
hp = 100,)
rat = dict(
name = "Rat",
att = random.randint(10, 15),
hp = 20,)
def attack(player, enemy):
firstAtt = random.randint(1, 2)#Player = 1, Enemy = 2. Checks to see who goes first.
if firstAtt == 1:
while player["hp"] > 0 and enemy["hp"] > 0:
enemy["hp"] = enemy["hp"] - player["att"]
print("You have dealt {0} damage to the {1}!".format(player["att"], enemy["name"]))
if enemy["hp"] <= 0:
print()
print("You have killed the {0}".format(enemy["name"]))
print("You have {0}HP left.".format(player["hp"]))
break
player["hp"] = player["hp"] - enemy["att"]
print("The {0} has dealt {1} damage to you!".format(enemy["name"], enemy["att"]))
if player["hp"] <= 0:
print()
print("The {0} has killed you!".format(enemy["name"]))
break
elif firstAtt == 2:
while player["hp"] > 0 and enemy["hp"] > 0:
player["hp"] = player["hp"] - enemy["att"]
print("The {0} has dealt {1} damage to you!".format(enemy["name"], enemy["att"]))
if player["hp"] <= 0:
print()
print("The {0} has killed you!".format(enemy["name"]))
break
enemy["hp"] = enemy["hp"] - player["att"]
print("You have dealt {0} damage to the {1}".format(player["att"], enemy["name"]))
if enemy["hp"] <= 0:
print()
print("You have killed the {0}".format(enemy["name"]))
print("You have {0}HP left.".format(player["hp"]))
break