1

我目前正在阅读“Python Programming for the Absolute Beginning 3rd Edition”。挑战之一是:

为角色扮演游戏编写 Character Creator 程序。应该给玩家一个 30 点的池用于四个属性:力量、健康、智慧和敏捷。玩家应该能够将积分池中的积分用于任何属性,并且还应该能够从属性中取出积分并将其放回池中。

一开始我是用变量写的

pool = 30
strength = 0
health = 0
wisdom = 0
dexterity = 0

本节是关于列表和字典的。所以我的问题是:以这种方式使用变量更好还是可以使用字典?如果是这样,效率更高吗?IE:

attributes = {
             "strength" : 0,
             "health" : 0,
             "wisdom" : 0, 
             "dexterity" : 0
             }
4

5 回答 5

4

简而言之:我会去找字典。

长话短说:这可能是直接深入研究面向对象编程的一个很好的例子。

#! /usr/bin/python3

class Character:
        class AbilityScoreOutOfBoundsException (Exception): pass

        def __init__ (self, name):
            self.name = name
            self.stats = {k: 1 for k in ['STR', 'DEX', 'WIS', 'INT'] }

        @property
        def strength (self): return self.stats ['STR']

        @property
        def dexterity (self): return self.stats ['DEX']

        @property
        def wisdom (self): return self.stats ['WIS']

        @property
        def intelligence (self): return self.stats ['INT']

        @strength.setter
        def strength (self, amount): self.setStat ('STR', amount)

        @wisdom.setter
        def wisdom (self, amount): self.setStat ('WIS', amount)

        @dexterity.setter
        def dexterity (self, amount): self.setStat ('DEX', amount)

        @intelligence.setter
        def intelligence (self, amount): self.setStat ('INT', amount)

        def setStat (self, which, amount):
            if amount < 1: raise Character.AbilityScoreOutOfBoundsException ('Beware hero! Thou wert about to smite thyself.')
            if self.total + amount - self.stats [which] > 30: raise Character.AbilityScoreOutOfBoundsException ('Beware hero! Thou shalt not grow too mighty.')
            self.stats [which] = amount

        @property
        def total (self): return sum (self.stats.values () )

        def __repr__ (self):
            return '{}\n{}'.format (self.name, '\n'.join ('{}{:>4}'.format (which, self.stats [which] ) for which in ['STR', 'DEX', 'WIS', 'INT'] ) )

a = Character ('Daggeroth')
a.strength += 9
a.dexterity += 9
a.wisdom += 5
a.intelligence += 3
print (a)
于 2013-07-29T02:12:16.853 回答
2

Python 中的字典是用哈希表实现的,所以这里的效率不是问题。使用属性字典更好,因为它更灵活。

例如,如果您想要多个字符,那么您可以简单地拥有一个属性字典列表。在这种情况下使用变量是不可维护的(你需要类似的东西player1Health, player2Health, ...)。

于 2013-07-29T02:07:34.320 回答
1

为了回答您的确切问题,Python 将变量存储在字典中,因此无论您将它们存储在字典中还是仅作为变量,它在程序运行方式方面都没有太大区别。

内置函数 globals() 和 locals() 返回存储变量集的字典,这些变量的相应名称为函数建议。

在 Python 程序中存储这些类型的变量的典型方法是构造一个类。我猜想在列表和字典之后的某个时候会涵盖类,所以这可能有点超前于书本。

这就是为此构造一个类的样子:

    class Character(object):
        def __init__(self):
            self.charisma = 0
            self.dexterity = 0
            self.wisdom = 0
            self.health = 0
            self.pool = 30

这有一些优点,但一个很容易看出的优点是它允许您轻松创建多个角色。

    alice = Character()
    bob = Character()

alice 和 bob 都使用与它们相关联的变量的自己的副本来启动。Python 还将类变量存储在字典中。所以 alice.charisma += 1 对 bob.charisma 没有任何影响。

alice.__dict__ 将是包含每个变量的 alice 副本的字典。

于 2013-07-29T02:08:31.630 回答
1

在这种情况下,我宁愿重视可读性而不是效率,因为您可能不会遇到任何与统计查找有关的性能问题。我会说字典看起来更好,因为

attributes['strength'] += 1

对我来说似乎更有条理。

于 2013-07-29T02:01:39.603 回答
0

我认为使用变量将是解决此问题的更有效方法。观察:

                    print(""""
                          1. strength \n
                          2 Health\n
                      3. wisdom\n
                      4. dexterity
                      5. remove 1 strength for point
                      6. remove 1 health for point
                      7. Remove 1 wisdom for point
                      8. remove 1 dexterity for point
                       """)

                         points=30
                         strength=0
                         health=0
                         wisdom=0
                         dexterity=0
                         default=1

                        while default:

                         choice=int(input("Select attributes that you want:"))
                            if choice==1:
                             strength+=1
                             points-=1
                             print("Strength:  ", strength, "\nHealth:  ", health, "\nWisdom:  ", wisdom, "\nDexterity: ")

                           elif choice==2:
                            health+=1
                            points-=1
                            print("Strength:  ", strength, "\nHealth:  ", health, "\nWisdom:  ", wisdom, "\nDexterity: ", dexterity)

                           elif choice==3:
                            wisdom+=1
                            points-=1
                            print("Strength:  ", strength, "\nHealth:  ", health, "\nWisdom:  ", wisdom, "\nDexterity: ", dexterity)

                          elif choice==4:
                           dexterity+=1
                           points-=1
                           print("Strength:  ", strength, "\nHealth:  ", health, "\nWisdom:  ", wisdom, "\nDexterity: ", dexterity)

                          elif oc==5:
                           strength-=1
                           points+=1
                           print("Strength:  ", strength, "\nHealth:  ", health, "\nWisdom:  ", wisdom, "\nDexterity: ", dexterity)

                         elif oc==6:
                          health-=1
                          points+=1
                          print("Strength:  ", strength, "\nHealth:  ", health, "\nWisdom:  ", wisdom, "\nDexterity: ", dexterity)

                         elif oc==7:
                          wisdowm-=1
                          points+=1
                          print("Strength:  ", strength, "\nHealth:  ", health, "\nWisdom:  ", wisdom, "\nDexterity: ", dexterity)

                        elif oc==8:
                         dexterity-=1
                         points+=1
                         print("Strength:  ", strength, "\nHealth:  ", health, "\nWisdom:  ", wisdom, "\nDexterity: ", dexterity)

当然你也可以使用字典,但是变量的想法要容易得多,而且编程就是要效率。

于 2013-07-29T18:17:36.120 回答