刚开始学python(3.2),有疑问。我创建了一些代码来创建一些统计数据(如健康、魔法等),并且数字是随机生成的。这是代码...
def stats ():
print ()
print ('Some text.')
done = False
while not done :
charname = input(str('What is the name of the character? '))
hp = random.randint(5,20)
mp = random.randint(4,20)
stre = random.randint(3,20)
agi = random.randint(3,20)
spd = random.randint(3,20)
wis = random.randint(3,20)
intel = random.randint(3,20)
cha = random.randint(3,20)
print (charname)
print ('HP:',hp)
print ('Mana:',mp)
print ('Strength:',stre)
print ('Agility:',agi)
print ('Speed:',spd)
print ('Wisdom:',wis)
print ('Intelligence:',intel)
print ('Charisma:',cha)
print ()
done = input('All done? yes/no ')
if( done == 'yes' ):
done = True
elif(done == 'no'):
done = False
while done :
print ()
print ('Now that your stats are done, you can go on your adventure!')
done = False
现在这很好用了,但是如果我想再次查看统计数据并保持之前随机生成的相同统计数据,我怎么能再次调用这个函数呢?
抱歉,如果问题有点不对。还是编程新手。
谢谢。
最佳答案
由于您是编程新手,这里有一些关于存储数据的不同方式的建议(无需实际为您编码)。
首先,定义一个Character
类,带有HP、法力等属性。我不知道你是否了解类,但是here's an intro .您可以使用各种技巧来避免必须明确写入 HP、法力等名称,但为了学习起见,目前最好手动完成这些操作。
然后 def
一个 random_character()
函数创建一个具有随机属性的 Character
对象,定义就像你现在做的那样,但是不是将它们保存在 Python 不知道彼此有任何关系的不同变量中,而是将它们放在一个 Character
中。
在Character
类中添加一个__str__
方法,这样如果char
是一个Character
,print(char)
打印出属性。
如果您希望能够跟踪字符,请使用 pickle
将其存储在文件中。
如果您对此有任何疑问,请尽管提问。 :)
关于python - 如何使用 python (3.2) 保存函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11588934/