Dragoonknight Dragoonknight - 2 months ago 6
Python Question

How does one return a random number from a dictionary every time a key is called?

I am trying to create a weapon that provides random damage. I am doing so using an item database in the form

itemsList = {
1: {"name": "Padded Armor", "armor": 1, "value": 5, "class": "Light"},
2: {"name": "Leather Armor", "armor": 2, "value": 10, "class": "Light"},
....
19: {"name": "Dagger", "damage" : int(random.randrange(1, 4)), "value": 2, "Type": "Dagger"},
20: {"name": "Dagger + 1", "damage" : int(random.randrange(1, 4) + 1), "value": 200, "Type": "Dagger"},
21: {"name": "Dagger + 2", "damage" : int(random.randrange(1, 4) + 2), "value": 750, "Type": "Dagger"},
22: {"name": "Dagger + 3", "damage" : int(random.randrange(1, 4) + 3), "value": 2000, "Type": "Dagger"}
}


Every time I attempt to call
"damage"
it just returns the same result. I understand that this is because the random number is generated one and then saved to that dictionary key.

How would I go about generating a random number every time damage is called?

Answer

You would store a function that generates a random number, not the random number itself, in the dictionary. (By the way, if your dictionary's keys are just sequential integers, consider using a list instead.)

from random import randrange    
itemsList = [
  {"name": "Padded Armor",  "armor": 1,  "value": 5, "class": "Light"},
  {"name": "Leather Armor",  "armor": 2,  "value": 10, "class": "Light"},
  ....
  {"name": "Dagger", "damage": lambda: randrange(1, 4), "value": 2, "Type": "Dagger"},
  {"name": "Dagger + 1", "damage": lambda: randrange(1, 4) + 1, "value": 200, "Type": "Dagger"},
  {"name": "Dagger + 2", "damage": lambda: randrange(1, 4) + 2, "value": 750, "Type": "Dagger"},
  {"name": "Dagger + 3", "damage": lambda: randrange(1, 4) + 3, "value": 2000, "Type": "Dagger"}
}

Then, you simply call the function to get an actual damage roll:

# Roll damage for a dagger + 3
damage = itemsList[22]["damage"]()
Comments