如何舍入到Python中的特定值

2024-09-30 12:24:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在研究一种自动创建角色扮演游戏角色表的算法。在游戏中,你有一些属性,你可以把点数放进去以增加点数。但是,在某个值处,实际属性的值增加1需要2个点。从一定数量的点开始,每个属性的默认值为1

我有一个程序,随机分配点,但我不知道如何更改这些值(在字典中),以便在必要时四舍五入。在

例如,如果我在“强度”中加上3点,就可以得到“强度”值3(包括基数1)。但是,如果我加4分,我仍然应该只有4分。它需要5个点(加上基数1)才能得到5个值。然后再加2分得到6分,3分得到7分,3分得到8分。在

我当前用于分配属性的代码如下所示:

attributes = {}
row1 = ['strength', 'intelligence', 'charisma']
row2 = ['stamina', 'willpower']
row3 = ['dexterity', 'wits', 'luck']

def assignRow(row, p): # p is the number of points you have to assign to each row
    rowValues = {}
    for i in range(0, len(row)-1):
        val = randint(0, p)
        rowValues[row[i]] = val + 1
        p -= val
    rowValues[row[-1]] = p + 1
    return attributes.update(rowValues)

assignRow(row1, 7)
assignRow(row2, 5)
assignRow(row3, 3)

我想要的只是一个简单的函数,它以字典“attributes”为参数,并将每个属性的点数转换为它应该具有的正确值。在

也就是说,"strength": 4保持为"strength": 4,但是"wits": 6"下降到{},而{}下降到{}。在

我对词典的使用有点陌生,因此我通常采用的方法是:

^{pr2}$

没有效率或漂亮,但仍然是一个解决方案。但是,您不能在字典中循环索引,所以我不完全确定如何进行类似的操作。在

如有一般解释或功能,将不胜感激。在


Tags: 游戏字典属性valstrengthattributesrowrow1
3条回答

您可以使用dictionary.items()对元素进行循环 然后可以修改转换函数:

def convert(attributes):
    for key, value in attributes.items():
        # do your conversion on value here
        if value <= 4:
            continue # do nothing for this element
        elif value in (5, 6):
            value -= 1
        elif value in (7, 8):
            value -= 2
        elif value in (9, 10):
            value = 6
        elif value in (11, 12, 13):
            value = 7
        else:
            value = 8

        # to replace the value in the dictionary you can use
        attributes[key] = new_value

似乎bisection算法非常适合您的需要-始终对“投资”点进行排序和定义。创建带有参考点的数组,最好不要使用if的组合:

>>> from bisect import bisect
>>> points_to_invest = [1, 2, 3, 4, 6, 8, 10, 13]
>>> bisect(points_to_invest, 1)
1
>>> bisect(points_to_invest, 4)
4
>>> bisect(points_to_invest, 5)
4
>>> bisect(points_to_invest, 6)
5

这种方法将为您将来提供更容易维护的方法

比您的“转换”功能少一点空间,但仍然需要人工:

p_to_v = {1:1, 2:2, 3:3, 4:4, 5:4, 6:5, 7:5, 8:6} # 'translator' dict, fill up further
input = {'strength':6, 'wits':8} # dict with stats and their points
output = dict((stat, p_to_v[point]) for stat, point in input.items()) # {'strength':5, 'wits':6}

如果你想让你的“翻译器”减少手工工作,更好地伸缩,那么你可以通过一些代码来预先生成它,这取决于你的点到值的逻辑。在

相关问题 更多 >

    热门问题