有没有办法将7个随机变量限制为40个?

我想为 Fallout New Vegas 的 SPECIAL 统计数据制作一个随机数,我已经构建了大部分代码,但有些情况下变量的总和超过/低于 40 的上限。

有没有办法限制它们,或者在总和低于或超过 40 的情况下,分配差异?

strength = random.randint(1, 10)
perception = random.randint(1, 10)
endurance = random.randint(1, 10)
charisma = random.randint(1, 10)
intelligence = random.randint(1, 10)
agility = random.randint(1, 10)
luck = random.randint(1, 10)
sum = strength + perception + endurance + charisma + intelligence + agility + luck

diff = 40 - sum
if diff < 0:
    diff = (diff * - 1)

print("=======================")
print("Strength:", strength)
print("Perception:", perception)
print("Endurance:", endurance)
print("Charisma:", charisma)
print("Intelligence:", intelligence)
print("Agility:", agility)
print("Luck:", luck)
print("Total:", sum)
print("Difference:", diff)
print("=======================")

回答

生成七个小于 40 的数字,而不是生成七个独立的随机数,并使用它们的差异来生成您的统计数据。

import random

STATMAX = 10

# generate six random numbers, sorted, to use as dividers in the range
rand_numbers = sorted(random.choices(range(40), k=6))
# calculate stats by taking the differences between them
stat_numbers = [(j - i) for (i, j) in zip([0] + rand_numbers, rand_numbers + [40])]
# for values higher than 10, dump the excess values into other stats
excess_points = sum(max(s - STATMAX, 0) for s in stat_numbers)
# also, drop stats above 10 before redistributing the points
stat_numbers = [min(s, STATMAX) for s in stat_numbers]
while excess_points > 0:
    idx = random.randint(0, len(stat_numbers) - 1)
    # this approach favors balanced stats by only adding one point at a time
    # an alternate approach would be to add as many points as possible, which
    # would favor imbalanced stats (i.e. minmaxing)
    if stat_numbers[idx] < STATMAX:
        stat_numbers[idx] += 1
        excess_points -= 1

strength, perception, endurance, charisma, intelligence, agility, luck = stat_numbers

您可以通过几种不同的方式来定制这种方法。例如,如果您希望滚动的总统计数据少于 40,则可以改为生成7 个随机数,并使用最后一个随机数而不是 40 作为端点。


以上是有没有办法将7个随机变量限制为40个?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>