如何在Python中实现带自定义稀有度概率的开箱游戏抽卡功能
加权随机开箱功能实现方案
Python 3.6及以上版本可直接使用标准库random内置的random.choices()方法实现带权重的随机抽取,无需引入第三方依赖。
调整后的完整代码
import random # 稀有度对应道具 skins = { 'Common':'Knife', 'Uncommon':'Pistol', 'Rare':'Submachine Gun', 'Epic':'Automatic Rifle', 'Legendary':'Semi-Automatic Sniper Rifle' } # 自定义各稀有度权重,数值越高抽中概率越高,示例配置Uncommon概率为50% rarity_weights = { 'Common': 30, 'Uncommon': 50, 'Rare': 12, 'Epic': 7, 'Legendary': 1 } print("Welcome to N/A") print("Input 'open' to open a chest.") n = input("> ") if n == "open": # 按权重抽取稀有度,k=1表示抽取1个结果 rarity_list = list(rarity_weights.keys()) weight_list = list(rarity_weights.values()) drawn_rarity = random.choices(rarity_list, weights=weight_list, k=1)[0] # 输出对应道具 print(skins[drawn_rarity])
配置说明
- 你可随时修改
rarity_weights中的数值调整各稀有度的出货概率,权重数值不需要强制总和为100,方法会自动按照权重比例计算抽中概率。示例配置中Uncommon的权重占比刚好为50%,匹配你的需求。 - 原代码直接对字典使用
random.choice会抛出类型错误,因为该方法仅支持序列类型参数,上述修改也同时修复了该问题。 - 如果你使用的Python版本低于3.6,可手动实现累计区间判断逻辑:生成0到权重总和的随机整数,遍历稀有度累加权重,当累加值大于随机数时返回对应稀有度即可。
内容的提问来源于stack exchange,提问作者Jayotomix
相关产品推荐
相关产品推荐

