here is a piece of code i created to generate loot from a loot table where every object has a weight that decides how often it gets picked.
import random
def genLootFromTable(count=2,table=None):
if table:
tmp = []
out = []
for item in table:
itm = table[item]
t = [ item ] * itm
tmp += t
for c in range(count):
out += [random.choice(tmp)]
return out
the loot table used is a dictionary like this
loottable = {"stone":200,"stick":200,"Apple":50,"Super Rare Ring":1,"Silver Armor":10}
working example
import random
def genLootFromTable(count=2,table=None):
if table:
tmp = []
out = []
for item in table:
itm = table[item]
t = [ item ] * itm
tmp += t
for c in range(count):
out += [random.choice(tmp)]
return out
#--- testing start -----
loottable = {"stone":200,"stick":200,"Apple":50,"Super Rare Ring":1,"Silver Armor":10}
out = {}
loot = genLootFromTable(1000,loottable)
for item in loot:
if item in out:
out[item] += 1
else:
out[item] = 1
print(out)
#--- testing end -----
here the output shows the distribution over 1000 iterations
sample output: {‘stick’: 416, ‘stone’: 438, ‘Apple’: 124, ‘Super Rare Ring’: 2, ‘Silver Armor’: 20}