我在学校用蟒蛇做了一个小游戏。我也玩了很多runescape,所以我想加入一些机会,而不是仅仅强迫与怪物互动。我有四种不同的rarites (普通的1/5,不常见的1/15,等等)在给用户输入之前,我想在地牢的每个部分滚动以确定怪物的级别/难度。
我试图使它尽可能简单和考虑,通过把稀缺性和相应的范围放在字典中,然后使用for循环来从随机的滚动中捕捉稀缺性,但我搞不清楚。
rolls = {'common': list(range(1, 6)), 'uncommon': list(range(6, 21)), 'rare': list(range(21, 46)), 'omg': list(range(46, 146))}chance = random.randint(1,146)
for i in rolls:
if i == chance:
print(i)我尝试过循环的变体,我搜索了很多,现在我收到了一个错误: TypeError: unhashable type:'list‘
发布于 2022-10-31 23:26:04
结合以前的一些意见:
生成的代码可以如下所示:
from random import randint
# store for every label the end of the range
chance_labels = [
('common', 20),
('uncommon', 27),
('rare', 31),
('omg', 32)
]
# get the second value from the last tuple in chance_labels (32) is the max value to be 'rolled'
max_randint = chance_labels[-1][1]
chance = randint(1, max_randint)
# get the first tuple from chance_labels for which 'chance' is smaller than the end of the range
label = next(label for label, range_end in chance_labels if chance <= range_end)
print(f'{chance}: {label}')注意到,为了获得发生某事的1/5机会(在您的例子中是“常见的”),其他选项必须加到4/5。这意味着其他机会的总和必须大4倍。
https://stackoverflow.com/questions/74268495
复制相似问题