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:
import random skins = { 'Common':'Knife', 'Uncommon':'Pistol', 'Rare':'Submachine Gun', 'Epic':'Automatic Rifle', 'Legendary':'Semi-Automatic Sniper Rifle' } print("Welcome to N/A") print("Input 'open' to open a chest.") n = input("> ") if n == "open": print(random.choice(skins))
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
from random import choices skins = { 'Common':'Knife', 'Uncommon':'Pistol', 'Rare':'Submachine Gun', 'Epic':'Automatic Rifle', 'Legendary':'Semi-Automatic Sniper Rifle' } weights = [0.4, 0.25, 0.2, 0.1, 0.05] print("Welcome to N/A") print("Input 'open' to open a chest.") n = input("> ") if n == "open": print(choices(list(skins.items()), weights))