如何创建帐户来存储信息?

时间:2014-01-11 22:27:53

标签: python-2.7 passwords username text-based

我目前正在创建一个带有游戏币的基于文本的游戏,我希望用户能够存储他们的信息,以便他们以后可以登录。如果没有连接到互联网,这可能吗?

1 个答案:

答案 0 :(得分:0)

在我发现泡菜之前,我被困在这个问题上一个星期。

加载信息

import pickle
from getpass import getpass

username = raw_input('What would you like your username to be?  ')
username2 = raw_input('Please enter the same username again: ')
while username != username2:
    print 'The usernames do not match.'
    username = raw_input('What would you like your username to be?  ')
    username2 = raw_input('Please enter the same username again: ')
pword = getpass("What would you like your password to be?  ")
pword2 = getpass("Please reenter the password: ")
while pword != pword2:
    print 'The passwords do not match'
    pword = getpass('What would you like your password to be?  ')
    pword2 = getpass('Please reenter the password: ')
money_left = 0
logininfo = [username, pword, money_left]
pickle.dump(logininfo, open( "%s.p" %username, "wb"))
print 'Your username is %s, and your password is %s. You have $%d ingame money.' % (username, pword, money_left)

检索信息

import pickle
from getpass import getpass    

login = raw_input('Enter your username')
password = getpass("Enter your password: ")
if pickle.load(open("%s.p"%login, "rb"))[1] == password:
    username = pickle.load(open("%s.p"%login, "rb"))[0]
    pword = pickle.load(open("%s.p"%login, "rb"))[1]
    money_left = pickle.load(open("%s.p"%login, "rb"))[2]
    print 'You have successfully logged in as %s and you have $%d ingame money.' %(login, money_left)

这应该有效,对我有用。 getpass是可选的,但它会在您输入密码时阻止字符回显。您还可以更改'money_left'的金额。这基本上创建了一个名为“%s.p”%username的文件。因此,如果您的用户名是pickler,它将创建一个名为pickler.p的文件。