你能在列表中创建一个变量,然后调用它吗?

2024-10-03 13:31:20 发布

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

我的朋友和我正在制作一个python RPG游戏,我目前正在研究武器。我已经建立了一个系统,允许你掷骰造成伤害,并有机会像dnd一样命中。我使用列表来制作武器,然后使用print(exampleWeapon[0])来计算伤害,并将0改为1以获得命中机会。我尝试过使用一个变量,这样我可以用print(handAxe[dmg])更轻松地打印损坏输出,但我似乎无法在列表中创建一个变量,是否有办法做到这一点,或者必须坚持我的做法。 这是我的剧本

handAxe = [
    random.randint(1,6),
    random.randint(1,20),
]


print(handAxe[0])

print(handAxe[1])```

Tags: 游戏列表系统朋友randomrpg机会print
2条回答

您可以为此使用词汇表:

handAxe = {"dmg": random.randint(1, 6), "hit": random.randint(1, 20)}

然后分别通过handAxe["dmg"]handAxe["hit"]访问它们

但是,这意味着您每次都必须重新定义此变量。否则,即使在定义handAxe时会随机确定损坏的值,但此后将保持相同的值

一种更简洁的方法可能是使用面向对象编程,尤其是使用特定的属性

class HandAxe:
    @property
    def damage(self):
        return random.randint(1, 6)
    
    @property
    def hit(self):
        return random.randint(1, 20)

weapon = HandAxe()
print(weapon.damage)  # Prints 2
print(weapon.damage)  # Prints 1
print(weapon.hit)  # Prints 13

更干净的方法可能是使用static properties,这样就不必实例化HandAxe

您可以使用dictionaries

hand_axe = {'damage': random.randint(1, 6),
            'hit_chance': random.randint(1, 20)}
print(hand_axe['damage'], hand_axe['hit_chance'])

或者您可以使用namedtuples

from collections import namedtuple

weapon = namedtuple('Weapon', ['damage', 'hit_chance'])
hand_axe = weapon(damage=random.randint(1, 6),
                  hit_chance=random.randint(1, 20))
print(hand_axe.damage, hand_axe.hit_chance)

或者你可以写一个简单的class

相关问题 更多 >