关于python的初学者问题

时间:2011-02-23 17:49:35

标签: python

以下代码没有执行我的预期,我无法弄清楚原因。我对python比较新,很困惑。两次我显示x.attributes他们都被设置为0.不应该rollStats()更新它们?

import random

def roll(size):
        return random.randint(1, size)

class lifeform:
        def __init__(self, name):
                self.name = name
                self.attributes = { 'STR': 0, 'DEX': 0, 'CON': 0, 'INT': 0, 'WIS': 0, 'CHA': 0, }

        def rollAttribute(self):
                # roll four 6sided di
                d1 = roll(6)
                d2 = roll(6)
                d3 = roll(6)
                d4 = roll(6)

                # discard lowest roll
                if d1 < d2 and d1 < d3 and d1 < d4:     total = d2 + d3 + d4
                elif d2 < d1 and d2 < d3 and d2 < d4:   total = d1 + d3 + d4
                elif d3 < d1 and d3 < d2 and d3 < d4:   total = d1 + d2 + d4
                else:                                   total = d1 + d2 + d3

                return total

        def rollStats(self):
                self.attributes['STR'] = self.rollAttribute()
                self.attributes['DEX'] = self.rollAttribute()
                self.attributes['CON'] = self.rollAttribute()
                self.attributes['INT'] = self.rollAttribute()
                self.attributes['WIS'] = self.rollAttribute()
                self.attributes['CHA'] = self.rollAttribute()
x = lifeform("test")
print x.attributes
x.rollStats()
print x.attributes

编辑:这是我得到的输出btw

$ python fight.py
{'DEX': 0, 'CHA': 0, 'INT': 0, 'WIS': 0, 'STR': 0, 'CON': 0}
{'DEX': 0, 'CHA': 0, 'INT': 0, 'WIS': 0, 'STR': 0, 'CON': 0}

(我最初在代码拼写错误“WIS”中写了“WIZ”,我纠正了,但问题仍然存在)

4 个答案:

答案 0 :(得分:2)

我也在每次运行中获得随机值。

至于样式,你可以大大缩小代码:

class lifeform:
    def __init__(self, name):
        self.name = name
        self.attributes = { 'STR': 0, 'DEX': 0, 'CON': 0, 'INT': 0, 'WIZ': 0, 'CHA': 0, }

    def rollAttribute(self):

        # roll four 6sided di
        dice = [roll(6) for i in range(4)]

        # discard lowest roll
        return sum(dice) - min(dice)

    def rollStats(self):
        for key in self.attributes:
            self.attributes[key] = self.rollAttribute()

答案 1 :(得分:1)

这不能回答你的问题,这只是一个侧面说明。我把它放在评论中,但我不能格式化。

我总是发现当你这样做时,dnd会更加优雅:

d1 = roll(6)
d2 = roll(6)
d3 = roll(6)
d4 = roll(6)

min = d1;
if d2 < min: min = d2
if d3 < min: min = d3
if d4 < min: min = d4

return d1 + d2 + d3 + d4 - min

答案 2 :(得分:0)

它应该,当我运行你的代码时,它确实。

> python temp.py
{'DEX': 0, 'CHA': 0, 'INT': 0, 'WIS': 0, 'STR': 0, 'CON': 0}
{'DEX': 17, 'CHA': 7, 'INT': 15, 'WIS': 12, 'STR': 15, 'CON': 7}

虽然注意你在初始化程序(WIZ不是WIS)中有Wisdom拼写错误的缩写,所以最初没有更新。除此之外,它对我来说很好。

答案 3 :(得分:0)

Python是一种编程语言,在非负整数矩阵中,小于邻接路径的元素的百分比将从第一个元素开始到最后一个元素是最少元素结束Vmjmv

相关问题