猜年龄
在猜年龄的基础上编写登录、注册方法,并且把猜年龄游戏分函数处理,如
- 登录函数
- 注册函数
- 猜年龄函数
- 选择奖品函数
# 程序的基本流程
'''
奖励物品存放在文件price.txt
登录和注册的用户名和密码都放在age_db.txt
用户可以选择执行的模式:
[1] 注册
[2] 登录
[3] 猜年龄
指定未登录的用户不能进行猜年龄游戏
给定年龄(随机18-60),用户可以猜三次年龄
年龄猜对,让用户选择两次奖励
用户选择两次奖励后会将奖励列表返回并打印,然后退出
'''
def register():
"""注册函数"""
name = input('请输入用户名:')
pwd = input('请输入密码:')
with open(r'C:Users青柠Desktop正课age_db','at',encoding='utf8') as f:
f.write(f'{name}:{pwd}|')
print('注册成功,请登录!')
def login(name,pwd):
"""登录函数"""
with open(r'C:Users青柠Desktop正课age_db','rt',encoding='utf8') as f:
msg = f.read()[:-1].split('|')
dic = {}
for i in msg:
i = i.split(':')
dic[i[0]] = i[1]
if name in dic.keys() and pwd == dic[name]:
print('登陆成功!')
else:
print('登陆失败!')
def open_file():
"""打开礼品列表文件"""
price = open(r'C:Users青柠Desktop正课price', 'r', encoding='utf8').read()
price = eval(price) # type:dict
return price
def gift_choose():
"""猜对后选择礼物部分"""
dic = {}
for i in range(1, 3):
for k, v in price.items():
print(k, v)
price_in = input('恭喜你猜对了,您可以获得两份自选礼品,请输入相应礼品编号:')
if not price_in.isdigit():
print("想要礼物吗?想要就好好输入编号")
continue
else:
price_in = int(price_in)
print(f'您获得了第{i}份礼品:{price[price_in]}')
if price[price_in] in dic:
dic[price[price_in]] += 1
else:
dic[price[price_in]] = 1
return dic
def game(age_in):
"""猜年龄主要核心代码"""
import random
age = random.randint(1, 5)
count = 0
while count < 3:
if not age_in.isdigit():
print('认真的输入数字好吗亲!')
continue
age_in = int(age_in)
if age_in == age:
print('你个呆逼居然猜中了!')
gift = gift_choose()
print(gift)
break
elif age_in > age:
print('傻屌,猜的太大了吧!')
elif age_in < age:
print('牛逼,你这猜的也太小了!')
continue
price = open_file()
print('''
[1] 注册
[2] 登录
[3] 猜年龄
''')
flag = 0
for i in range(3):
s = input('请先输入操作编号[1][2][3]:')
if s == '1':
register()
if s == '2':
flag = 1
name_in = input('请输入用户名:')
pwd_in = input('请输入密码:')
login(name_in,pwd_in)
if s == '3':
if flag == 0:
print('还没登录,请先登录!')
continue
age_in = input('请输入猜想的年龄:')
game(age_in)