How can I get Python 3 to pick a random item from a list every time I call it?
I’ve got two functions that I need to do this with. I’ve tried item = random.randint() and item = random.choice(), but those only randomize it once then store it into item.
Here are the two functions.
With function 1, I need the item to randomize every time I call it, so the player will get a random item each time. For function 2, I need the the player and rats attacks to randomize within the numbers I’ve chosen. So whenever the player attacks, it’s between 10 and 30, and when the rat attacks it’s between 10 and 15. It has to do this each turn.
Is this possible?
Function 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()
Function 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
chest()is fine.For
attack(), turn theattelement into a function and then call it as appropriate.