在猜年龄的基础上编写登录、注册方法,并且把猜年龄游戏分函数处理,如
- 登录函数
- 注册函数
- 猜年龄函数
- 选择奖品函数
#注册
def register():
'''注册'''
count=0
while count<3:
username_inp=input('请输入你的用户名:')
pwd_inp=input('请输入你的密码:')
re_pwd_inp=input('请再次输入你的密码:')
if not pwd_inp==re_pwd_inp:
print('两次密码不一致')
count+=1
continue
with open('user_info.txt','a',encoding='utf8') as fa:
fa.write(f'{username_inp}:{pwd_inp}\n')
fa.flush()
print('注册成功')
break
#登录
def login():
'''登录'''
username_inp = input('现在登录!!请输入你的用户名:')
pwd_inp = input('请输入你的密码:')
with open('user_info.txt', 'r', encoding='utf8') as fr:
for user_info in fr:
username, pwd = user_info.split(':')
print(user_info.split(':'))
if username.strip() == username_inp and pwd.strip() == pwd_inp: # strip可以去掉两端的换行符
print('登录成功')
break
else:
print('登录失败')
#猜年龄
def guess_age():
'''猜年龄'''
age_count = 0
age=18
while age_count < 3:
age_inp = input('现在猜年龄抽奖,请输入你猜的年龄:')
if not age_inp.isdigit(): # 如果输入的不是纯数字
print('只能输入数字,请重新输入')
continue
age_inp_int = int(age_inp)
if age_inp_int == age:
print('猜中了,可以抽两次奖')
choice_prize()
break
elif age_inp_int > age:
print('猜大了')
else:
print('猜小了')
age_count += 1 # 玩成一次游戏次数加1
if age_count != 3:
continue
again_choice = input('你还想继续玩吗?继续请回复y,否则按其他任意键退出!')
if again_choice == 'y':
age_count = 0
#选奖品
def choice_prize():
'''选奖品'''
get_prize_dict = {} # 获取的奖品信息
prize_dict = {'0': '多拉爱梦', '1': '百宝箱', '2': 'python学习宝典', '3': '境外游资助费'}
print(prize_dict)
for i in range(2): # 猜中后的内循环
prize_choice = input('请输入你想要的奖品序号,如果不抽奖输入其他任意键退出!!')
if prize_choice not in prize_dict :
break
# 奖品信息放入购物车
prize = prize_dict[prize_choice]
if prize in get_prize_dict:
get_prize_dict[prize] += 1
else:
get_prize_dict[prize] = 1
print(f'恭喜你获得奖品:{prize}') # 字典按key取值
print(f'总共获得奖品为:{get_prize_dict}')
#开始游戏
def play():
'''开始游戏'''
register()
login()
guess_age()
play()
浙公网安备 33010602011771号