I’ve been trying to figure out how to recreate odds in python for a chest opening game thingy, but the random.choice
isn’t really considering different odds. The goal I’m trying to achieve is set certain odds for different “rarities”, like for example having 50% probability for getting an “Uncommon”.
Code example:
JavaScript
x
17
17
1
import random
2
3
skins = {
4
'Common':'Knife',
5
'Uncommon':'Pistol',
6
'Rare':'Submachine Gun',
7
'Epic':'Automatic Rifle',
8
'Legendary':'Semi-Automatic Sniper Rifle'
9
}
10
11
12
print("Welcome to N/A")
13
print("Input 'open' to open a chest.")
14
n = input("> ")
15
if n == "open":
16
print(random.choice(skins))
17
Advertisement
Answer
My advice is to use Random choice() method since it allows you to make a list where you can specify probability for each element. https://www.w3schools.com/python/ref_random_choices.asp
JavaScript
1
15
15
1
from random import choices
2
skins = {
3
'Common':'Knife',
4
'Uncommon':'Pistol',
5
'Rare':'Submachine Gun',
6
'Epic':'Automatic Rifle',
7
'Legendary':'Semi-Automatic Sniper Rifle'
8
}
9
weights = [0.4, 0.25, 0.2, 0.1, 0.05]
10
print("Welcome to N/A")
11
print("Input 'open' to open a chest.")
12
n = input("> ")
13
if n == "open":
14
print(choices(list(skins.items()), weights))
15