-5

I'm making a code in which there is suppose, a box, and when you open the box you will either get a weapon that is common, uncommon, rare or legendary. But the problem is all the weapons have the same chance of occurring so how do I change the code so that it's more difficult for rarer weapons to spawn?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Sho
  • 1
  • 1

2 Answers2

3

python 3.x:

You can use random.choices and supply a distribution for the randomness:

import random

things = ["common","rare","epic"]
chance = [90,9,1]

results = random.choices(things,chance,k=1000)

from collections import Counter
print(Counter(results))

Output:

Counter({'common': 921, 'rare': 75, 'epic': 4})

Distributions can be absolute or cumulative - absolute ones are internally converted into cumulativ ones. See the doku

I use collections.Counter to count the resulting 1000 random draws.


python 2.x:

You can create a list with the correct amount of things in it and draw via random.choice in a loop (no random.choices for you, sorry):

things = ["common"]*90 + ["rare"]*9 + ["epic"]

thing = random.choice(things)  # only 1 item - loop if need more

There are several not-quite dupes for this:

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0

Numpy can help you with that, the p value is the probability and the sum must be 1.

import numpy as np
np.random.choice(('common', 'uncommon', 'rare' , 'legendary'), p=[0.4, 0.35, 0.2, 0.05])

In the example I added Counter to show the occurrence of each item.

from collections import Counter
import numpy as np

item = []
for _ in range(1,100):
    item.append(np.random.choice(('common', 'uncommon', 'rare' , 'legendary'), p=[0.4, 0.35, 0.2, 0.05]))

print(Counter(item))
Frans
  • 799
  • 6
  • 7
  • [numpy.random.choice(a, size=None, replace=True, p=None)](https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.random.choice.html) ... why not simply give a size of 100 ? – Patrick Artner Jan 21 '19 at 08:17
  • @Patrick. You're right, for the example even shorter. – Frans Jan 21 '19 at 08:27