gpt4 book ai didi

python - 有没有办法将 7 个随机变量的总和限制为 40?

转载 作者:行者123 更新时间:2023-12-05 08:29:49 24 4
gpt4 key购买 nike

我想为 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 个作为端点。

关于python - 有没有办法将 7 个随机变量的总和限制为 40?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67712245/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com